v4.3.19-3: 도구 스키마 컨텍스트 스코핑 + web-ui/js 서브디렉토리 정리
- handle-chat.ts: excel/coder+shell/email/kakao/sqlite_query/image_edit/ image_read/run_command/news_search/pdf_*/schedule_job를 전용 앱 세션· 키워드·첨부 신호로 스코핑 (기존 weather/legal/pptx/dental/mind 패턴과 동일). 일반 대화 기준 도구 스키마 오버헤드 10,204→3,951 토큰(-61%) - desktop_*(10개, Windows 전용) 완전 제외 — 이 리눅스 서버에서 전량 실패 확인(tool_audit.log), process.platform 체크라 윈도우 이전시 자동 복구 - 채팅 기본 num_predict 4096→6000 (사고형 모델 빈 응답 여유분) - ollama-adapter.ts: 턴마다 prompt/completion 토큰을 token-usage.jsonl에 기록 (Ollama Cloud vs 종량제 API 비용 비교용) - web-ui/js/ 25개 파일을 app/·code-editor/·voice/·music/·claude-app/ 서브디렉토리로 재배치, 전체 참조 경로 갱신 - package.json build 스크립트에 dist 클린 단계 추가 Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0963231327
commit
f5ae095837
40 files changed
+7091
-6963
No files matched your search
+1
-1
@@ -8,7 +8,7 @@
|
||||
},
|
||||
"scripts": {
|
||||
"prepare": "npm run build",
|
||||
"build": "tsc",
|
||||
"build": "rm -rf dist && tsc",
|
||||
"dev": "tsx src/cli/index.ts",
|
||||
"start": "node dist/cli/index.js",
|
||||
"gateway": "tsx src/gateway/server-v2.ts",
|
||||
|
||||
@@ -207,7 +207,10 @@ async function handleChat(
|
||||
// coder_delete_lines, coder_list_files, shell, python_eval, and web_search to directly
|
||||
// inspect and fix code. Blocked tools are ones that don't make sense in
|
||||
// an editor context (browser automation, messaging, timers, presentations, etc.)
|
||||
const codeAiBlockedTools = new Set(['start_task', 'task_control', 'write_note', 'browser_open', 'browser_snapshot', 'browser_click', 'browser_fill', 'browser_press_key', 'browser_wait', 'browser_close', 'image_search', 'image_url', 'image_edit', 'image_info', 'image_read', 'weather_search', 'weather_map_screenshot', 'start_timer', 'send_message', 'send_telegram', 'kakao_send_message', 'create_presentation', 'edit_presentation', 'spawn_subagent', 'schedule_job', 'parse_schedule_pattern']);
|
||||
const codeAiBlockedTools = new Set(['start_task', 'task_control', 'write_note', 'browser_open', 'browser_snapshot', 'browser_click', 'browser_fill', 'browser_press_key', 'browser_wait', 'browser_close', 'image_search', 'image_url', 'image_edit', 'image_info', 'image_read', 'weather_search', 'weather_map_screenshot', 'start_timer', 'send_message', 'send_telegram', 'kakao_send_message', 'create_presentation', 'edit_presentation', 'spawn_subagent', 'schedule_job', 'parse_schedule_pattern',
|
||||
// desktop_* is Windows-only (desktop-tools.ts throws off process.platform); every call on
|
||||
// this Linux server fails, same reasoning as dormantDesktopTools below for the main filter.
|
||||
...(process.platform !== 'win32' ? ['desktop_screenshot', 'desktop_find_window', 'desktop_focus_window', 'desktop_click', 'desktop_drag', 'desktop_wait', 'desktop_press_key', 'desktop_type', 'desktop_set_clipboard', 'desktop_get_clipboard'] : [])]);
|
||||
const weatherToolNames = new Set(['weather_search', 'weather_airpollution', 'weather_openmeteo', 'weather_kma', 'weather_airkorea', 'weather_nasa_power', 'weather_era5', 'weather_cds', 'weather_cmip6']);
|
||||
const legalToolNames = new Set(['korean_law_search', 'korean_law_fetch', 'us_case_search']);
|
||||
const pptxToolNames = new Set(['create_presentation', 'edit_presentation']);
|
||||
@@ -215,6 +218,32 @@ async function handleChat(
|
||||
// papers → create_presentation), not in standalone chat — gate them the same way as the
|
||||
// pptx tools themselves rather than always loading 5 more schemas.
|
||||
const academicToolNames = new Set(['pubmed_search', 'pubmed_fetch', 'pubmed_fulltext', 'openalex_search', 'semantic_search']);
|
||||
// coder_* (10 tools) is the file-authoring toolkit for actual code/script work — it has its
|
||||
// own dedicated branch for isCodeAiSession (code.html) below, so this only affects the
|
||||
// general chat path (main app + app-specific tabs like ac_/wt_/lw_/dental_/mn_, none of which
|
||||
// are coding contexts). Ungated, it rode along on every single turn regardless of topic.
|
||||
const coderToolNames = new Set(['coder_read_file', 'coder_write_file', 'coder_overwrite_lines', 'coder_insert_lines', 'coder_delete_lines', 'coder_str_replace', 'coder_patch_file', 'coder_delete_file', 'coder_move_file', 'coder_list_files']);
|
||||
const hasCodeKeyword = /코드|스크립트|소스\s*코드|알고리즘|파이썬|python|javascript|typescript|자바스크립트|타입스크립트|프로그램|함수\b|클래스\b|디버그|버그\b|리팩터|refactor|\.py\b|\.js\b|\.ts\b|\.html\b|\.css\b|\.json\b|\.sh\b|\bcode\b|script|algorithm/i.test(message);
|
||||
// Email/kakao/db/image-edit — same story as excel: no dedicated skill toggle or app tab,
|
||||
// so gate purely on keyword. shell's own description tells the model to pair it with
|
||||
// coder_write_file, so it rides the same code-intent gate rather than its own.
|
||||
const emailToolNames = new Set(['email_list', 'email_read', 'email_send', 'email_search', 'email_delete']);
|
||||
const hasEmailKeyword = /이메일|메일\b|email|inbox|받은편지함/i.test(message);
|
||||
const hasKakaoKeyword = /카카오|kakao/i.test(message);
|
||||
const hasSqliteKeyword = /데이터베이스|sqlite|쿼리|query\b|\.db\b/i.test(message);
|
||||
const hasImageEditKeyword = /편집|보정|자르기|리사이즈|크롭|워터마크|배경\s*제거|필터|흑백|그레이스케일|스타일화|crop|resize|watermark|remove.?bg|grayscale|stylize/i.test(message);
|
||||
// news_search is the single biggest ungated schema (2,035 chars, mostly usage guidance for
|
||||
// its country/category/language params) yet was included on every turn regardless of topic.
|
||||
const hasNewsKeyword = /뉴스|시사|헤드라인|속보|기사\b|news|headline/i.test(message);
|
||||
// image_read (OCR) only makes sense once an actual image is in play — the upload flow
|
||||
// inserts attachments as markdown image links (), so detect that
|
||||
// directly instead of guessing at phrasing like the other keyword gates.
|
||||
const hasImageAttachment = /\.(png|jpe?g|webp|bmp|tiff?|gif)\b/i.test(message);
|
||||
const hasRunCommandKeyword = /실행해|열어줘|띄워줘|런칭|실행시켜|메모장|notepad|vscode|vs\s*code|launch\s+(app|the|notepad|vscode)/i.test(message);
|
||||
// Same shape as hasImageAttachment — pdf_read/pdf_extract_images (1,792 chars combined, the
|
||||
// biggest remaining pair) only make sense once a PDF is actually referenced.
|
||||
const hasPdfAttachment = /\.pdf\b|pdf\s*(파일|읽어|추출)/i.test(message);
|
||||
const hasScheduleKeyword = /예약|스케줄|반복|매일|매주|매월|정기적|주기적|cron|schedule|recurring/i.test(message);
|
||||
const meteorologistEnabled = isSkillEnabledForUser('meteorologist', userWorkspace);
|
||||
const lawyerEnabled = isSkillEnabledForUser('lawyer', userWorkspace);
|
||||
const presenterEnabled = isSkillEnabledForUser('presenter', userWorkspace);
|
||||
@@ -224,6 +253,11 @@ async function handleChat(
|
||||
// rode along on unrelated turns too. Mirrors the pptx pattern (skill + keyword) below.
|
||||
const hasWeatherKeyword = /날씨|기온|강수|미세먼지|대기질|태풍|기후|일기예보|장마|폭염|한파|자외선|황사|weather|forecast/i.test(message);
|
||||
const hasLegalKeyword = /법률|판례|소송|변호사|법원|법조문|조항|계약서|형법|민법|법령|legal|lawsuit|court|statute/i.test(message);
|
||||
// excel_read/excel_write have no dedicated skill toggle (accountant-app.html's persona is
|
||||
// page-local, not a registered skill) — gate on the accountant app tab (ac_ sessions) or an
|
||||
// explicit excel/spreadsheet keyword, same shape as the weather/legal gates above. Previously
|
||||
// ungated, so both tool schemas rode along on every single chat turn regardless of app.
|
||||
const hasExcelKeyword = /엑셀|xlsx|xls\b|스프레드시트|spreadsheet|excel/i.test(message);
|
||||
// Sub-agent/task-orchestration tools that tool_audit.log shows near-zero real usage for
|
||||
// (2026-05-04~2026-07-12: start_task/request_secondary_assist/subagent_spawn/
|
||||
// delegate_to_specialist/spawn_subagent = 0 calls; task_control/parse_schedule_pattern/
|
||||
@@ -239,6 +273,15 @@ async function handleChat(
|
||||
// probe swapping which schema set gets exposed. Excluding all 9 names covers both variants.
|
||||
// Re-enable by removing this set once browser automation is fixed / needed (e.g. home shopping).
|
||||
const dormantBrowserTools = new Set(['browser_open', 'browser_snapshot', 'browser_click', 'browser_fill', 'browser_press_key', 'browser_wait', 'browser_close', 'browser_scroll', 'browser_get_images']);
|
||||
// desktop_* (10 tools, ~2.7k of the tool-schema overhead) is Windows-only remote-desktop
|
||||
// control (mouse/keyboard/screenshot) — desktop-tools.ts itself throws "Desktop tools are
|
||||
// currently supported on Windows only." off process.platform, and tool_audit.log shows every
|
||||
// desktop_screenshot call ever made on this server failing with exactly that. Mirror the same
|
||||
// platform check here so the schemas aren't sent on a platform where every call is guaranteed
|
||||
// to fail (auto-recovers if this ever runs on Windows, unlike a hardcoded exclude).
|
||||
const dormantDesktopTools = process.platform !== 'win32'
|
||||
? new Set(['desktop_screenshot', 'desktop_find_window', 'desktop_focus_window', 'desktop_click', 'desktop_drag', 'desktop_wait', 'desktop_press_key', 'desktop_type', 'desktop_set_clipboard', 'desktop_get_clipboard'])
|
||||
: new Set<string>();
|
||||
// MCP database servers built for a specific dedicated app tab (dental-agent.html →
|
||||
// 'dental_' sessions, mind-app.html → 'mn_' sessions) — 62% of the tool-schema overhead
|
||||
// (12,124 of 19,531 tokens measured) came from these 3 servers × 8 sub-tools each, riding
|
||||
@@ -252,10 +295,12 @@ async function handleChat(
|
||||
// keyword (e.g. a follow-up "내일은?"), so always include the tools there.
|
||||
const isWeatherAppSession = /^wt_/.test(String(sessionId || ''));
|
||||
const isLawyerAppSession = /^lw_/.test(String(sessionId || ''));
|
||||
const isAccountantAppSession = /^ac_/.test(String(sessionId || ''));
|
||||
const skillToolFilter = (t: any) => {
|
||||
const name = String(t?.function?.name || '');
|
||||
if (dormantAgentTools.has(name)) return false;
|
||||
if (dormantBrowserTools.has(name)) return false;
|
||||
if (dormantDesktopTools.has(name)) return false;
|
||||
if (name.startsWith('mcp__dental-dict-sqlite__') && !isDentalAppSession) return false;
|
||||
if ((name.startsWith('mcp__psychotherapy-cases-sqlite__') || name.startsWith('mcp__psychiatry-cases-sqlite__')) && !isMindAppSession) return false;
|
||||
if (weatherToolNames.has(name) && !isWeatherAppSession && !(meteorologistEnabled && hasWeatherKeyword)) return false;
|
||||
@@ -264,8 +309,20 @@ async function handleChat(
|
||||
// other weather tools, not offered via the meteorologist skill in general chat.
|
||||
if (name === 'weather_map_screenshot' && !isWeatherAppSession) return false;
|
||||
if (legalToolNames.has(name) && !isLawyerAppSession && !(lawyerEnabled && hasLegalKeyword)) return false;
|
||||
if ((name === 'excel_read' || name === 'excel_write') && !isAccountantAppSession && !hasExcelKeyword) return false;
|
||||
if (coderToolNames.has(name) && !hasCodeKeyword) return false;
|
||||
if (name === 'shell' && !hasCodeKeyword) return false;
|
||||
if (pptxToolNames.has(name) && presenterEnabled && !hasPptxKeyword) return false;
|
||||
if (academicToolNames.has(name) && !hasPptxKeyword) return false;
|
||||
if (emailToolNames.has(name) && !hasEmailKeyword) return false;
|
||||
if (name === 'kakao_send_message' && !hasKakaoKeyword) return false;
|
||||
if (name === 'sqlite_query' && !hasSqliteKeyword) return false;
|
||||
if (name === 'image_edit' && !hasImageEditKeyword) return false;
|
||||
if (name === 'image_read' && !hasImageAttachment) return false;
|
||||
if (name === 'news_search' && !hasNewsKeyword) return false;
|
||||
if ((name === 'pdf_read' || name === 'pdf_extract_images') && !hasPdfAttachment) return false;
|
||||
if (name === 'schedule_job' && !hasScheduleKeyword) return false;
|
||||
if (name === 'run_command' && !hasRunCommandKeyword) return false;
|
||||
return true;
|
||||
};
|
||||
const tools = isBootStartupTurn
|
||||
@@ -1352,7 +1409,7 @@ OUTPUT FORMAT: When presenting 3+ items (emails, search results, lists), always
|
||||
temperature: 0.3,
|
||||
// num_ctx omitted → adapter sizes it to the prompt (up to the model's native
|
||||
// context_length) instead of a fixed 8192 that silently truncated big contexts.
|
||||
num_predict: (isCodeAiSession || isProjSession) ? 32768 : (needsLongOutput ? 32768 : 4096),
|
||||
num_predict: (isCodeAiSession || isProjSession) ? 32768 : (needsLongOutput ? 32768 : 6000),
|
||||
think: primaryThinkMode,
|
||||
model: effectiveModel,
|
||||
});
|
||||
|
||||
@@ -14,6 +14,22 @@ import type { LLMProvider, ChatMessage, ContentPart, ChatOptions, ChatResult, Ge
|
||||
|
||||
import { getConfig } from '../config/config';
|
||||
|
||||
// Lightweight JSONL usage log for cost-comparison analysis (Ollama Cloud flat-fee
|
||||
// vs metered APIs like Gemini). Append-only, one line per completed call.
|
||||
const USAGE_LOG_PATH = (() => {
|
||||
try { return path.join(getConfig().getConfigDir(), 'logs', 'token-usage.jsonl'); }
|
||||
catch { return null; }
|
||||
})();
|
||||
function logUsage(model: string, promptTokens: number, completionTokens: number) {
|
||||
if (!USAGE_LOG_PATH || (!promptTokens && !completionTokens)) return;
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(USAGE_LOG_PATH), { recursive: true });
|
||||
fs.appendFileSync(USAGE_LOG_PATH, JSON.stringify({
|
||||
ts: new Date().toISOString(), model, promptTokens, completionTokens,
|
||||
}) + '\n');
|
||||
} catch { /* non-fatal */ }
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a message's content for Ollama.
|
||||
* - String content is passed through unchanged.
|
||||
@@ -424,6 +440,7 @@ export class OllamaAdapter implements LLMProvider {
|
||||
const message = response?.message || { role: 'assistant', content: String(response?.response || '') };
|
||||
const hasThinking = !!(response?.thinking && String(response.thinking).length > 0);
|
||||
const _usage = { promptTokens: Number(response?.prompt_eval_count) || 0, completionTokens: Number(response?.eval_count) || 0, ctxWindow: modelCtx };
|
||||
logUsage(model, _usage.promptTokens, _usage.completionTokens);
|
||||
|
||||
// Mistral cloud sometimes embeds parallel tool calls in content instead of tool_calls.
|
||||
if (message.content && !message.tool_calls?.length) {
|
||||
@@ -602,6 +619,7 @@ export class OllamaAdapter implements LLMProvider {
|
||||
if (typeof (chunk as any).eval_count === 'number') completionTokens = (chunk as any).eval_count;
|
||||
}
|
||||
}
|
||||
logUsage(model, promptTokens, completionTokens);
|
||||
|
||||
message.content = fullContent || message.content || '';
|
||||
if (toolCalls.length > 0) {
|
||||
|
||||
@@ -136,7 +136,7 @@ body{background:var(--bg);color:var(--text);font-family:system-ui,sans-serif;dis
|
||||
#mob-backdrop{display:none !important;}
|
||||
}
|
||||
</style>
|
||||
<script src="../js/voice-utils.js"></script>
|
||||
<script src="../js/voice/voice-utils.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="ac-drop" id="drop-overlay">📊 Excel 파일을 드롭하세요</div>
|
||||
|
||||
@@ -212,6 +212,6 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="../js/claude-app.js"></script>
|
||||
<script src="../js/claude-app/claude-app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -677,7 +677,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="../js/code.js?v=20260721b"></script>
|
||||
<script src="../js/code-editor/code.js?v=20260721b"></script>
|
||||
<script>
|
||||
function mobCloseAll(){
|
||||
document.querySelector('.code-sidebar-wrap').classList.remove('mob-open');
|
||||
|
||||
@@ -232,7 +232,7 @@ body{background:var(--bg);color:var(--text);font-family:system-ui,sans-serif;dis
|
||||
.hash-btn{background:var(--panel-2);border:1px solid var(--line);border-radius:6px;padding:4px 10px;font-size:11px;color:var(--fg);cursor:pointer;transition:.15s;}
|
||||
.hash-btn:hover{background:var(--panel-3,#2a2a3a);border-color:#93c5fd;}
|
||||
</style>
|
||||
<script src="../js/voice-utils.js"></script>
|
||||
<script src="../js/voice/voice-utils.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
|
||||
+19
-8
@@ -1942,14 +1942,25 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="../js/voice-call.js"></script>
|
||||
<script src="../js/helpers-core.js"></script>
|
||||
<script src="../js/markdown.js"></script>
|
||||
<script src="../js/voice.js"></script>
|
||||
<script src="../js/media.js"></script>
|
||||
<script src="../js/files.js"></script>
|
||||
<script src="../js/chat-sse.js"></script>
|
||||
<script src="../js/app.js"></script>
|
||||
<script src="../js/voice/voice-call.js"></script>
|
||||
<script src="../js/app/helpers-core.js"></script>
|
||||
<script src="../js/app/markdown.js"></script>
|
||||
<script src="../js/app/voice.js"></script>
|
||||
<script src="../js/app/media.js"></script>
|
||||
<script src="../js/app/files.js"></script>
|
||||
<script src="../js/app/chat-sse.js"></script>
|
||||
<script src="../js/app/chat-sessions.js"></script>
|
||||
<script src="../js/app/chat-render.js"></script>
|
||||
<script src="../js/app/settings-provider.js"></script>
|
||||
<script src="../js/app/settings-agents.js"></script>
|
||||
<script src="../js/app/settings-channels.js"></script>
|
||||
<script src="../js/app/bg-tasks.js"></script>
|
||||
<script src="../js/app/schedules.js"></script>
|
||||
<script src="../js/app/integrations.js"></script>
|
||||
<script src="../js/app/error-panel.js"></script>
|
||||
<script src="../js/app/terminal.js"></script>
|
||||
<script src="../js/app/pptx-workflow.js"></script>
|
||||
<script src="../js/app/app.js"></script>
|
||||
|
||||
<!-- Code folder browser dropdown (fixed, rendered outside any overflow:hidden container) -->
|
||||
|
||||
|
||||
@@ -160,7 +160,7 @@ body{background:var(--bg);color:var(--text);font-family:system-ui,sans-serif;dis
|
||||
#mob-backdrop{display:none !important;}
|
||||
}
|
||||
</style>
|
||||
<script src="../js/voice-utils.js"></script>
|
||||
<script src="../js/voice/voice-utils.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
|
||||
@@ -161,7 +161,7 @@ body{background:var(--bg);color:var(--text);font-family:system-ui,sans-serif;dis
|
||||
#mob-backdrop{display:none !important;}
|
||||
}
|
||||
</style>
|
||||
<script src="../js/voice-utils.js"></script>
|
||||
<script src="../js/voice/voice-utils.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
|
||||
@@ -247,7 +247,7 @@ body{background:var(--bg);color:var(--text);font-family:system-ui,sans-serif;dis
|
||||
.mn-send:hover:not(:disabled){background:#6d28d9;}
|
||||
.mn-send:disabled{opacity:.5;cursor:not-allowed;}
|
||||
</style>
|
||||
<script src="../js/voice-utils.js"></script>
|
||||
<script src="../js/voice/voice-utils.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
|
||||
@@ -1351,7 +1351,7 @@ async function _ensureSpessa() {
|
||||
if (!window.SpessaSynth) {
|
||||
await new Promise((res, rej) => {
|
||||
const s = document.createElement('script');
|
||||
s.src = '/js/spessasynth.js';
|
||||
s.src = '/js/music/spessasynth.js';
|
||||
s.onload = res; s.onerror = () => rej(new Error('SpessaSynth 로드 실패'));
|
||||
document.head.appendChild(s);
|
||||
});
|
||||
@@ -1367,7 +1367,7 @@ async function _ensureSpessa() {
|
||||
_spessaSfBuf = await r.arrayBuffer();
|
||||
}
|
||||
|
||||
await _spessaCtx.audioWorklet.addModule('/js/spessasynth_processor.min.js');
|
||||
await _spessaCtx.audioWorklet.addModule('/js/music/spessasynth_processor.min.js');
|
||||
const { WorkletSynthesizer, Sequencer } = window.SpessaSynth;
|
||||
_spessaSynth = new WorkletSynthesizer(_spessaCtx);
|
||||
_spessaSynth.connect(_spessaCtx.destination); // AudioWorkletNode → output (the global connect-patch redirects this through the master FX chain)
|
||||
|
||||
@@ -176,7 +176,7 @@ body{background:var(--bg);color:var(--text);font-family:system-ui,sans-serif;fon
|
||||
#mob-tabbar{display:none !important;}
|
||||
}
|
||||
</style>
|
||||
<script src="../js/voice-utils.js"></script>
|
||||
<script src="../js/voice/voice-utils.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
|
||||
-6941
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,700 @@
|
||||
// bg-tasks.js — 하트비트 태스크 카드 + 백그라운드 태스크 패널(생성/일시정지/채팅/삭제).
|
||||
// extracted from app.js (v4.3.19-3 split).
|
||||
|
||||
let hbJobs = [];
|
||||
let hbConfig = { enabled: false, intervalMinutes: 30, activeHoursStart: 8, activeHoursEnd: 22 };
|
||||
let editingTaskId = null;
|
||||
|
||||
async function loadTasksFromServer() {
|
||||
try {
|
||||
const data = await api('/api/tasks');
|
||||
if (data.success) {
|
||||
hbJobs = data.jobs || [];
|
||||
hbConfig = data.config || hbConfig;
|
||||
renderHeartbeatPage();
|
||||
}
|
||||
} catch (err) { console.error('[HB] Load failed:', err); }
|
||||
}
|
||||
|
||||
function renderHeartbeatPage() {
|
||||
// Update topbar
|
||||
const dot = document.getElementById('hb-dot');
|
||||
const label = document.getElementById('hb-label');
|
||||
const meta = document.getElementById('hb-meta');
|
||||
const btn = document.getElementById('hb-toggle-btn');
|
||||
if (dot) dot.className = 'hb-status-dot ' + (hbConfig.enabled ? 'active' : '');
|
||||
if (label) label.textContent = hbConfig.enabled ? '하트비트 ON' : '하트비트 OFF';
|
||||
if (meta) meta.textContent = `Every ${hbConfig.intervalMinutes}m \u00b7 ${hbConfig.activeHoursStart}:00\u2013${hbConfig.activeHoursEnd}:00`;
|
||||
if (btn) { btn.textContent = hbConfig.enabled ? 'Pause' : 'Enable'; btn.className = 'hb-btn' + (hbConfig.enabled ? ' danger' : ' primary'); }
|
||||
|
||||
// Split jobs into sections
|
||||
const running = hbJobs.filter(j => j.status === 'running');
|
||||
const queued = hbJobs.filter(j => j.enabled && j.status !== 'running' && j.status !== 'completed' && j.status !== 'paused').sort((a,b) => a.priority - b.priority);
|
||||
const paused = hbJobs.filter(j => j.status === 'paused');
|
||||
const completed = hbJobs.filter(j => j.status === 'completed' || j.type === 'one-shot' && j.lastRun).slice(0, 15);
|
||||
|
||||
const empty = document.getElementById('hb-empty');
|
||||
if (empty) empty.style.display = hbJobs.length === 0 ? '' : 'none';
|
||||
|
||||
renderHBSection('hb-section-running', 'hb-running-cards', running, 'running');
|
||||
renderHBSection('hb-section-queued', 'hb-queued-cards', [...queued, ...paused], 'queued');
|
||||
renderHBSection('hb-section-scheduled', 'hb-scheduled-cards', queued.filter(j => j.schedule), 'scheduled');
|
||||
renderHBSection('hb-section-completed', 'hb-completed-cards', completed, 'completed');
|
||||
}
|
||||
|
||||
function renderHBSection(sectionId, cardsId, jobs, sectionType) {
|
||||
const section = document.getElementById(sectionId);
|
||||
const container = document.getElementById(cardsId);
|
||||
if (!section || !container) return;
|
||||
section.style.display = jobs.length > 0 ? '' : 'none';
|
||||
container.innerHTML = jobs.map(j => renderTaskCard(j, sectionType)).join('');
|
||||
}
|
||||
|
||||
function renderTaskCard(job, sectionType) {
|
||||
const statusClass = job.status === 'running' ? 'running' : job.status === 'completed' ? 'completed' : job.status === 'paused' ? 'paused' : '';
|
||||
const scheduleText = job.schedule ? cronToHuman(job.schedule) : (job.runAt ? 'One-shot: ' + new Date(job.runAt).toLocaleString() : 'Manual');
|
||||
const lastRunText = job.lastRun ? timeAgo(new Date(job.lastRun).getTime()) : 'Never';
|
||||
const nextRunText = job.nextRun ? new Date(job.nextRun).toLocaleTimeString('en-US', {hour:'2-digit',minute:'2-digit'}) : '-';
|
||||
const resultSnippet = job.lastResult ? (job.lastResult.length > 60 ? job.lastResult.slice(0,60)+'...' : job.lastResult) : '';
|
||||
const isOk = /^\s*HEARTBEAT_OK\s*$/i.test(job.lastResult || '');
|
||||
|
||||
return `<div class="hb-card ${statusClass}" data-job-id="${job.id}">
|
||||
<div class="hb-card-drag">${sectionType === 'completed' ? '' : '\u2261'}</div>
|
||||
<div class="hb-card-body">
|
||||
<div class="hb-card-name">${escHtml(job.name)}</div>
|
||||
<div class="hb-card-meta">
|
||||
<span>${scheduleText}</span>
|
||||
<span>Next: ${nextRunText}</span>
|
||||
<span>Last: ${lastRunText}</span>
|
||||
${resultSnippet && !isOk ? `<span style="color:var(--text);font-weight:600">${escHtml(resultSnippet)}</span>` : ''}
|
||||
${isOk ? '<span style="color:var(--ok)">\u2713 OK</span>' : ''}
|
||||
</div>
|
||||
</div>
|
||||
<div class="hb-card-actions">
|
||||
${job.status !== 'running' ? `<button class="hb-card-btn" onclick="runTaskNow('${job.id}')" title="Run now">\u25b6</button>` : '<span style="font-size:11px;color:var(--brand)">Running...</span>'}
|
||||
<button class="hb-card-btn" onclick="editTask('${job.id}')" title="Edit">\u270e</button>
|
||||
<button class="hb-card-btn" onclick="toggleTaskPause('${job.id}')" title="${job.status === 'paused' ? 'Resume' : 'Pause'}">${job.status === 'paused' ? '\u25b6' : '\u23f8'}</button>
|
||||
<button class="hb-card-btn danger" onclick="deleteTask('${job.id}')" title="Delete">\u2715</button>
|
||||
${job.sessionId ? `<button class="hb-card-btn" onclick="viewTaskSession('${job.sessionId}')" title="View response">\u2192</button>` : ''}
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function cronToHuman(expr) {
|
||||
if (!expr) return 'Manual';
|
||||
const p = expr.split(/\s+/);
|
||||
if (p.length !== 5) return expr;
|
||||
const [min, hr, dom, , dow] = p;
|
||||
if (min.startsWith('*/')) return `Every ${min.slice(2)}m`;
|
||||
if (hr === '*') return `Every minute`;
|
||||
if (dom === '*' && dow === '*') return `Daily at ${hr}:${min.padStart(2,'0')}`;
|
||||
const days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
|
||||
if (dow !== '*') return `${days[Number(dow)] || dow} at ${hr}:${min.padStart(2,'0')}`;
|
||||
return expr;
|
||||
}
|
||||
|
||||
async function toggleHeartbeatEnabled() {
|
||||
try {
|
||||
const data = await api('/api/tasks/config', { method: 'PUT', headers: {'Content-Type':'application/json'}, body: JSON.stringify({ enabled: !hbConfig.enabled }) });
|
||||
if (data.success) { hbConfig = data.config; renderHeartbeatPage(); }
|
||||
} catch (err) { console.error('[HB] Toggle failed:', err); }
|
||||
}
|
||||
|
||||
async function runTaskNow(id) {
|
||||
try { await api(`/api/tasks/${id}/run`, { method: 'POST' }); } catch {}
|
||||
}
|
||||
|
||||
async function deleteTask(id) {
|
||||
if (!confirm('Delete this task?')) return;
|
||||
try {
|
||||
await api(`/api/tasks/${id}`, { method: 'DELETE' });
|
||||
hbJobs = hbJobs.filter(j => j.id !== id);
|
||||
renderHeartbeatPage();
|
||||
} catch {}
|
||||
}
|
||||
|
||||
async function toggleTaskPause(id) {
|
||||
const job = hbJobs.find(j => j.id === id);
|
||||
if (!job) return;
|
||||
const newStatus = job.status === 'paused' ? 'scheduled' : 'paused';
|
||||
try {
|
||||
const data = await api(`/api/tasks/${id}`, { method: 'PUT', headers:{'Content-Type':'application/json'}, body: JSON.stringify({ status: newStatus, enabled: newStatus !== 'paused' }) });
|
||||
if (data.success) { Object.assign(job, data.job); renderHeartbeatPage(); }
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function viewTaskSession(sessionId) {
|
||||
// Switch to chat mode and open the automated session
|
||||
const session = chatSessions.find(s => s.id === sessionId);
|
||||
if (session) {
|
||||
setMode('chat');
|
||||
openSession(sessionId);
|
||||
}
|
||||
}
|
||||
|
||||
function openTaskModal(taskId) {
|
||||
editingTaskId = taskId || null;
|
||||
const job = taskId ? hbJobs.find(j => j.id === taskId) : null;
|
||||
const modal = document.getElementById('task-modal');
|
||||
modal.style.display = '';
|
||||
modal.innerHTML = `<div class="hb-modal-overlay" onclick="if(event.target===this)closeTaskModal()">
|
||||
<div class="hb-modal">
|
||||
<h3>${job ? 'Edit Task' : 'Add Task'}</h3>
|
||||
<label>Name</label>
|
||||
<input id="tm-name" value="${job ? escHtml(job.name) : ''}" placeholder="e.g. Check inbox for urgent emails">
|
||||
<label>Prompt (what the LLM should do)</label>
|
||||
<textarea id="tm-prompt" placeholder="e.g. Search for any urgent emails or messages I should know about">${job ? escHtml(job.prompt) : ''}</textarea>
|
||||
<label>Type</label>
|
||||
<select id="tm-type">
|
||||
<option value="recurring" ${!job || job.type==='recurring' ? 'selected' : ''}>Recurring (cron)</option>
|
||||
<option value="one-shot" ${job?.type==='one-shot' ? 'selected' : ''}>One-shot (run once)</option>
|
||||
</select>
|
||||
<label>Schedule (cron expression)</label>
|
||||
<input id="tm-schedule" value="${job?.schedule || '*/30 * * * *'}" placeholder="*/30 * * * * (every 30 min)">
|
||||
<div style="font-size:10px;color:var(--muted);margin-top:2px">Examples: */30 * * * * (every 30m), 0 9 * * * (daily 9am), 0 9 * * 1 (Mon 9am)</div>
|
||||
<div class="hb-modal-actions">
|
||||
<button class="hb-btn" onclick="closeTaskModal()">Cancel</button>
|
||||
<button class="hb-btn primary" onclick="saveTask()">Save</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function editTask(id) { openTaskModal(id); }
|
||||
|
||||
function closeTaskModal() {
|
||||
document.getElementById('task-modal').style.display = 'none';
|
||||
editingTaskId = null;
|
||||
}
|
||||
|
||||
async function saveTask() {
|
||||
const name = document.getElementById('tm-name').value.trim();
|
||||
const prompt = document.getElementById('tm-prompt').value.trim();
|
||||
const type = document.getElementById('tm-type').value;
|
||||
const schedule = document.getElementById('tm-schedule').value.trim();
|
||||
if (!name || !prompt) { alert('Name and prompt are required'); return; }
|
||||
try {
|
||||
if (editingTaskId) {
|
||||
const data = await api(`/api/tasks/${editingTaskId}`, { method: 'PUT', headers:{'Content-Type':'application/json'}, body: JSON.stringify({ name, prompt, type, schedule }) });
|
||||
if (data.success) {
|
||||
const idx = hbJobs.findIndex(j => j.id === editingTaskId);
|
||||
if (idx >= 0) hbJobs[idx] = data.job;
|
||||
}
|
||||
} else {
|
||||
const data = await api('/api/tasks', { method: 'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({ name, prompt, type, schedule }) });
|
||||
if (data.success) hbJobs.push(data.job);
|
||||
}
|
||||
closeTaskModal();
|
||||
renderHeartbeatPage();
|
||||
} catch (err) { alert('Failed to save: ' + err.message); }
|
||||
}
|
||||
|
||||
function updateHbNotifyLabel() {
|
||||
const on = document.getElementById('settings-hb-notify')?.checked;
|
||||
const label = document.getElementById('settings-hb-notify-label');
|
||||
if (label) label.textContent = on ? '알림 받기' : '알림 끄기';
|
||||
}
|
||||
|
||||
async function saveHbNotifyConfig() {
|
||||
const notifyEnabled = !!document.getElementById('settings-hb-notify')?.checked;
|
||||
try {
|
||||
const data = await api('/api/heartbeat/config', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ notifyEnabled }),
|
||||
});
|
||||
if (data?.success) {
|
||||
updateHbNotifyLabel();
|
||||
addProcessEntry('final', notifyEnabled ? '허트비트 알림 켜짐' : '허트비트 알림 꺼짐');
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
let bgtTasks = []; // all task records from server
|
||||
let bgtOpenTaskId = null; // currently open panel task id
|
||||
let bgtHeartbeatConfig = { enabled: true, interval_minutes: 10 };
|
||||
|
||||
function openNewBgTaskModal() {
|
||||
const modal = document.getElementById('bgt-new-task-modal');
|
||||
if (modal) { modal.style.display = 'flex'; document.getElementById('bgt-new-title').focus(); }
|
||||
}
|
||||
function closeNewBgTaskModal() {
|
||||
const modal = document.getElementById('bgt-new-task-modal');
|
||||
if (modal) modal.style.display = 'none';
|
||||
document.getElementById('bgt-new-title').value = '';
|
||||
document.getElementById('bgt-new-prompt').value = '';
|
||||
}
|
||||
async function submitNewBgTask() {
|
||||
const title = document.getElementById('bgt-new-title').value.trim();
|
||||
const prompt = document.getElementById('bgt-new-prompt').value.trim();
|
||||
if (!title || !prompt) { alert('제목과 작업 내용을 입력해주세요.'); return; }
|
||||
const btn = document.getElementById('bgt-new-submit-btn');
|
||||
btn.textContent = '시작 중...'; btn.disabled = true;
|
||||
try {
|
||||
const data = await api('/api/bg-tasks', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title, prompt }) });
|
||||
if (data.success) {
|
||||
closeNewBgTaskModal();
|
||||
await refreshBgTasks();
|
||||
} else {
|
||||
alert('태스크 생성 실패: ' + (data.error || 'unknown'));
|
||||
}
|
||||
} catch (err) {
|
||||
alert('오류: ' + err.message);
|
||||
} finally {
|
||||
btn.textContent = '▶ 시작'; btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
function openBgtHeartbeatModal() {
|
||||
const modal = document.getElementById('bgt-heartbeat-modal');
|
||||
const enabledEl = document.getElementById('bgt-hb-enabled');
|
||||
const intervalEl = document.getElementById('bgt-hb-interval');
|
||||
if (!modal || !enabledEl || !intervalEl) return;
|
||||
enabledEl.checked = !!bgtHeartbeatConfig.enabled;
|
||||
intervalEl.value = String(Math.max(1, Number(bgtHeartbeatConfig.interval_minutes) || 10));
|
||||
modal.style.display = 'flex';
|
||||
}
|
||||
|
||||
function closeBgtHeartbeatModal() {
|
||||
const modal = document.getElementById('bgt-heartbeat-modal');
|
||||
if (modal) modal.style.display = 'none';
|
||||
}
|
||||
|
||||
async function saveBgtHeartbeatConfig() {
|
||||
const enabledEl = document.getElementById('bgt-hb-enabled');
|
||||
const intervalEl = document.getElementById('bgt-hb-interval');
|
||||
if (!enabledEl || !intervalEl) return;
|
||||
|
||||
const enabled = !!enabledEl.checked;
|
||||
const interval = Math.max(1, Math.min(1440, Number(intervalEl.value) || 10));
|
||||
try {
|
||||
const data = await api('/api/bg-tasks/heartbeat/config', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ enabled, interval_minutes: interval }),
|
||||
});
|
||||
if (data?.success && data.config) {
|
||||
bgtHeartbeatConfig = data.config;
|
||||
renderBgTasks();
|
||||
closeBgtHeartbeatModal();
|
||||
bgtToast('Heartbeat updated', enabled ? `Every ${interval} minute(s)` : 'Task heartbeat disabled');
|
||||
return;
|
||||
}
|
||||
bgtToast('Heartbeat update failed', String(data?.error || 'Unknown error'));
|
||||
} catch (err) {
|
||||
bgtToast('Heartbeat update failed', String(err?.message || err));
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (e.key !== 'Escape') return;
|
||||
const modal = document.getElementById('bgt-heartbeat-modal');
|
||||
if (modal && modal.style.display === 'flex') closeBgtHeartbeatModal();
|
||||
});
|
||||
|
||||
document.addEventListener('click', (e) => {
|
||||
const modal = document.getElementById('bgt-heartbeat-modal');
|
||||
if (!modal || modal.style.display !== 'flex') return;
|
||||
if (e.target === modal) closeBgtHeartbeatModal();
|
||||
});
|
||||
|
||||
// --- Columns config ---------------------------------------------------------
|
||||
const BGT_COLUMNS = [
|
||||
{ key: 'running', label: '● In Progress', color: '#0d4faf', bg: '#eaf2ff' },
|
||||
{ key: 'queued', label: '◷ Queued', color: '#7c4d00', bg: '#fff8e1' },
|
||||
{ key: 'paused', label: '‖ Paused', color: '#555', bg: '#f5f5f5' },
|
||||
{ key: 'stalled', label: '▲ Stalled', color: '#9c1a1a', bg: '#fff0f0' },
|
||||
{ key: 'needs_assistance', label: '⚠️ Needs You', color: '#6d2d9e', bg: '#f5eeff' },
|
||||
{ key: 'complete', label: '✓ Complete', color: '#1a6e35', bg: '#efffea' },
|
||||
{ key: 'failed', label: '✕ Failed', color: '#9c1a1a', bg: '#fff0f0' },
|
||||
];
|
||||
|
||||
const STATUS_ICON = {
|
||||
running: '●',
|
||||
queued: '◷',
|
||||
paused: '‖',
|
||||
stalled: '▲',
|
||||
needs_assistance: '⚠️',
|
||||
complete: '✓',
|
||||
failed: '✕',
|
||||
};
|
||||
|
||||
// --- Fetch & Render ----------------------------------------------------------
|
||||
async function refreshBgTasks() {
|
||||
try {
|
||||
const data = await api('/api/bg-tasks');
|
||||
if (data.success) {
|
||||
bgtTasks = data.tasks || [];
|
||||
bgtHeartbeatConfig = data.heartbeatConfig || bgtHeartbeatConfig;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[BGT] refreshBgTasks error:', err);
|
||||
}
|
||||
renderBgTasks();
|
||||
}
|
||||
|
||||
function renderBgTasks() {
|
||||
const board = document.getElementById('bgt-board');
|
||||
if (!board) return;
|
||||
|
||||
// Update count badge
|
||||
const countEl = document.getElementById('bgt-count');
|
||||
if (countEl) {
|
||||
const active = bgtTasks.filter(t => t.status !== 'complete' && t.status !== 'failed').length;
|
||||
countEl.textContent = `${active} active`;
|
||||
}
|
||||
|
||||
// Update heartbeat label
|
||||
const hbLabel = document.getElementById('bgt-heartbeat-label');
|
||||
if (hbLabel) {
|
||||
const mins = bgtHeartbeatConfig.interval_minutes || 10;
|
||||
const on = bgtHeartbeatConfig.enabled;
|
||||
hbLabel.textContent = on ? `• heartbeat: ${mins}min` : '• heartbeat: off';
|
||||
hbLabel.style.color = on ? 'var(--brand)' : 'var(--muted)';
|
||||
}
|
||||
|
||||
// Only render non-empty columns
|
||||
const byStatus = {};
|
||||
for (const col of BGT_COLUMNS) byStatus[col.key] = [];
|
||||
for (const t of bgtTasks) {
|
||||
if (byStatus[t.status]) byStatus[t.status].push(t);
|
||||
else if (byStatus['stalled']) byStatus['stalled'].push(t);
|
||||
}
|
||||
|
||||
board.innerHTML = '';
|
||||
for (const col of BGT_COLUMNS) {
|
||||
const tasks = byStatus[col.key];
|
||||
if (tasks.length === 0 && (col.key === 'complete' || col.key === 'failed' || col.key === 'stalled' || col.key === 'needs_assistance')) continue;
|
||||
const colEl = document.createElement('div');
|
||||
colEl.style.cssText = 'min-width:240px;max-width:280px;flex:0 0 auto;display:flex;flex-direction:column;gap:0;';
|
||||
colEl.innerHTML = `
|
||||
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:8px">
|
||||
<span style="font-size:11px;font-weight:800;text-transform:uppercase;letter-spacing:0.06em;color:${col.color}">${col.label}</span>
|
||||
<span style="font-size:10px;background:${col.bg};color:${col.color};border-radius:999px;padding:1px 8px;font-weight:700">${tasks.length}</span>
|
||||
</div>
|
||||
<div class="bgt-col-cards" style="display:flex;flex-direction:column;gap:8px;min-height:60px">${tasks.map(t => bgtCardHTML(t, col)).join('')}</div>
|
||||
`;
|
||||
board.appendChild(colEl);
|
||||
if (tasks.length === 0) {
|
||||
// Empty placeholder
|
||||
colEl.querySelector('.bgt-col-cards').innerHTML = `<div style="text-align:center;padding:20px 8px;color:var(--muted);font-size:11px;border:1.5px dashed var(--line);border-radius:10px">No ${col.label.split(' ').slice(1).join(' ').toLowerCase()} tasks</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
// If no tasks at all
|
||||
if (bgtTasks.length === 0) {
|
||||
board.innerHTML = `<div style="text-align:center;padding:60px 24px;color:var(--muted);font-size:13px;flex:1">
|
||||
<div style="font-size:36px;margin-bottom:12px">작업</div>
|
||||
<div style="font-weight:700;margin-bottom:4px">No background tasks yet</div>
|
||||
<div style="font-size:12px">Ask HomeClaw to do something in the background and it'll appear here.</div>
|
||||
</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
function bgtCardHTML(t, col) {
|
||||
const mins = Math.round((Date.now() - (t.lastProgressAt || t.startedAt)) / 60000);
|
||||
const timeAgo = mins < 1 ? 'just now' : mins < 60 ? `${mins}m ago` : `${Math.round(mins/60)}h ago`;
|
||||
const stepsDone = (t.plan || []).filter(s => s.status === 'done' || s.status === 'skipped').length;
|
||||
const totalSteps = (t.plan || []).length;
|
||||
const pct = totalSteps > 0 ? Math.round(stepsDone / totalSteps * 100) : 0;
|
||||
const currentStep = (t.plan || [])[t.currentStepIndex || 0];
|
||||
const channel = t.channel === 'telegram' ? 'Telegram' : 'Web UI';
|
||||
|
||||
return `
|
||||
<div onclick="openBgtPanel('${escHtml(t.id)}')" data-bgt-id="${escHtml(t.id)}" style="
|
||||
background:var(--panel);border:1.5px solid var(--line);border-radius:12px;padding:12px 14px;
|
||||
cursor:pointer;transition:border-color 0.15s,box-shadow 0.15s;
|
||||
${bgtOpenTaskId === t.id ? 'border-color:var(--brand);box-shadow:0 0 0 2px rgba(90,145,255,0.15);' : ''}
|
||||
" onmouseover="this.style.borderColor='var(--brand)'" onmouseout="this.style.borderColor='${bgtOpenTaskId===t.id?'var(--brand)':'var(--line)'}'">
|
||||
<div style="display:flex;align-items:flex-start;justify-content:space-between;gap:8px;margin-bottom:6px">
|
||||
<span style="font-size:13px;font-weight:700;line-height:1.3;flex:1;min-width:0">${escHtml(t.title || 'Untitled Task')}</span>
|
||||
<div style="display:flex;align-items:center;gap:6px;flex-shrink:0">
|
||||
<button
|
||||
onclick="event.stopPropagation(); bgtDeleteTask('${escHtml(t.id)}', '${escHtml(t.status)}')"
|
||||
title="Remove task"
|
||||
style="border:1px solid #fca5a5;background:#fff0f0;color:#9c1a1a;border-radius:7px;padding:1px 6px;font-size:11px;font-weight:700;cursor:pointer"
|
||||
>✕</button>
|
||||
<span style="font-size:14px;flex-shrink:0">${STATUS_ICON[t.status] || '?'}</span>
|
||||
</div>
|
||||
</div>
|
||||
${currentStep ? `<div style="font-size:11px;color:var(--muted);margin-bottom:8px;line-height:1.4">Step ${(t.currentStepIndex||0)+1}/${totalSteps}: ${escHtml(currentStep.description.slice(0,60))}${currentStep.description.length>60?'…':''}</div>` : ''}
|
||||
${totalSteps > 0 ? `
|
||||
<div style="background:var(--line);border-radius:999px;height:3px;margin-bottom:8px;overflow:hidden">
|
||||
<div style="background:${col.color};width:${pct}%;height:100%;border-radius:999px;transition:width 0.4s"></div>
|
||||
</div>` : ''}
|
||||
<div style="display:flex;align-items:center;justify-content:space-between">
|
||||
<span style="font-size:10px;color:var(--muted)">${channel} ${timeAgo}</span>
|
||||
${t.status === 'needs_assistance' ? `<span style="font-size:10px;background:#f5eeff;color:#6d2d9e;border-radius:999px;padding:1px 8px;font-weight:700">Needs you</span>` : ''}
|
||||
${t.status === 'paused' ? `<span style="font-size:10px;background:#f5f5f5;color:#555;border-radius:999px;padding:1px 8px;font-weight:700">${t.pauseReason || 'paused'}</span>` : ''}
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
// --- Side Panel --------------------------------------------------------------
|
||||
async function openBgtPanel(taskId) {
|
||||
bgtOpenTaskId = taskId;
|
||||
const panel = document.getElementById('bgt-panel');
|
||||
if (panel) panel.style.display = 'flex';
|
||||
// Clear chat input when switching tasks
|
||||
const chatInput = document.getElementById('bgt-chat-input');
|
||||
if (chatInput) { chatInput.value = ''; chatInput.disabled = false; chatInput.style.opacity = ''; }
|
||||
await bgtRefreshOpenPanel();
|
||||
// Highlight the card
|
||||
renderBgTasks();
|
||||
}
|
||||
|
||||
function closeBgtPanel() {
|
||||
bgtOpenTaskId = null;
|
||||
const panel = document.getElementById('bgt-panel');
|
||||
if (panel) panel.style.display = 'none';
|
||||
renderBgTasks();
|
||||
}
|
||||
|
||||
async function bgtRefreshOpenPanel() {
|
||||
if (!bgtOpenTaskId) return;
|
||||
let task;
|
||||
try {
|
||||
const data = await api(`/api/bg-tasks/${bgtOpenTaskId}`);
|
||||
if (data.success) task = data.task;
|
||||
} catch {}
|
||||
if (!task) { task = bgtTasks.find(t => t.id === bgtOpenTaskId); }
|
||||
if (!task) return;
|
||||
|
||||
const titleEl = document.getElementById('bgt-panel-title');
|
||||
if (titleEl) titleEl.textContent = task.title || '작업 상세';
|
||||
|
||||
const pauseBtn = document.getElementById('bgt-panel-pause');
|
||||
if (pauseBtn) {
|
||||
if (task.status === 'running') {
|
||||
pauseBtn.textContent = '일시정지';
|
||||
pauseBtn.style.display = '';
|
||||
} else if (task.status === 'paused' || task.status === 'queued') {
|
||||
pauseBtn.textContent = '재개';
|
||||
pauseBtn.style.display = '';
|
||||
} else {
|
||||
pauseBtn.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
const body = document.getElementById('bgt-panel-body');
|
||||
if (!body) return;
|
||||
|
||||
const plan = task.plan || [];
|
||||
const journal = task.journal || [];
|
||||
const stepsDone = plan.filter(s => s.status === 'done' || s.status === 'skipped').length;
|
||||
const lastTool = task.lastToolCall || '—';
|
||||
const lastToolAt = task.lastToolCallAt ? new Date(task.lastToolCallAt).toLocaleTimeString() : '—';
|
||||
const channel = task.channel === 'telegram' ? 'Telegram' : 'Web UI';
|
||||
const startedAt = task.startedAt ? new Date(task.startedAt).toLocaleString() : '—';
|
||||
const statusColor = { running:'#0d4faf', queued:'#7c4d00', paused:'#555', stalled:'#9c1a1a', needs_assistance:'#6d2d9e', complete:'#1a6e35', failed:'#9c1a1a' };
|
||||
const sc = statusColor[task.status] || '#555';
|
||||
|
||||
// Build plan steps HTML
|
||||
const stepsHTML = plan.map((step, i) => {
|
||||
const icon = step.status === 'done' ? '✓' : step.status === 'failed' ? '✕' : step.status === 'skipped' ? '↷' : i === (task.currentStepIndex || 0) && task.status === 'running' ? '▶' : '○';
|
||||
const isCurrent = i === (task.currentStepIndex || 0) && task.status !== 'complete';
|
||||
return `<div style="display:flex;gap:10px;align-items:flex-start;padding:7px 0;border-bottom:1px solid var(--line);${isCurrent?'background:#f0f5ff;margin:0 -8px;padding:7px 8px;border-radius:6px;':''}"
|
||||
title="${step.notes ? escHtml(step.notes) : ''}">
|
||||
<span style="font-size:14px;flex-shrink:0;line-height:1.4">${icon}</span>
|
||||
<div style="flex:1;min-width:0">
|
||||
<div style="font-size:12px;font-weight:${isCurrent?'700':'500'};color:${isCurrent?'var(--text)':'var(--muted)'}">${escHtml(step.description)}</div>
|
||||
${step.notes ? `<div style="font-size:11px;color:var(--muted);margin-top:2px">${escHtml(step.notes.slice(0,120))}</div>` : ''}
|
||||
</div>
|
||||
</div>`;
|
||||
}).join('');
|
||||
|
||||
// Build journal HTML (last 30 entries)
|
||||
const recentJournal = journal.slice(-30).reverse();
|
||||
const journalHTML = recentJournal.map(entry => {
|
||||
const time = new Date(entry.t).toLocaleTimeString();
|
||||
const typeColor = { tool_call:'#0d4faf', tool_result:'#1a6e35', error:'#9c1a1a', plan_mutation:'#6d2d9e', status_push:'#555', pause:'#7c4d00', resume:'#7c4d00', advisor_decision:'#555', heartbeat:'var(--brand)' };
|
||||
const tc = typeColor[entry.type] || '#888';
|
||||
return `<div style="display:flex;gap:8px;padding:5px 0;border-bottom:1px solid var(--line);font-size:11px">
|
||||
<span style="color:var(--muted);flex-shrink:0;min-width:52px">${time}</span>
|
||||
<span style="color:${tc};flex-shrink:0;font-weight:700;min-width:60px">${entry.type}</span>
|
||||
<span style="color:var(--text);flex:1;min-width:0;word-break:break-word">${escHtml(entry.content)}</span>
|
||||
</div>`;
|
||||
}).join('');
|
||||
|
||||
// Build assistance block outside template literal to avoid backtick nesting issues
|
||||
let assistanceHTML = '';
|
||||
const taskStatusNorm = String(task.status || '').trim().toLowerCase();
|
||||
console.log('[BGT panel] task.status =', JSON.stringify(task.status), 'norm =', taskStatusNorm);
|
||||
if (taskStatusNorm === 'needs_assistance' || taskStatusNorm === 'paused' || taskStatusNorm === 'stalled' || taskStatusNorm === 'failed') {
|
||||
const lastPause = [...journal].reverse().find(e => e.type === 'pause' || e.type === 'error');
|
||||
const lastStatusPush = [...journal].reverse().find(e => e.type === 'status_push' && e.content);
|
||||
const pauseMsg = escHtml((lastPause?.content || lastStatusPush?.content || 'Task paused and waiting for input.').replace(/^Task paused for assistance:\s*/i, ''));
|
||||
const pauseDetail = lastPause?.detail ? escHtml(lastPause.detail.slice(0, 300)) : '';
|
||||
const tid = escHtml(task.id);
|
||||
assistanceHTML = '<div style="background:#f5eeff;border:1px solid #cba8f5;border-radius:10px;padding:12px 14px;font-size:12px;line-height:1.6;color:#6d2d9e">'
|
||||
+ '<div style="font-weight:800;margin-bottom:6px">⚠️ Task needs your input</div>'
|
||||
+ '<div style="color:#3d1a6e;margin-bottom:' + (pauseDetail ? '6px' : '0') + '">' + pauseMsg + '</div>'
|
||||
+ (pauseDetail ? '<div style="font-size:11px;color:#6d2d9e;opacity:0.8;margin-bottom:4px">' + pauseDetail + '</div>' : '')
|
||||
+ '</div>'
|
||||
+ '<div style="border:1px solid #cba8f5;border-radius:10px;overflow:hidden;background:#faf5ff;margin-top:8px">'
|
||||
+ '<div style="padding:8px 12px;font-size:11px;font-weight:700;color:#6d2d9e;border-bottom:1px solid #e9d8ff">💬 Reply to agent</div>'
|
||||
+ '<div style="display:flex;gap:8px;padding:8px">'
|
||||
+ '<textarea id="task-reply-input" rows="2" placeholder="Type your reply — the agent will see this and continue..." style="flex:1;resize:none;border:1px solid #cba8f5;border-radius:8px;padding:8px;font-size:12px;font-family:inherit;background:#fff;color:var(--text)"></textarea>'
|
||||
+ '<button id="task-reply-send" data-taskid="' + tid + '" style="background:#7c3aed;color:#fff;border:none;border-radius:8px;padding:8px 14px;font-size:12px;font-weight:700;cursor:pointer;align-self:flex-end">전송</button>'
|
||||
+ '</div></div>';
|
||||
}
|
||||
|
||||
body.innerHTML = `
|
||||
<!-- Status row -->
|
||||
<div style="display:flex;gap:8px;flex-wrap:wrap;align-items:center">
|
||||
<span style="font-size:11px;background:var(--line);border-radius:999px;padding:2px 10px;font-weight:700;color:${sc}">${STATUS_ICON[task.status]} ${task.status.replace(/_/g,' ')}</span>
|
||||
<span style="font-size:11px;color:var(--muted)">${channel}</span>
|
||||
<span style="font-size:11px;color:var(--muted)">Started ${startedAt}</span>
|
||||
</div>
|
||||
|
||||
<!-- Summary if complete -->
|
||||
${task.finalSummary ? `<div style="background:#efffea;border:1px solid #b2dfb2;border-radius:10px;padding:12px 14px;font-size:12px;line-height:1.6;color:#1a6e35">
|
||||
<div style="font-weight:800;margin-bottom:4px">✓ Summary</div>
|
||||
${escHtml(task.finalSummary)}
|
||||
</div>` : ''}
|
||||
|
||||
<!-- Needs assistance -->
|
||||
${assistanceHTML}
|
||||
|
||||
<!-- Stats row -->
|
||||
<div style="display:flex;gap:12px;flex-wrap:wrap">
|
||||
<div style="flex:1;min-width:100px;background:var(--panel-2);border-radius:10px;padding:10px 12px">
|
||||
<div style="font-size:10px;color:var(--muted);text-transform:uppercase;font-weight:700;margin-bottom:2px">Progress</div>
|
||||
<div style="font-size:18px;font-weight:800">${stepsDone}<span style="font-size:12px;color:var(--muted)">/${plan.length}</span></div>
|
||||
<div style="font-size:10px;color:var(--muted)">steps done</div>
|
||||
</div>
|
||||
<div style="flex:1;min-width:100px;background:var(--panel-2);border-radius:10px;padding:10px 12px">
|
||||
<div style="font-size:10px;color:var(--muted);text-transform:uppercase;font-weight:700;margin-bottom:2px">Last Tool</div>
|
||||
<div style="font-size:12px;font-weight:700;word-break:break-all">${escHtml(lastTool.slice(0,30))}</div>
|
||||
<div style="font-size:10px;color:var(--muted)">${lastToolAt}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Plan steps -->
|
||||
${plan.length > 0 ? `
|
||||
<div>
|
||||
<div style="font-size:11px;font-weight:800;text-transform:uppercase;letter-spacing:0.05em;color:var(--muted);margin-bottom:8px">Execution Plan</div>
|
||||
<div style="border:1px solid var(--line);border-radius:10px;padding:6px 8px">${stepsHTML}</div>
|
||||
</div>` : ''}
|
||||
|
||||
<!-- Process journal -->
|
||||
<div>
|
||||
<div style="font-size:11px;font-weight:800;text-transform:uppercase;letter-spacing:0.05em;color:var(--muted);margin-bottom:6px">Process Log <span style="font-weight:400;opacity:0.6">(latest first)</span></div>
|
||||
<div style="font-family:monospace;font-size:11px;border:1px solid var(--line);border-radius:10px;padding:6px 8px;max-height:300px;overflow-y:auto">
|
||||
${journalHTML || '<div style="color:var(--muted);padding:8px">No entries yet.</div>'}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Delete button -->
|
||||
${(task.status === 'complete' || task.status === 'failed') ? `
|
||||
<button onclick="bgtDeleteTask('${escHtml(task.id)}')" style="border:1px solid #fca5a5;background:#fff0f0;color:#9c1a1a;border-radius:8px;padding:6px 14px;font-size:12px;font-weight:700;cursor:pointer;align-self:flex-start">Remove</button>` : ''}
|
||||
`;
|
||||
|
||||
// Wire up the reply send button via JS (avoids inline onclick escaping issues)
|
||||
const sendBtn = document.getElementById('task-reply-send');
|
||||
if (sendBtn) {
|
||||
sendBtn.addEventListener('click', () => bgtSendReply(sendBtn.dataset.taskid));
|
||||
}
|
||||
// Also allow Enter (without Shift) in the textarea to send
|
||||
const replyInput = document.getElementById('task-reply-input');
|
||||
if (replyInput) {
|
||||
replyInput.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
bgtSendReply(sendBtn ? sendBtn.dataset.taskid : bgtOpenTaskId);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// --- Actions -----------------------------------------------------------------
|
||||
async function bgtPauseResume() {
|
||||
if (!bgtOpenTaskId) return;
|
||||
const task = bgtTasks.find(t => t.id === bgtOpenTaskId);
|
||||
if (!task) return;
|
||||
if (task.status === 'running') {
|
||||
// Pause
|
||||
try { await api(`/api/bg-tasks/${bgtOpenTaskId}/pause`, { method: 'POST' }); } catch {}
|
||||
} else if (task.status === 'paused' || task.status === 'queued') {
|
||||
// Resume
|
||||
try { await api(`/api/bg-tasks/${bgtOpenTaskId}/resume`, { method: 'POST' }); } catch {}
|
||||
}
|
||||
await refreshBgTasks();
|
||||
await bgtRefreshOpenPanel();
|
||||
}
|
||||
|
||||
async function bgtSendReply(taskId) {
|
||||
const input = document.getElementById('task-reply-input');
|
||||
if (!input) return;
|
||||
const message = input.value.trim();
|
||||
if (!message) return;
|
||||
input.value = '';
|
||||
input.disabled = true;
|
||||
try {
|
||||
const result = await api(`/api/bg-tasks/${taskId}/message`, { method: 'POST', body: JSON.stringify({ message }) });
|
||||
if (result.success) {
|
||||
// Refresh the panel after a short delay to show the journal update
|
||||
setTimeout(() => bgtRefreshOpenPanel(), 800);
|
||||
} else {
|
||||
alert('Failed to send: ' + (result.error || 'unknown error'));
|
||||
}
|
||||
} catch (e) {
|
||||
alert('Error sending message: ' + e.message);
|
||||
} finally {
|
||||
input.disabled = false;
|
||||
input.focus();
|
||||
}
|
||||
}
|
||||
|
||||
async function bgtChatSend() {
|
||||
const input = document.getElementById('bgt-chat-input');
|
||||
if (!input || !bgtOpenTaskId) return;
|
||||
const message = input.value.trim();
|
||||
if (!message) return;
|
||||
input.value = '';
|
||||
input.disabled = true;
|
||||
input.style.opacity = '0.5';
|
||||
try {
|
||||
const result = await api(`/api/bg-tasks/${bgtOpenTaskId}/message`, { method: 'POST', body: JSON.stringify({ message }) });
|
||||
if (result.success) {
|
||||
// Show optimistic sent indicator in journal area
|
||||
const body = document.getElementById('bgt-panel-body');
|
||||
if (body) {
|
||||
const sentDiv = document.createElement('div');
|
||||
sentDiv.style.cssText = 'background:var(--brand);color:#fff;border-radius:8px;padding:6px 10px;font-size:12px;align-self:flex-end;max-width:80%;word-break:break-word;opacity:0.85';
|
||||
sentDiv.textContent = '\u2192 ' + message;
|
||||
body.appendChild(sentDiv);
|
||||
body.scrollTop = body.scrollHeight;
|
||||
}
|
||||
// Refresh panel after short delay to show journal update
|
||||
setTimeout(() => bgtRefreshOpenPanel(), 1000);
|
||||
} else {
|
||||
alert('Failed to send: ' + (result.error || 'unknown error'));
|
||||
}
|
||||
} catch (e) {
|
||||
alert('Error: ' + e.message);
|
||||
} finally {
|
||||
input.disabled = false;
|
||||
input.style.opacity = '';
|
||||
input.focus();
|
||||
}
|
||||
}
|
||||
|
||||
async function bgtDeleteTask(taskId, status) {
|
||||
const isActive = status && status !== 'complete' && status !== 'failed';
|
||||
const prompt = isActive
|
||||
? 'This task is still active. Remove it from the board anyway?'
|
||||
: 'Remove this task from the board?';
|
||||
if (!confirm(prompt)) return;
|
||||
try { await api(`/api/bg-tasks/${taskId}`, { method: 'DELETE' }); } catch {}
|
||||
if (bgtOpenTaskId === taskId) closeBgtPanel();
|
||||
await refreshBgTasks();
|
||||
}
|
||||
|
||||
// --- Toast notification -------------------------------------------------------
|
||||
function bgtToast(title, body) {
|
||||
const toast = document.createElement('div');
|
||||
toast.style.cssText = `position:fixed;bottom:24px;right:24px;z-index:9999;background:var(--panel);border:1.5px solid var(--line);border-radius:12px;padding:12px 16px;min-width:240px;max-width:360px;box-shadow:0 4px 24px rgba(0,0,0,0.12);font-family:var(--font)`;
|
||||
toast.innerHTML = `<div style="font-size:13px;font-weight:800;margin-bottom:4px">${escHtml(title)}</div>${body ? `<div style="font-size:12px;color:var(--muted);line-height:1.4">${escHtml(body)}</div>` : ''}`;
|
||||
document.body.appendChild(toast);
|
||||
setTimeout(() => toast.remove(), 6000);
|
||||
}
|
||||
@@ -0,0 +1,851 @@
|
||||
// chat-render.js — 채팅 메시지·아티팩트·프로세스로그·에이전트 실행 패널 렌더링, 큐잉된 프롬프트 패널.
|
||||
// extracted from app.js (v4.3.19-3 split).
|
||||
|
||||
function renderQueuedPromptsPanel() {
|
||||
const panel = document.getElementById('queued-prompts-panel');
|
||||
const list = document.getElementById('queued-prompts-list');
|
||||
const title = document.getElementById('queued-prompts-title');
|
||||
if (!panel || !list || !title) return;
|
||||
const count = queuedPrompts.length;
|
||||
if (count === 0) {
|
||||
panel.style.display = 'none';
|
||||
list.innerHTML = '';
|
||||
return;
|
||||
}
|
||||
panel.style.display = 'block';
|
||||
title.textContent = `Queued prompts (${count})`;
|
||||
list.innerHTML = queuedPrompts.map((q, i) => `
|
||||
<div class="queued-item">
|
||||
<div class="queued-item-text">${escHtml(q)}</div>
|
||||
<button class="queued-item-btn" onclick="removeQueuedPrompt(${i})">Remove</button>
|
||||
</div>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
function removeQueuedPrompt(index) {
|
||||
if (!Number.isInteger(index) || index < 0 || index >= queuedPrompts.length) return;
|
||||
queuedPrompts.splice(index, 1);
|
||||
updateQueuedPromptUI();
|
||||
}
|
||||
|
||||
function clearQueuedPrompts() {
|
||||
if (!queuedPrompts.length) return;
|
||||
queuedPrompts = [];
|
||||
addProcessEntry('info', 'Cleared queued prompts.');
|
||||
updateQueuedPromptUI();
|
||||
}
|
||||
|
||||
function updateQueuedPromptUI() {
|
||||
const badge = document.getElementById('queued-prompts-indicator');
|
||||
const sendBtn = document.getElementById('send-btn');
|
||||
const input = document.getElementById('chat-input');
|
||||
const count = queuedPrompts.length;
|
||||
if (badge) {
|
||||
if (count > 0) {
|
||||
badge.style.display = 'inline';
|
||||
badge.textContent = `Queued: ${count}`;
|
||||
} else {
|
||||
badge.style.display = 'none';
|
||||
badge.textContent = '';
|
||||
}
|
||||
}
|
||||
if (sendBtn) {
|
||||
sendBtn.disabled = false;
|
||||
sendBtn.title = isThinking ? `Queue next prompt${count ? ` (${count} queued)` : ''}` : 'Send';
|
||||
}
|
||||
if (input) {
|
||||
input.placeholder = isThinking
|
||||
? 'Assistant is responding. Press Enter/Send to queue next prompt.'
|
||||
: 'Type a message... (Enter to send, Shift+Enter for newline)';
|
||||
}
|
||||
renderQueuedPromptsPanel();
|
||||
}
|
||||
|
||||
function renderThinkBlock(thinking) {
|
||||
if (!thinking || !thinking.trim()) return '';
|
||||
const id = 'think_' + Math.random().toString(36).slice(2);
|
||||
const wordCount = thinking.trim().split(/\s+/).length;
|
||||
return `
|
||||
<div class="think-block">
|
||||
<button class="think-toggle" id="${id}_btn" onclick="toggleThink('${id}')">
|
||||
<span class="think-icon">...</span>
|
||||
<span>Thought process</span>
|
||||
<span style="margin-left:auto;opacity:0.5">${wordCount} words</span>
|
||||
</button>
|
||||
<div class="think-content" id="${id}_body">${escHtml(thinking)}</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function toggleThink(id) {
|
||||
const btn = document.getElementById(id + '_btn');
|
||||
const body = document.getElementById(id + '_body');
|
||||
if (!btn || !body) return;
|
||||
const open = body.style.display !== 'none' && body.style.display !== '';
|
||||
body.style.display = open ? 'none' : 'block';
|
||||
btn.classList.toggle('open', !open);
|
||||
}
|
||||
|
||||
function renderReactSteps(steps) {
|
||||
if (!steps || steps.length === 0) return '';
|
||||
const toolSteps = steps.filter(s => s.action);
|
||||
if (toolSteps.length === 0) return '';
|
||||
|
||||
const getSearchDiagnostics = (s) => s?.toolData?.search_diagnostics || s?.diagnostics || null;
|
||||
const extractUrls = (s, resultText) => {
|
||||
const fromToolData = Array.isArray(s?.toolData?.results)
|
||||
? s.toolData.results.map(r => String(r?.url || '').trim()).filter(u => /^https?:\/\//i.test(u))
|
||||
: [];
|
||||
const fromText = String(resultText || '').match(/https?:\/\/[^\s)]+/g) || [];
|
||||
const merged = [...fromToolData, ...fromText.map(u => String(u).trim())];
|
||||
const out = [];
|
||||
const seen = new Set();
|
||||
for (const u of merged) {
|
||||
if (!u || seen.has(u)) continue;
|
||||
seen.add(u);
|
||||
out.push(u);
|
||||
if (out.length >= 5) break;
|
||||
}
|
||||
return out;
|
||||
};
|
||||
const providerSummary = (diag) => {
|
||||
if (!diag || !Array.isArray(diag.attempted) || !diag.attempted.length) return '';
|
||||
return diag.attempted.map(a => {
|
||||
const p = String(a.provider || '').toLowerCase();
|
||||
const status = String(a.status || '').toLowerCase();
|
||||
if (status === 'success') {
|
||||
const count = Number.isFinite(a.result_count) ? `, ${a.result_count} result${a.result_count === 1 ? '' : 's'}` : '';
|
||||
return `${p}=success${count}`;
|
||||
}
|
||||
if (status === 'skipped') return `${p}=skipped${a.reason ? ` (${a.reason})` : ''}`;
|
||||
return `${p}=failed${a.reason ? ` (${a.reason})` : ''}`;
|
||||
}).join(' | ');
|
||||
};
|
||||
|
||||
const id = 'steps_' + Math.random().toString(36).slice(2);
|
||||
const items = toolSteps.map(s => {
|
||||
const resultText = typeof s.toolResult === 'string' ? s.toolResult : JSON.stringify(s.toolResult || '');
|
||||
const diag = String(s.action || '') === 'web_search' ? getSearchDiagnostics(s) : null;
|
||||
const query = String(diag?.query || s?.params?.query || '').trim();
|
||||
const selectedProvider = String(diag?.selected_provider || s?.toolData?.provider || '').toLowerCase();
|
||||
const providers = diag ? providerSummary(diag) : '';
|
||||
const urls = String(s.action || '') === 'web_search' ? extractUrls(s, resultText) : [];
|
||||
return `
|
||||
<div class="react-step">
|
||||
${s.thought ? `<div class="react-step-thought">${escHtml(s.thought.slice(0, 120))}</div>` : ''}
|
||||
<div class="react-step-action">${escHtml(s.action)}</div>
|
||||
${resultText ? `<div class="react-step-result${resultText.startsWith('ERROR') ? ' error' : ''}">${escHtml(resultText.slice(0, 160))}${resultText.length > 160 ? '…' : ''}</div>` : ''}
|
||||
${diag ? `
|
||||
<div style="margin-top:6px;font-size:10px;color:var(--muted);line-height:1.5">
|
||||
${query ? `<div><b>query</b>: ${escHtml(query)}</div>` : ''}
|
||||
${selectedProvider ? `<div><b>provider hit</b>: ${escHtml(selectedProvider)}</div>` : ''}
|
||||
${providers ? `<div><b>providers</b>: ${escHtml(providers)}</div>` : ''}
|
||||
</div>
|
||||
` : ''}
|
||||
${String(s.action || '') === 'web_search' && !diag ? `
|
||||
<div style="margin-top:6px;font-size:10px;color:var(--muted);line-height:1.5">
|
||||
${selectedProvider ? `<div><b>provider hit</b>: ${escHtml(selectedProvider)}</div>` : ''}
|
||||
</div>
|
||||
` : ''}
|
||||
${urls.length ? `
|
||||
<div style="margin-top:6px;font-size:10px;line-height:1.6">
|
||||
<div style="color:var(--muted);margin-bottom:2px"><b>sources</b>:</div>
|
||||
${urls.slice(0, 3).map((u, i) => `<div>${i + 1}. <a href="${escHtml(u)}" target="_blank" rel="noopener noreferrer">${escHtml(u)}</a></div>`).join('')}
|
||||
</div>
|
||||
` : ''}
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
return `
|
||||
<div class="react-steps-toggle" onclick="toggleSteps('${id}')">
|
||||
? ${toolSteps.length} tool step${toolSteps.length !== 1 ? 's' : ''} used
|
||||
</div>
|
||||
<div class="react-steps" id="${id}" style="display:none">${items}</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function toggleSteps(id) {
|
||||
const el = document.getElementById(id);
|
||||
if (!el) return;
|
||||
const visible = el.style.display !== 'none';
|
||||
el.style.display = visible ? 'none' : 'block';
|
||||
el.previousElementSibling.textContent = `${visible ? '?' : '?'} ${el.querySelectorAll('.react-step').length} tool step${el.querySelectorAll('.react-step').length !== 1 ? 's' : ''} used`;
|
||||
}
|
||||
|
||||
function renderFileDownloads(steps, processEntries) {
|
||||
const seenUrls = new Set(); // normalized (decoded) URLs
|
||||
const buttons = [];
|
||||
const URL_RE = /\/api\/files\/[^\s)"'\]]+/g;
|
||||
|
||||
function normalizeUrl(u) {
|
||||
try { return decodeURIComponent(u); } catch { return u; }
|
||||
}
|
||||
|
||||
function extractUrls(text) {
|
||||
const urls = [];
|
||||
let m;
|
||||
while ((m = URL_RE.exec(text)) !== null) urls.push(m[0]);
|
||||
return urls;
|
||||
}
|
||||
|
||||
// Pre-mark URLs already present in msg.content so tool-result duplicates are suppressed.
|
||||
// renderMarkdown() handles content links — we must not render a second button for the same URL.
|
||||
// Normalize both sides (decode percent-encoding) before comparing so Korean paths match.
|
||||
if (arguments.length > 2 && arguments[2]) {
|
||||
const contentText = String(arguments[2]);
|
||||
if (contentText.indexOf('/api/files/') !== -1) {
|
||||
for (const u of extractUrls(contentText)) seenUrls.add(normalizeUrl(u));
|
||||
URL_RE.lastIndex = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Collect /api/files/ URLs from tool results only (not content — already handled above)
|
||||
const allUrls = [];
|
||||
|
||||
// 1. msg.steps (legacy step events)
|
||||
if (steps && steps.length) {
|
||||
for (const s of steps) {
|
||||
const resultText = typeof s.toolResult === 'string' ? s.toolResult : JSON.stringify(s.toolResult || '');
|
||||
allUrls.push(...extractUrls(resultText));
|
||||
}
|
||||
}
|
||||
|
||||
// 2. msg.processEntries (stored per-message in chatHistory)
|
||||
if (processEntries && processEntries.length) {
|
||||
for (const e of processEntries) {
|
||||
const txt = String(e.content || '');
|
||||
if (txt.indexOf('/api/files/') !== -1) allUrls.push(...extractUrls(txt));
|
||||
}
|
||||
}
|
||||
|
||||
const _imgExts = /\.(jpg|jpeg|png|gif|webp|heic|heif|bmp|svg|avif|tiff|tif)(\?|$)/i;
|
||||
for (const rawUrl of allUrls) {
|
||||
const normUrl = normalizeUrl(rawUrl);
|
||||
if (seenUrls.has(normUrl)) continue;
|
||||
seenUrls.add(normUrl);
|
||||
const decoded = (() => { try { return decodeURIComponent(rawUrl); } catch { return rawUrl; } })();
|
||||
if (_imgExts.test(decoded)) continue; // images shown inline, no download button needed
|
||||
const filename = decoded.split('/').pop() || 'download';
|
||||
const isPptx = decoded.toLowerCase().indexOf('.pptx') !== -1;
|
||||
if (isPptx) {
|
||||
const previewId = 'pptx-chat-' + Math.random().toString(36).substr(2, 9);
|
||||
buttons.push(`
|
||||
<div class="pptx-file-row" style="margin:6px 0">
|
||||
<a href="${escHtml(rawUrl)}" onclick="downloadFile(event, this)" class="download-btn" title="Download ${escHtml(filename)}">
|
||||
<span class="download-icon">⬇</span> ${escHtml(filename)}</a>
|
||||
<button class="pptx-preview-btn" onclick="togglePptxPreview('${escHtml(rawUrl)}', '${previewId}', this)" title="Preview slides">◀ Preview</button>
|
||||
<div id="${previewId}" class="pptx-preview-strip" style="display:none"></div>
|
||||
</div>`);
|
||||
} else {
|
||||
buttons.push(`
|
||||
<a href="${escHtml(rawUrl)}" onclick="downloadFile(event, this)" class="download-btn" title="Download ${escHtml(filename)}">
|
||||
<span class="download-icon">⬇</span> ${escHtml(filename)}</a>`);
|
||||
}
|
||||
}
|
||||
return buttons.length ? `<div style="margin-top:8px">${buttons.join(' ')}</div>` : '';
|
||||
}
|
||||
|
||||
function renderAssistantContent(content) {
|
||||
const text = String(content || '');
|
||||
const hasStaged = /(^|\n)(Initial chat|Execution result|Final chat):\s*/i.test(text);
|
||||
if (!hasStaged) return `<div class="msg-content">${renderMarkdown(text)}</div>`;
|
||||
const chunks = text
|
||||
.split(/\n\s*---\s*\n/g)
|
||||
.map(s => String(s || '').trim())
|
||||
.filter(Boolean);
|
||||
const html = chunks.map((chunk, idx) => {
|
||||
const m = chunk.match(/^(Initial chat|Execution result|Final chat):\s*\n?/i);
|
||||
const title = m ? m[1] : `Section ${idx + 1}`;
|
||||
const body = m ? chunk.slice(m[0].length).trim() : chunk;
|
||||
return `
|
||||
<div class="msg-stage">
|
||||
<div class="msg-stage-title">${escHtml(title)}</div>
|
||||
<div class="msg-content">${renderMarkdown(body)}</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
return `<div class="msg-staged">${html}</div>`;
|
||||
}
|
||||
|
||||
function renderArtifacts(artifacts) {
|
||||
const rows = Array.isArray(artifacts) ? artifacts : [];
|
||||
if (!rows.length) return '';
|
||||
const cards = rows.map((a, idx) => {
|
||||
const type = String(a?.type || '').trim();
|
||||
const title = String(a?.title || type || `Artifact ${idx + 1}`).trim();
|
||||
const status = String(a?.status || 'ok').toLowerCase();
|
||||
const pathVal = String(a?.path || '').trim();
|
||||
const fromPath = String(a?.from_path || '').trim();
|
||||
const toPath = String(a?.to_path || '').trim();
|
||||
const summary = String(a?.summary || '').trim();
|
||||
const preview = String(a?.preview || '').trim();
|
||||
const files = Array.isArray(a?.files) ? a.files.slice(0, 12).map(x => String(x || '')).filter(Boolean) : [];
|
||||
const dirs = Array.isArray(a?.directories) ? a.directories.slice(0, 8).map(x => String(x || '')).filter(Boolean) : [];
|
||||
const locationTarget = toPath || pathVal || fromPath;
|
||||
return `
|
||||
<div class="artifact-card">
|
||||
<div class="artifact-head">
|
||||
<div class="artifact-title">${escHtml(title)}</div>
|
||||
<div class="artifact-status ${escHtml(status)}">${escHtml(status)}</div>
|
||||
</div>
|
||||
${pathVal ? `<div class="artifact-row"><b>Path:</b> <code>${escHtml(pathVal)}</code></div>` : ''}
|
||||
${fromPath ? `<div class="artifact-row"><b>From:</b> <code>${escHtml(fromPath)}</code></div>` : ''}
|
||||
${toPath ? `<div class="artifact-row"><b>To:</b> <code>${escHtml(toPath)}</code></div>` : ''}
|
||||
${summary ? `<div class="artifact-row">${escHtml(summary)}</div>` : ''}
|
||||
${files.length ? `<div class="artifact-row"><b>Files:</b> ${escHtml(files.join(', '))}${Array.isArray(a?.files) && a.files.length > files.length ? ' ...' : ''}</div>` : ''}
|
||||
${dirs.length ? `<div class="artifact-row"><b>Directories:</b> ${escHtml(dirs.join(', '))}${Array.isArray(a?.directories) && a.directories.length > dirs.length ? ' ...' : ''}</div>` : ''}
|
||||
${preview ? `<div class="artifact-preview">${escHtml(preview)}</div>` : ''}
|
||||
${locationTarget ? `
|
||||
<div class="artifact-actions">
|
||||
<button class="artifact-btn" onclick="openInFileLocation('${escHtml(locationTarget).replace(/'/g, ''')}')">Open In File Location</button>
|
||||
</div>
|
||||
` : ''}
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
return `<div class="artifact-list">${cards}</div>`;
|
||||
}
|
||||
|
||||
async function openInFileLocation(targetPath) {
|
||||
const p = String(targetPath || '').trim();
|
||||
if (!p) return;
|
||||
try {
|
||||
const res = await fetch('/api/open-path', {
|
||||
method: 'POST',
|
||||
headers: authHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify({ path: p }),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok || !data?.ok) {
|
||||
throw new Error(String(data?.error || `HTTP ${res.status}`));
|
||||
}
|
||||
addProcessEntry('info', `Opened in file location: ${p}`);
|
||||
} catch (err) {
|
||||
addProcessEntry('error', `Open path failed: ${String(err?.message || err)}`);
|
||||
}
|
||||
}
|
||||
|
||||
// KaTeX auto-render must run AFTER the HTML is in the DOM — innerHTML doesn't execute
|
||||
// embedded <script>, so this has to be called explicitly wherever chat HTML gets inserted
|
||||
// (mirrors validateDownloadLinks() right above each call site). mhchem.min.js (loaded in
|
||||
// index.html alongside katex.min.js) extends KaTeX's math mode with \ce{...} for reaction/
|
||||
// formula notation, e.g. $\ce{C4H10}$ or $\ce{2H2 + O2 -> 2H2O}$.
|
||||
function renderKatexIn(container) {
|
||||
if (!window.renderMathInElement || !container) return;
|
||||
try {
|
||||
renderMathInElement(container, {
|
||||
delimiters: [
|
||||
{ left: '$$', right: '$$', display: true },
|
||||
{ left: '\\[', right: '\\]', display: true },
|
||||
{ left: '$', right: '$', display: false },
|
||||
{ left: '\\(', right: '\\)', display: false },
|
||||
],
|
||||
throwOnError: false,
|
||||
});
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
function renderChatMessages() {
|
||||
const container = document.getElementById('chat-messages');
|
||||
|
||||
if (chatHistory.length === 0) {
|
||||
container.innerHTML = `
|
||||
<div class="chat-welcome" id="chat-welcome">
|
||||
<div class="chat-welcome-icon"><img src="/homeclaw_logo.png" alt="🏠"></div>
|
||||
<h2>HomeClaw</h2>
|
||||
<p>Chat directly with your local model. No API keys, no cloud — just you and the model.</p>
|
||||
<div class="hint">Enable Agent mode when you want planning + tool execution in this chat.</div>
|
||||
</div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
container.innerHTML = chatHistory.map((msg, idx) => {
|
||||
const pinClass = contextPinMode ? ' pin-selectable' : '';
|
||||
const selectedClass = (contextPinMode && pinnedMessageIndices.has(idx)) ? ' pin-selected' : '';
|
||||
// Also show green for confirmed pins even outside pin mode
|
||||
const confirmedClass = (!contextPinMode && confirmedPins.some(p => p.content === msg.content && p.role === (msg.role === 'user' ? 'user' : 'assistant'))) ? ' pin-selected' : '';
|
||||
const clickHandler = contextPinMode ? ` onclick="togglePinMessage(${idx})"` : '';
|
||||
if (msg.role === 'widget') {
|
||||
return `<div class="msg widget${pinClass}${selectedClass}${confirmedClass}"${clickHandler}><div class="msg-content">${msg.content}</div></div>`;
|
||||
}
|
||||
return `
|
||||
<div class="msg ${msg.role}${pinClass}${selectedClass}${confirmedClass}"${clickHandler}>
|
||||
<div class="msg-avatar">${msg.role === 'user' ? 'U' : '<img src="/homeclaw_logo.png" style="width:48px;height:48px;border-radius:6px">'}</div>
|
||||
<div class="msg-body">
|
||||
<div class="msg-role">${msg.role === 'user' ? 'You' : (msg.mode === 'agentic' ? 'HomeClaw (Agent)' : 'HomeClaw')}${msg.role === 'ai' ? ` <button class="tts-btn" onclick="playTTSMsg(this,${idx})" title="음성으로 듣기">🔊</button>` : ''}</div>
|
||||
${msg.role === 'ai' ? renderAssistantContent(msg.content) : `<div class="msg-content">${renderMarkdown(msg.display !== undefined ? msg.display : msg.content, { hideDownload: true })}</div>`}
|
||||
${msg.role === 'ai' ? renderArtifacts(msg.artifacts) : ''}
|
||||
${msg.role === 'ai' ? renderFileDownloads(msg.steps, msg.processEntries, msg.content) : ''}
|
||||
${msg.role === 'ai' && msg.processEntries && msg.processEntries.length ? renderProcessPill(msg.processEntries) : ''}
|
||||
${msg.role === 'ai' ? renderThinkBlock(msg.thinking) : ''}
|
||||
${msg.role === 'ai' ? renderReactSteps(msg.steps) : ''}
|
||||
</div>
|
||||
</div>`;
|
||||
}).join('');
|
||||
|
||||
validateDownloadLinks(container);
|
||||
renderKatexIn(container);
|
||||
renderSmilesIn(container);
|
||||
|
||||
if (isThinking && streamingSessionId === activeChatSessionId) {
|
||||
const progressHtml = currentProgressLines.length
|
||||
? `<div style="margin:6px 0 8px 0;font-size:11px;line-height:1.6;color:var(--muted)">
|
||||
${currentProgressLines.map((l) => `<div>• ${escHtml(l)}</div>`).join('')}
|
||||
</div>`
|
||||
: '';
|
||||
container.innerHTML += `
|
||||
<div class="msg ai" id="thinking-msg">
|
||||
<div class="msg-avatar"><img src="/homeclaw_logo.png" style="width:48px;height:48px;border-radius:6px"></div>
|
||||
<div class="msg-body">
|
||||
<div class="msg-role">HomeClaw${useAgentMode ? ' (Agent)' : ''}</div>
|
||||
${currentPreflightStatus ? `<div class="msg-content" style="margin-bottom:6px;color:#26487e">${escHtml(currentPreflightStatus)}</div>` : ''}
|
||||
${progressHtml}
|
||||
<div class="thinking" style="align-items:center">
|
||||
<div class="thinking-dot"></div>
|
||||
<div class="thinking-dot"></div>
|
||||
<div class="thinking-dot"></div>
|
||||
<span id="thinking-elapsed" style="margin-left:8px;font-size:11px;color:var(--muted)"></span>
|
||||
</div>
|
||||
<div style="margin-top:8px">
|
||||
<button class="skill-install-btn" style="font-size:10px;padding:3px 9px" onclick="toggleCurrentProcess()">Process</button>
|
||||
<div id="current-turn-process" style="display:none;margin-top:8px;border:1px solid var(--line);border-radius:10px;background:var(--panel-2);padding:8px;max-height:220px;overflow:auto;font-size:11px;line-height:1.6"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
container.scrollTop = container.scrollHeight;
|
||||
}
|
||||
|
||||
function pushProgressLine(line) {
|
||||
const txt = String(line || '').trim();
|
||||
if (!txt) return;
|
||||
const last = currentProgressLines[currentProgressLines.length - 1] || '';
|
||||
if (last === txt) return;
|
||||
currentProgressLines.push(txt);
|
||||
if (currentProgressLines.length > 8) currentProgressLines = currentProgressLines.slice(-8);
|
||||
if (isThinking) renderChatMessages();
|
||||
}
|
||||
|
||||
// ---- Process log ----
|
||||
function renderProcessPill(entries) {
|
||||
const id = 'proc_' + Math.random().toString(36).slice(2);
|
||||
return `
|
||||
<div style="margin-top:8px">
|
||||
<button class="skill-install-btn" style="font-size:10px;padding:3px 9px" onclick="togglePL('${id}')">Process</button>
|
||||
<div id="${id}" style="display:none;margin-top:8px;border:1px solid var(--line);border-radius:10px;background:var(--panel-2);padding:8px;max-height:220px;overflow:auto;font-size:11px;line-height:1.6">
|
||||
${formatProcessLines(entries)}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function formatProcessLines(entries) {
|
||||
if (!entries || entries.length === 0) return '<div style="color:var(--muted)">No process details.</div>';
|
||||
const TYPE_COLORS = {
|
||||
user: 'var(--text)', think: '#388bfd', tool: '#e3b341',
|
||||
result: '#bc8cff', error: 'var(--red)', final: '#56d364',
|
||||
warn: 'var(--yellow)', step: '#56d364', info: '#79c0ff',
|
||||
split: 'var(--accent2)', synth: 'var(--accent2)',
|
||||
};
|
||||
return entries.map(e => {
|
||||
const rawType = String(e.type || 'info');
|
||||
const typeLabel = escHtml(rawType).toUpperCase();
|
||||
const typeColor = TYPE_COLORS[rawType] || 'var(--muted)';
|
||||
const rawContent = String(e.content || '');
|
||||
// Render markdown for result entries so download links show as clickable buttons
|
||||
const content = rawType === 'result' ? renderMarkdown(rawContent) : escHtml(rawContent);
|
||||
return `<div style="margin-bottom:4px"><span style="color:var(--muted)">[${escHtml(String(e.ts || ''))}]</span> <span style="color:${typeColor};font-weight:600">${typeLabel}</span> ${content}</div>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function toggleCurrentProcess() {
|
||||
const panel = document.getElementById('current-turn-process');
|
||||
if (!panel) return;
|
||||
const open = panel.style.display !== 'none';
|
||||
panel.style.display = open ? 'none' : 'block';
|
||||
if (!open) {
|
||||
const turnEntries = currentTurnStartIndex >= 0 ? processLogEntries.slice(currentTurnStartIndex) : [];
|
||||
panel.innerHTML = formatProcessLines(turnEntries);
|
||||
}
|
||||
}
|
||||
|
||||
function isNearBottom(el, threshold = 40) {
|
||||
if (!el) return true;
|
||||
return (el.scrollHeight - (el.scrollTop + el.clientHeight)) <= threshold;
|
||||
}
|
||||
|
||||
function setupProcessAndRightScrollTracking() {
|
||||
const processEl = document.getElementById('process-log');
|
||||
if (processEl && !processEl.dataset.scrollBound) {
|
||||
processEl.dataset.scrollBound = '1';
|
||||
processEl.addEventListener('scroll', () => {
|
||||
processLogAutoFollow = isNearBottom(processEl, 36);
|
||||
});
|
||||
}
|
||||
|
||||
const rightEl = document.getElementById('right-panel');
|
||||
if (rightEl && !rightEl.dataset.scrollBound) {
|
||||
rightEl.dataset.scrollBound = '1';
|
||||
rightEl.addEventListener('scroll', () => {
|
||||
rightColumnAutoFollow = isNearBottom(rightEl, 28);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function maybeAutoScrollRightColumn(force = false) {
|
||||
const rightEl = document.getElementById('right-panel');
|
||||
if (!rightEl) return;
|
||||
if (force || rightColumnAutoFollow || isThinking) {
|
||||
rightEl.scrollTop = rightEl.scrollHeight;
|
||||
}
|
||||
}
|
||||
|
||||
function updateHeartbeatUI() {
|
||||
const stateEl = document.getElementById('r-heartbeat-state');
|
||||
const metaEl = document.getElementById('r-heartbeat-meta');
|
||||
if (stateEl) {
|
||||
const state = String(lastHeartbeat.state || 'idle').toLowerCase();
|
||||
stateEl.textContent = state || 'idle';
|
||||
stateEl.style.color = state === 'running' || state === 'retrying'
|
||||
? 'var(--warn)'
|
||||
: (state === 'stalled' ? 'var(--err)' : 'var(--text)');
|
||||
}
|
||||
if (metaEl) {
|
||||
const step = String(lastHeartbeat.current_step || '-');
|
||||
const retries = Number(lastHeartbeat.retry_count || 0);
|
||||
const fv = Number(lastHeartbeat.format_violation_count || 0);
|
||||
const lvl = String(lastHeartbeat.level || '').toLowerCase();
|
||||
const lvlTag = lvl ? ` ${lvl}` : '';
|
||||
metaEl.textContent = `step:${step} • retries:${retries} • fv:${fv}${lvlTag}`;
|
||||
}
|
||||
}
|
||||
|
||||
function clearProcessLog() {
|
||||
processLogEntries.length = 0;
|
||||
const el = document.getElementById('process-log');
|
||||
if (el) el.innerHTML = '<div style="color:var(--muted);text-align:center;padding:20px 0;opacity:0.5">활동 대기 중...</div>';
|
||||
processLogAutoFollow = true;
|
||||
rightColumnAutoFollow = true;
|
||||
maybeAutoScrollRightColumn(true);
|
||||
persistActiveChat();
|
||||
}
|
||||
|
||||
function addProcessEntry(type, content, extra) {
|
||||
const ts = new Date().toLocaleTimeString();
|
||||
processLogEntries.push({ ts, type, content, extra });
|
||||
renderProcessLog();
|
||||
maybeAutoScrollRightColumn(isThinking || rightColumnAutoFollow);
|
||||
persistActiveChat();
|
||||
if (isThinking) {
|
||||
const panel = document.getElementById('current-turn-process');
|
||||
if (panel && panel.style.display !== 'none' && currentTurnStartIndex >= 0) {
|
||||
panel.innerHTML = formatProcessLines(processLogEntries.slice(currentTurnStartIndex));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function renderProcessLog() {
|
||||
const el = document.getElementById('process-log');
|
||||
if (!el) return;
|
||||
setupProcessAndRightScrollTracking();
|
||||
const shouldFollow = processLogAutoFollow || isThinking;
|
||||
|
||||
if (processLogEntries.length === 0) {
|
||||
el.innerHTML = '<div style="color:var(--muted);text-align:center;padding:20px 0;opacity:0.5">활동 대기 중...</div>';
|
||||
if (shouldFollow) el.scrollTop = el.scrollHeight;
|
||||
return;
|
||||
}
|
||||
|
||||
el.innerHTML = processLogEntries.map((e,i) => {
|
||||
let icon, color, label, labelColor;
|
||||
switch(e.type) {
|
||||
case 'user': icon='?'; color='var(--accent2)'; labelColor='var(--text)'; label='USER'; break;
|
||||
case 'think': icon='??'; color='#388bfd'; labelColor='#388bfd'; label='THINK'; break;
|
||||
case 'tool': icon='?'; color='#e3b341'; labelColor='#e3b341'; label='TOOL'; break;
|
||||
case 'result': icon='?'; color='#bc8cff'; labelColor='#bc8cff'; label='OK'; break;
|
||||
case 'error': icon='?'; color='var(--red)'; labelColor='var(--red)'; label='FAIL'; break;
|
||||
case 'final': icon='?'; color='#56d364'; labelColor='#56d364'; label='FINAL'; break;
|
||||
case 'warn': icon='?'; color='var(--yellow)'; labelColor='var(--yellow)'; label='WARN'; break;
|
||||
case 'step': icon='?'; color='#56d364'; labelColor='#56d364'; label='STEP'; break;
|
||||
case 'split': icon='?'; color='var(--accent2)'; labelColor='var(--accent2)'; label='SPLIT'; break;
|
||||
case 'synth': icon='?'; color='var(--accent2)'; labelColor='var(--accent2)'; label='SYNTH'; break;
|
||||
case 'info': icon='·'; color='#79c0ff'; labelColor='#79c0ff'; label='INFO'; break;
|
||||
default: icon='·'; color='var(--muted)'; labelColor='var(--muted)'; label=e.type; break;
|
||||
}
|
||||
|
||||
// Think entries: show full content in a scrollable block
|
||||
if (e.type === 'think' && e.content && e.content.length > 60) {
|
||||
const id = 'pl_' + Math.random().toString(36).slice(2,8);
|
||||
const preview = e.content.slice(0, 80).replace(/\n/g,' ');
|
||||
return `
|
||||
<div style="margin-bottom:4px">
|
||||
<span style="color:var(--muted);font-size:10px">${e.ts}</span>
|
||||
<span style="color:${color};margin:0 6px">${icon} <span style="color:${labelColor}">${label}</span></span>
|
||||
<span style="color:var(--muted);cursor:pointer;text-decoration:underline;font-size:10px" onclick="togglePL('${id}')">${escHtml(preview)}…</span>
|
||||
</div>
|
||||
<div id="${id}" style="display:none;background:var(--bg3);border:1px solid var(--border);border-radius:4px;padding:8px;margin-bottom:6px;white-space:pre-wrap;color:var(--muted);font-size:10px;max-height:200px;overflow-y:auto;font-style:italic">${escHtml(e.content)}</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// Tool result entries: collapsible if long
|
||||
if (e.type === 'result' && e.content && e.content.length > 120) {
|
||||
const id = 'pl_' + Math.random().toString(36).slice(2,8);
|
||||
const preview = e.content.slice(0, 100).replace(/\n/g,' ');
|
||||
return `
|
||||
<div style="margin-bottom:4px">
|
||||
<span style="color:var(--muted);font-size:10px">${e.ts}</span>
|
||||
<span style="color:${color};margin:0 6px">${icon} <span style="color:${labelColor}">${label}</span></span>
|
||||
<span style="color:${color};cursor:pointer;font-size:10px" onclick="togglePL('${id}')">${escHtml(preview)}… <span style="opacity:0.5">[expand]</span></span>
|
||||
</div>
|
||||
<div id="${id}" style="display:none;background:var(--bg3);border:1px solid var(--border);border-radius:4px;padding:8px;margin-bottom:6px;white-space:pre-wrap;color:var(--text);font-size:10px;max-height:300px;overflow-y:auto">${escHtml(e.content)}</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// Memory suggestion: show approve/reject buttons
|
||||
if (e.type === 'memory') {
|
||||
const id = 'pl_mem_' + i;
|
||||
const suggest = e.extra || {};
|
||||
return `
|
||||
<div style="margin-bottom:6px">
|
||||
<span style="color:var(--muted);font-size:10px">${e.ts}</span>
|
||||
<span style="color:${color};margin:0 6px">${icon} <span style="color:${labelColor}">${label}</span></span>
|
||||
<span style="color:var(--text);">${escHtml(String(e.content || ''))}</span>
|
||||
<div style="margin-top:6px">
|
||||
<button class="btn btn-sm" onclick="confirmMemory(${i})">Approve</button>
|
||||
<button class="btn btn-sm" style="margin-left:6px" onclick="rejectMemory(${i})">Reject</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// If an 'extra' object/array was provided, show a details toggle
|
||||
if (e.extra) {
|
||||
const id = 'pl_extra_' + i;
|
||||
const pretty = escHtml(JSON.stringify(e.extra, null, 2));
|
||||
return `
|
||||
<div style="margin-bottom:3px">
|
||||
<span style="color:var(--muted);font-size:10px">${e.ts}</span>
|
||||
<span style="color:${color}">${icon} <span style="color:${labelColor}">${label}</span></span>
|
||||
<span style="color:var(--text);margin-left:8px">${escHtml(String(e.content || ''))}</span>
|
||||
<span style="color:var(--muted);cursor:pointer;margin-left:8px;font-size:10px" onclick="togglePL('${id}')">[details]</span>
|
||||
</div>
|
||||
<pre id="${id}" style="display:none;background:var(--bg3);border:1px solid var(--border);border-radius:4px;padding:8px;margin-bottom:6px;color:var(--muted);font-size:11px;max-height:300px;overflow:auto">${pretty}</pre>
|
||||
`;
|
||||
}
|
||||
|
||||
return `<div style="margin-bottom:3px"><span style="color:var(--muted);font-size:10px">${e.ts}</span> <span style="color:${color}">${icon} <span style="color:${labelColor}">${label}</span></span> <span style="color:var(--text)">${escHtml(String(e.content || ''))}</span></div>`;
|
||||
}).join('');
|
||||
|
||||
if (shouldFollow) el.scrollTop = el.scrollHeight;
|
||||
}
|
||||
|
||||
function togglePL(id) {
|
||||
const el = document.getElementById(id);
|
||||
if (el) el.style.display = el.style.display === 'none' ? 'block' : 'none';
|
||||
}
|
||||
|
||||
function isFailedTurnReply(text) {
|
||||
const t = String(text || '').trim().toLowerCase();
|
||||
if (!t) return true;
|
||||
if (/^blocked\b/.test(t)) return true;
|
||||
if (/^no response received\.?$/.test(t)) return true;
|
||||
if (/^connection error:/.test(t)) return true;
|
||||
if (/^sorry, i didn'?t catch that/.test(t)) return true;
|
||||
if (/could not|couldn't/.test(t) && /(verify|format|synthes|extract|read|write|tool|request)/.test(t)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
// ---- Agent Execution Tracking ----
|
||||
function spawnAgentExecution(agentName, taskPrompt, isSubagent = false) {
|
||||
const agentId = (isSubagent ? 'sub_' : 'main_') + (++agentIdCounter);
|
||||
const agentData = {
|
||||
id: agentId,
|
||||
name: agentName,
|
||||
status: AGENT_STATUS.ACTIVE,
|
||||
task: taskPrompt,
|
||||
logs: [],
|
||||
isSubagent: isSubagent,
|
||||
startTime: new Date(),
|
||||
};
|
||||
agentExecutionMap.set(agentId, agentData);
|
||||
renderAgentExecutionPanel();
|
||||
return agentId;
|
||||
}
|
||||
|
||||
function addAgentLog(agentId, type, content) {
|
||||
const agentData = agentExecutionMap.get(agentId);
|
||||
if (!agentData) return;
|
||||
const ts = new Date().toLocaleTimeString();
|
||||
agentData.logs.push({ ts, type, content });
|
||||
// Keep only last 20 logs per agent
|
||||
if (agentData.logs.length > 20) agentData.logs.shift();
|
||||
renderAgentExecutionPanel();
|
||||
}
|
||||
|
||||
function completeAgentExecution(agentId) {
|
||||
const agentData = agentExecutionMap.get(agentId);
|
||||
if (!agentData) return;
|
||||
agentData.status = AGENT_STATUS.COMPLETED;
|
||||
renderAgentExecutionPanel();
|
||||
}
|
||||
|
||||
function pauseAgentExecution(agentId, reason) {
|
||||
const agentData = agentExecutionMap.get(agentId);
|
||||
if (!agentData) return;
|
||||
agentData.status = AGENT_STATUS.PAUSED;
|
||||
if (reason) addAgentLog(agentId, 'error', reason);
|
||||
renderAgentExecutionPanel();
|
||||
}
|
||||
|
||||
function renderAgentExecutionPanel() {
|
||||
const panel = document.getElementById('agent-execution-panel');
|
||||
if (!panel) return;
|
||||
|
||||
if (agentExecutionMap.size === 0) {
|
||||
panel.innerHTML = '<div style="padding:8px 12px;font-size:11px;color:var(--muted)">작업 실행 대기 중...</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
const agents = Array.from(agentExecutionMap.values()).sort((a, b) => a.startTime - b.startTime);
|
||||
panel.innerHTML = agents.map((agent) => {
|
||||
const statusClass = agent.status === AGENT_STATUS.ACTIVE ? 'active' :
|
||||
agent.status === AGENT_STATUS.COMPLETED ? 'completed' : 'paused';
|
||||
const arrow = agent.expanded ? '▼' : '▶';
|
||||
const logsHtml = agent.logs.length > 0
|
||||
? agent.logs.map(log => `<div class="agent-log-entry"><span class="agent-log-entry-time">${escHtml(log.ts)}</span><span class="agent-log-entry-type">[${escHtml(log.type.toUpperCase())}]</span><span class="agent-log-entry-content">${escHtml(log.content)}</span></div>`).join('')
|
||||
: '<div style="color:var(--muted);opacity:0.6">No logs yet</div>';
|
||||
|
||||
return `
|
||||
<div class="agent-item ${agent.expanded ? 'expanded' : ''}" onclick="toggleAgentPanel('${agent.id}')">
|
||||
<div class="agent-item-header">
|
||||
<span style="color:var(--muted);font-size:10px;min-width:12px">${arrow}</span>
|
||||
<div class="agent-item-name">${escHtml(agent.isSubagent ? '└─ ' + agent.name : agent.name)}</div>
|
||||
<div class="agent-item-status ${statusClass}">${agent.status.toUpperCase()}</div>
|
||||
</div>
|
||||
<div class="agent-item-task">${escHtml(agent.task.substring(0, 70))}${agent.task.length > 70 ? '...' : ''}</div>
|
||||
<div class="agent-item-logs">${logsHtml}</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function toggleAgentPanel(agentId) {
|
||||
const agentData = agentExecutionMap.get(agentId);
|
||||
if (!agentData) return;
|
||||
agentData.expanded = !agentData.expanded;
|
||||
renderAgentExecutionPanel();
|
||||
}
|
||||
|
||||
function openProcessLogFile() {
|
||||
// Call server endpoint to open the process log file
|
||||
if (activeTaskId) {
|
||||
fetch(`/api/open-file?task=${encodeURIComponent(activeTaskId)}&type=process`, {
|
||||
headers: authHeaders()
|
||||
})
|
||||
.catch(err => console.error('Unable to open process log:', err));
|
||||
}
|
||||
}
|
||||
|
||||
function clearChat() {
|
||||
chatHistory = [];
|
||||
persistActiveChat();
|
||||
renderChatMessages();
|
||||
}
|
||||
|
||||
function toggleExportMenu(e) {
|
||||
if (e) e.stopPropagation();
|
||||
var menu = document.getElementById('export-menu');
|
||||
if (!menu) return;
|
||||
var opening = menu.style.display === 'none' || !menu.style.display;
|
||||
menu.style.display = opening ? 'block' : 'none';
|
||||
if (opening) {
|
||||
setTimeout(function() {
|
||||
document.addEventListener('click', function closeExport() {
|
||||
menu.style.display = 'none';
|
||||
document.removeEventListener('click', closeExport);
|
||||
});
|
||||
}, 0);
|
||||
}
|
||||
}
|
||||
|
||||
function exportChat(format) {
|
||||
var menu = document.getElementById('export-menu');
|
||||
if (menu) menu.style.display = 'none';
|
||||
|
||||
if (!chatHistory || !chatHistory.length) {
|
||||
alert('내보낼 채팅 내용이 없습니다.');
|
||||
return;
|
||||
}
|
||||
|
||||
var sess = chatSessions.find(function(s) { return s.id === activeChatSessionId; });
|
||||
var title = (sess && sess.title) ? sess.title : '채팅';
|
||||
var dateStr = new Date().toLocaleString('ko-KR');
|
||||
var safeName = title.replace(/[^\w가-힣\s-]/g, '').trim().replace(/\s+/g, '_').slice(0, 40) || 'chat';
|
||||
var dateSuffix = new Date().toISOString().slice(0, 10);
|
||||
var filename = safeName + '_' + dateSuffix;
|
||||
|
||||
var content, mime, ext;
|
||||
|
||||
if (format === 'json') {
|
||||
content = JSON.stringify({
|
||||
title: title,
|
||||
exportedAt: new Date().toISOString(),
|
||||
sessionId: activeChatSessionId,
|
||||
messages: chatHistory.map(function(m) {
|
||||
return { role: m.role, content: (m.display || m.content || '').trim() };
|
||||
})
|
||||
}, null, 2);
|
||||
mime = 'application/json';
|
||||
ext = 'json';
|
||||
|
||||
} else if (format === 'md') {
|
||||
var lines = ['# ' + title, '', '> 내보낸 시간: ' + dateStr, ''];
|
||||
chatHistory.forEach(function(m) {
|
||||
var label = m.role === 'user' ? '## 사용자' : '## 어시스턴트';
|
||||
var text = (m.display || m.content || '').trim();
|
||||
lines.push(label, '', text, '', '---', '');
|
||||
});
|
||||
content = lines.join('\n');
|
||||
mime = 'text/markdown';
|
||||
ext = 'md';
|
||||
|
||||
} else {
|
||||
var lines = [title, '내보낸 시간: ' + dateStr, '='.repeat(50), ''];
|
||||
chatHistory.forEach(function(m) {
|
||||
var label = m.role === 'user' ? '[사용자]' : '[AI]';
|
||||
var text = (m.display || m.content || '').trim()
|
||||
.replace(/!\[[^\]]*\]\([^)]*\)/g, '[이미지]')
|
||||
.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
|
||||
.replace(/[*_`#>]/g, '');
|
||||
lines.push(label, text, '');
|
||||
});
|
||||
content = lines.join('\n');
|
||||
mime = 'text/plain';
|
||||
ext = 'txt';
|
||||
}
|
||||
|
||||
var blob = new Blob([content], { type: mime + '; charset=utf-8' });
|
||||
var a = document.createElement('a');
|
||||
a.href = URL.createObjectURL(blob);
|
||||
a.download = filename + '.' + ext;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
setTimeout(function() { URL.revokeObjectURL(a.href); a.remove(); }, 1000);
|
||||
}
|
||||
|
||||
// Enter to send, Shift+Enter for newline
|
||||
document.getElementById('chat-input').addEventListener('keydown', e => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
sendChat();
|
||||
}
|
||||
});
|
||||
|
||||
// Auto-resize textarea
|
||||
document.getElementById('chat-input').addEventListener('input', function() {
|
||||
this.style.height = 'auto';
|
||||
this.style.height = Math.min(this.scrollHeight, 140) + 'px';
|
||||
});
|
||||
@@ -0,0 +1,244 @@
|
||||
// chat-sessions.js — 채팅 세션 저장/로드/전환/삭제 (sidebar 세션 목록).
|
||||
// extracted from app.js (v4.3.19-3 split).
|
||||
|
||||
function saveChatSessions() {
|
||||
localStorage.setItem(chatSessionsKey(), JSON.stringify(chatSessions));
|
||||
}
|
||||
|
||||
function makeSessionTitle(history) {
|
||||
const firstUser = (history || []).find(m => m.role === 'user');
|
||||
if (!firstUser) return 'New chat';
|
||||
// Strip markdown image/link syntax for clean session title
|
||||
let text = firstUser.content
|
||||
.replace(/!\[[^\]]*\]\([^)]+\)/g, '[image]')
|
||||
.replace(/\[[^\]]+\]\([^)]+\)/g, (m) => m.replace(/\[([^\]]*)\].*/, '$1'))
|
||||
.replace(/```[\s\S]*?```/g, '')
|
||||
.replace(/\n/g, ' ')
|
||||
.trim();
|
||||
return text.slice(0, 42) || 'New chat';
|
||||
}
|
||||
|
||||
function loadChatSessions() {
|
||||
const key = chatSessionsKey();
|
||||
try {
|
||||
const raw = localStorage.getItem(key);
|
||||
if (raw) {
|
||||
chatSessions = JSON.parse(raw);
|
||||
} else {
|
||||
// Migrate from old non-namespaced key once, then delete it so other users can't see it.
|
||||
const oldRaw = localStorage.getItem(CHAT_SESSIONS_KEY_BASE);
|
||||
if (oldRaw) {
|
||||
chatSessions = JSON.parse(oldRaw);
|
||||
localStorage.setItem(key, oldRaw);
|
||||
localStorage.removeItem(CHAT_SESSIONS_KEY_BASE);
|
||||
} else {
|
||||
chatSessions = [];
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
chatSessions = [];
|
||||
}
|
||||
if (!Array.isArray(chatSessions)) chatSessions = [];
|
||||
let isFreshDevice = false;
|
||||
if (chatSessions.length === 0) {
|
||||
isFreshDevice = true;
|
||||
const id = crypto?.randomUUID?.() || ('chat_' + Math.random().toString(36).slice(2));
|
||||
chatSessions.push({ id, title: 'New chat', history: [], processLog: [], createdAt: Date.now(), updatedAt: Date.now() });
|
||||
activeChatSessionId = id;
|
||||
setAgentSessionId(id);
|
||||
saveChatSessions();
|
||||
} else if (!activeChatSessionId || !chatSessions.some(s => s.id === activeChatSessionId)) {
|
||||
activeChatSessionId = chatSessions[0].id;
|
||||
setAgentSessionId(activeChatSessionId);
|
||||
}
|
||||
if (!agentSessionId || agentSessionId !== activeChatSessionId) setAgentSessionId(activeChatSessionId);
|
||||
syncActiveChat();
|
||||
// 서버 세션 목록과 비교해 누락된 세션을 사이드바에 추가
|
||||
syncServerSessions();
|
||||
// 새 기기에서 처음 열었다면, 다른 기기에서 이어가던 대화로 자동 복귀
|
||||
if (isFreshDevice) resumeMainSessionPointer();
|
||||
}
|
||||
|
||||
// 메인챗의 "마지막 활성 세션"을 서버에 기록 — 다른 기기에서 새로 열었을 때 이어보기용
|
||||
function updateMainSessionPointer(id) {
|
||||
if (!id) return;
|
||||
api('/api/user/app-sessions', { method: 'PUT', body: JSON.stringify({ appKey: 'main', sessionId: id }) }).catch(() => {});
|
||||
}
|
||||
|
||||
async function resumeMainSessionPointer() {
|
||||
try {
|
||||
const d = await api('/api/user/app-sessions');
|
||||
const ptr = d && d.main;
|
||||
if (!ptr) { updateMainSessionPointer(activeChatSessionId); return; } // 최초 로그인: 이 세션을 기준점으로 등록
|
||||
if (ptr === activeChatSessionId) return;
|
||||
const cur = chatSessions.find(s => s.id === activeChatSessionId);
|
||||
if (cur && cur.history && cur.history.length > 0) return; // 이미 이 기기에서 대화가 시작됐으면 건드리지 않음
|
||||
const hd = await api('/api/chat/sessions/' + encodeURIComponent(ptr));
|
||||
if (!hd || !hd.success || !Array.isArray(hd.history) || hd.history.length === 0) return;
|
||||
// 비어있던 자리표시자 세션은 제거하고 포인터가 가리키는 세션으로 전환
|
||||
chatSessions = chatSessions.filter(s => s.id !== activeChatSessionId);
|
||||
let existing = chatSessions.find(s => s.id === ptr);
|
||||
if (!existing) {
|
||||
existing = { id: ptr, title: makeSessionTitle(hd.history), history: hd.history, processLog: [], createdAt: hd.createdAt || Date.now(), updatedAt: hd.lastActiveAt || Date.now() };
|
||||
chatSessions.unshift(existing);
|
||||
} else {
|
||||
existing.history = hd.history;
|
||||
delete existing.serverOnly;
|
||||
}
|
||||
activeChatSessionId = ptr;
|
||||
setAgentSessionId(ptr);
|
||||
saveChatSessions();
|
||||
syncActiveChat();
|
||||
} catch { /* 서버 미응답 시 무시 */ }
|
||||
}
|
||||
|
||||
async function syncServerSessions() {
|
||||
try {
|
||||
const res = await fetch('/api/chat/sessions');
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
if (!data.success || !Array.isArray(data.sessions)) return;
|
||||
let changed = false;
|
||||
for (const srv of data.sessions) {
|
||||
const existing = chatSessions.find(s => s.id === srv.id);
|
||||
if (!existing) {
|
||||
// 서버에만 있는 세션 → 스텁으로 추가 (history는 열 때 로드)
|
||||
chatSessions.push({
|
||||
id: srv.id,
|
||||
title: srv.title || 'New chat',
|
||||
history: [],
|
||||
processLog: [],
|
||||
createdAt: srv.createdAt,
|
||||
updatedAt: srv.lastActiveAt,
|
||||
serverOnly: true, // 열 때 서버에서 history 로드
|
||||
});
|
||||
changed = true;
|
||||
} else if (existing.serverOnly) {
|
||||
// 이미 스텁으로 있으면 메타만 업데이트
|
||||
existing.title = srv.title || existing.title;
|
||||
existing.updatedAt = srv.lastActiveAt;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (changed) {
|
||||
saveChatSessions();
|
||||
renderSessionsList();
|
||||
}
|
||||
} catch { /* 서버 미응답 시 무시 */ }
|
||||
}
|
||||
|
||||
function syncActiveChat() {
|
||||
const sess = chatSessions.find(s => s.id === activeChatSessionId);
|
||||
chatHistory = sess ? (sess.history || []) : [];
|
||||
processLogEntries = sess ? (sess.processLog || []) : [];
|
||||
liveTaskSteps = []; // clear live steps so a different session never inherits in-progress tool display
|
||||
// Mark session as read when opening it
|
||||
if (sess) sess.unread = false;
|
||||
renderChatMessages();
|
||||
renderProcessLog();
|
||||
renderLiveStepsPanel();
|
||||
renderSessionsList();
|
||||
updateStats([]);
|
||||
loadAgentSessionContext();
|
||||
}
|
||||
|
||||
function persistActiveChat() {
|
||||
const idx = chatSessions.findIndex(s => s.id === activeChatSessionId);
|
||||
if (idx === -1) return;
|
||||
chatSessions[idx].history = chatHistory;
|
||||
chatSessions[idx].processLog = processLogEntries;
|
||||
chatSessions[idx].title = makeSessionTitle(chatHistory);
|
||||
chatSessions[idx].updatedAt = Date.now();
|
||||
saveChatSessions();
|
||||
renderSessionsList();
|
||||
updateStats([]);
|
||||
}
|
||||
|
||||
function newChatSession() {
|
||||
const id = crypto?.randomUUID?.() || ('chat_' + Math.random().toString(36).slice(2));
|
||||
chatSessions.unshift({ id, title: 'New chat', history: [], processLog: [], createdAt: Date.now(), updatedAt: Date.now() });
|
||||
activeChatSessionId = id;
|
||||
setAgentSessionId(id);
|
||||
syncActiveChat();
|
||||
updateMainSessionPointer(id);
|
||||
}
|
||||
|
||||
function toggleSessionsEditMode() {
|
||||
sessionsEditMode = !sessionsEditMode;
|
||||
const btn = document.getElementById('sessions-edit-btn');
|
||||
if (btn) btn.textContent = sessionsEditMode ? '완료' : '편집';
|
||||
renderSessionsList();
|
||||
}
|
||||
|
||||
function deleteChatSession(id, ev) {
|
||||
if (ev) ev.stopPropagation();
|
||||
const idx = chatSessions.findIndex(s => s.id === id);
|
||||
if (idx === -1) return;
|
||||
|
||||
chatSessions.splice(idx, 1);
|
||||
if (chatSessions.length === 0) {
|
||||
const newId = crypto?.randomUUID?.() || ('chat_' + Math.random().toString(36).slice(2));
|
||||
chatSessions.push({ id: newId, title: 'New chat', history: [], processLog: [], createdAt: Date.now(), updatedAt: Date.now() });
|
||||
activeChatSessionId = newId;
|
||||
setAgentSessionId(newId);
|
||||
} else if (activeChatSessionId === id) {
|
||||
activeChatSessionId = chatSessions[0].id;
|
||||
setAgentSessionId(activeChatSessionId);
|
||||
}
|
||||
|
||||
saveChatSessions();
|
||||
syncActiveChat();
|
||||
updateMainSessionPointer(activeChatSessionId);
|
||||
// 서버 세션 파일도 삭제 (재로드 시 재등장 방지)
|
||||
api(`/api/chat/sessions/${id}`, { method: 'DELETE' }).catch(() => {});
|
||||
}
|
||||
|
||||
function openSession(id) {
|
||||
activeChatSessionId = id;
|
||||
setAgentSessionId(id);
|
||||
updateMainSessionPointer(id);
|
||||
const sess = chatSessions.find(s => s.id === id);
|
||||
if (sess && sess.serverOnly && sess.history.length === 0) {
|
||||
// 서버에서 history 로드 후 렌더
|
||||
fetch(`/api/chat/sessions/${id}`)
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
if (data.success && Array.isArray(data.history)) {
|
||||
sess.history = data.history;
|
||||
sess.title = makeSessionTitle(data.history) || sess.title;
|
||||
delete sess.serverOnly;
|
||||
saveChatSessions();
|
||||
syncActiveChat();
|
||||
renderSessionsList();
|
||||
}
|
||||
})
|
||||
.catch(() => syncActiveChat());
|
||||
renderSessionsList(); // 즉시 세션 활성화 표시
|
||||
return;
|
||||
}
|
||||
syncActiveChat();
|
||||
}
|
||||
|
||||
function markSessionUnread(sessionId) {
|
||||
const sess = chatSessions.find(s => s.id === sessionId);
|
||||
if (sess && sessionId !== activeChatSessionId) {
|
||||
sess.unread = true;
|
||||
renderSessionsList();
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Mode switching ----
|
||||
function setMode(mode) {
|
||||
if (!['chat','bgtasks'].includes(mode)) mode = 'chat';
|
||||
currentMode = mode;
|
||||
document.getElementById('chat-view').style.display = mode === 'chat' ? 'flex' : 'none';
|
||||
const bgtView = document.getElementById('bgtasks-view');
|
||||
if (bgtView) bgtView.style.display = mode === 'bgtasks' ? 'flex' : 'none';
|
||||
const aside = document.querySelector('aside');
|
||||
const rightPanel = document.getElementById('right-panel');
|
||||
if (aside) aside.style.display = '';
|
||||
if (rightPanel) rightPanel.style.display = mode === 'chat' ? '' : 'none';
|
||||
// sidebar tab 하이라이트 동기화
|
||||
document.getElementById('tab-bgtasks')?.classList.toggle('active', mode === 'bgtasks');
|
||||
if (mode === 'bgtasks') refreshBgTasks();
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,286 @@
|
||||
// error-panel.js — 작업 실패 시 사용자 응답이 필요한 에러 패널 + WebSocket 패치.
|
||||
// extracted from app.js (v4.3.19-3 split).
|
||||
|
||||
let _errTaskId = null;
|
||||
let _errTemplate = null;
|
||||
let _errSelectedAction = null;
|
||||
let _errCategory = null;
|
||||
let _errBackdrop = null;
|
||||
|
||||
function _getOrCreateErrorBackdrop() {
|
||||
if (_errBackdrop) return _errBackdrop;
|
||||
_errBackdrop = document.createElement('div');
|
||||
_errBackdrop.id = 'error-response-backdrop';
|
||||
_errBackdrop.style.cssText = 'position:fixed;inset:0;background:rgba(10,20,40,0.45);z-index:9997;display:none';
|
||||
_errBackdrop.addEventListener('click', closeErrorResponse);
|
||||
document.body.appendChild(_errBackdrop);
|
||||
return _errBackdrop;
|
||||
}
|
||||
|
||||
function showErrorResponsePanel(taskId, category, errorMessage, errorDetail, template) {
|
||||
_errTaskId = taskId;
|
||||
_errTemplate = template;
|
||||
_errSelectedAction = null;
|
||||
_errCategory = category;
|
||||
|
||||
// Title & description
|
||||
const titleEl = document.getElementById('error-response-title');
|
||||
const descEl = document.getElementById('error-response-desc');
|
||||
if (titleEl) titleEl.textContent = template?.title || ('\u26a0\ufe0f ' + (category || 'Error').toUpperCase());
|
||||
if (descEl) descEl.textContent = template?.description || errorMessage || 'The task needs your help to continue.';
|
||||
|
||||
// Render options
|
||||
const optionsEl = document.getElementById('error-response-options');
|
||||
if (optionsEl) {
|
||||
optionsEl.innerHTML = '';
|
||||
const options = template?.options || [
|
||||
{ id: 'retry_now', label: '\u27f3 Retry Now', icon: '\u27f3' },
|
||||
{ id: 'skip', label: '\u229a Skip Step', icon: '\u229a' },
|
||||
{ id: 'cancel', label: '\u2715 Cancel Task', icon: '\u2715', danger: true },
|
||||
];
|
||||
options.forEach(opt => {
|
||||
const btn = document.createElement('button');
|
||||
btn.className = 'error-option-btn' + (opt.danger ? ' danger' : '');
|
||||
btn.dataset.actionId = opt.id;
|
||||
btn.innerHTML = `<strong>${escHtml(opt.icon || '')} ${escHtml(opt.label)}</strong>${opt.description ? `<br><span style="font-weight:400;opacity:0.75">${escHtml(opt.description)}</span>` : ''}`;
|
||||
btn.addEventListener('click', () => selectErrorOption(opt));
|
||||
optionsEl.appendChild(btn);
|
||||
});
|
||||
}
|
||||
|
||||
// Clear inputs
|
||||
const inputsEl = document.getElementById('error-response-inputs');
|
||||
if (inputsEl) {
|
||||
inputsEl.innerHTML = '';
|
||||
inputsEl.classList.remove('visible');
|
||||
}
|
||||
|
||||
// Reset submit button
|
||||
const submitBtn = document.getElementById('error-response-submit-btn');
|
||||
if (submitBtn) submitBtn.disabled = true;
|
||||
|
||||
// Show backdrop + panel
|
||||
const backdrop = _getOrCreateErrorBackdrop();
|
||||
backdrop.style.display = 'block';
|
||||
const panel = document.getElementById('error-response-panel');
|
||||
if (panel) panel.classList.add('visible');
|
||||
|
||||
// Notification toast
|
||||
bgtToast('\u26a0\ufe0f Task needs help', (template?.title || category || 'Error') + ' — see panel');
|
||||
}
|
||||
|
||||
function selectErrorOption(opt) {
|
||||
_errSelectedAction = opt.id;
|
||||
|
||||
// Highlight selected
|
||||
document.querySelectorAll('.error-option-btn').forEach(b => b.classList.remove('selected'));
|
||||
const btn = document.querySelector(`.error-option-btn[data-action-id="${opt.id}"]`);
|
||||
if (btn) btn.classList.add('selected');
|
||||
|
||||
// Show input fields if this option requires them
|
||||
const inputsEl = document.getElementById('error-response-inputs');
|
||||
if (inputsEl) {
|
||||
inputsEl.innerHTML = '';
|
||||
inputsEl.classList.remove('visible');
|
||||
|
||||
const triggerInputs = opt.triggerInputs || [];
|
||||
const allFields = _errTemplate?.requiredInputs || [];
|
||||
const fieldsToShow = triggerInputs.length > 0
|
||||
? allFields.filter(f => triggerInputs.includes(f.id))
|
||||
: [];
|
||||
|
||||
if (fieldsToShow.length > 0) {
|
||||
fieldsToShow.forEach(field => {
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'input-field';
|
||||
const label = document.createElement('label');
|
||||
label.textContent = field.label;
|
||||
label.setAttribute('for', 'err-input-' + field.id);
|
||||
const input = document.createElement('input');
|
||||
input.id = 'err-input-' + field.id;
|
||||
input.type = field.type || 'text';
|
||||
input.placeholder = field.placeholder || '';
|
||||
input.dataset.fieldId = field.id;
|
||||
if (field.validation === 'digits_only') {
|
||||
input.inputMode = 'numeric';
|
||||
input.pattern = '[0-9]*';
|
||||
input.maxLength = 8;
|
||||
}
|
||||
wrap.appendChild(label);
|
||||
wrap.appendChild(input);
|
||||
inputsEl.appendChild(wrap);
|
||||
});
|
||||
inputsEl.classList.add('visible');
|
||||
// Focus first input
|
||||
const firstInput = inputsEl.querySelector('input');
|
||||
if (firstInput) setTimeout(() => firstInput.focus(), 80);
|
||||
}
|
||||
}
|
||||
|
||||
// Enable submit unless it's cancel (which submits immediately)
|
||||
const submitBtn = document.getElementById('error-response-submit-btn');
|
||||
if (submitBtn) {
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = opt.danger ? '작업 취소' : '계속';
|
||||
}
|
||||
}
|
||||
|
||||
function closeErrorResponse() {
|
||||
_errTaskId = null;
|
||||
_errTemplate = null;
|
||||
_errSelectedAction = null;
|
||||
_errCategory = null;
|
||||
|
||||
const backdrop = document.getElementById('error-response-backdrop');
|
||||
if (backdrop) backdrop.style.display = 'none';
|
||||
const panel = document.getElementById('error-response-panel');
|
||||
if (panel) panel.classList.remove('visible');
|
||||
}
|
||||
|
||||
async function submitErrorResponse() {
|
||||
if (!_errTaskId || !_errSelectedAction) return;
|
||||
|
||||
const action = _errSelectedAction;
|
||||
const category = _errCategory;
|
||||
|
||||
// Collect input values
|
||||
const inputs = {};
|
||||
document.querySelectorAll('#error-response-inputs input[data-field-id]').forEach(el => {
|
||||
if (el.value.trim()) inputs[el.dataset.fieldId] = el.value.trim();
|
||||
});
|
||||
|
||||
// Validate required fields for credential action
|
||||
if (action === 'credentials') {
|
||||
if (!inputs.email) {
|
||||
const emailEl = document.getElementById('err-input-email');
|
||||
if (emailEl) { emailEl.style.borderColor = 'var(--err)'; emailEl.focus(); }
|
||||
return;
|
||||
}
|
||||
if (!inputs.password) {
|
||||
const pwEl = document.getElementById('err-input-password');
|
||||
if (pwEl) { pwEl.style.borderColor = 'var(--err)'; pwEl.focus(); }
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (action === 'verification_code') {
|
||||
if (!inputs.code) {
|
||||
const codeEl = document.getElementById('err-input-code');
|
||||
if (codeEl) { codeEl.style.borderColor = 'var(--err)'; codeEl.focus(); }
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Disable submit to prevent double-send
|
||||
const submitBtn = document.getElementById('error-response-submit-btn');
|
||||
if (submitBtn) { submitBtn.disabled = true; submitBtn.textContent = '전송 중…'; }
|
||||
|
||||
try {
|
||||
const resp = await fetch(`/api/bg-tasks/${_errTaskId}/error-response`, {
|
||||
method: 'POST',
|
||||
headers: authHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify({ action, category, inputs }),
|
||||
});
|
||||
const data = await resp.json();
|
||||
if (data.success) {
|
||||
closeErrorResponse();
|
||||
if (data.resumed) {
|
||||
bgtToast('\u2705 Task resuming', 'Agent is continuing with your response');
|
||||
// Refresh the kanban board to show updated status
|
||||
if (typeof refreshBgTasks === 'function') setTimeout(refreshBgTasks, 800);
|
||||
} else {
|
||||
bgtToast('Task cancelled', 'Task has been stopped');
|
||||
if (typeof refreshBgTasks === 'function') setTimeout(refreshBgTasks, 400);
|
||||
}
|
||||
} else {
|
||||
bgtToast('\u274c Error', data.error || 'Failed to submit response');
|
||||
if (submitBtn) { submitBtn.disabled = false; submitBtn.textContent = '계속'; }
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[ErrorResponse] Submit failed:', err);
|
||||
bgtToast('\u274c Network error', 'Could not submit response');
|
||||
if (submitBtn) { submitBtn.disabled = false; submitBtn.textContent = '계속'; }
|
||||
}
|
||||
}
|
||||
|
||||
// Hook into the existing WebSocket message handler
|
||||
// We extend the onmessage handler after the page loads
|
||||
(function patchWebSocketForErrorResponse() {
|
||||
function applyPatch() {
|
||||
// Find the ws variable — it’s declared in a closure, so we intercept via MutationObserver
|
||||
// Alternative: override addEventListener on WebSocket prototype to intercept messages
|
||||
const _origOnMessage = WebSocket.prototype.__defineGetter__
|
||||
? null
|
||||
: null; // not needed — use event listener approach below
|
||||
|
||||
// We hook into the document-level custom event that server-v2’s WS handler
|
||||
// already dispatches. If that’s not available, we’ll patch the WS directly.
|
||||
document.addEventListener('ws:message', handleErrorResponseWsEvent);
|
||||
|
||||
// Also directly patch any open WebSocket connections by overriding WebSocket prototype
|
||||
const _OrigWS = window.WebSocket;
|
||||
window.WebSocket = function(...args) {
|
||||
const ws = new _OrigWS(...args);
|
||||
const _origAddEventListener = ws.addEventListener.bind(ws);
|
||||
ws.addEventListener = function(type, listener, ...rest) {
|
||||
if (type === 'message') {
|
||||
const wrappedListener = function(e) {
|
||||
try {
|
||||
const msg = JSON.parse(e.data);
|
||||
if (msg.type === 'task_error_requires_response') {
|
||||
handleErrorResponseWsEvent({ detail: msg });
|
||||
}
|
||||
} catch {}
|
||||
return listener.call(this, e);
|
||||
};
|
||||
return _origAddEventListener('message', wrappedListener, ...rest);
|
||||
}
|
||||
return _origAddEventListener(type, listener, ...rest);
|
||||
};
|
||||
// Also patch onmessage setter
|
||||
let _onmsgHandler = null;
|
||||
Object.defineProperty(ws, 'onmessage', {
|
||||
get: () => _onmsgHandler,
|
||||
set: (fn) => {
|
||||
_onmsgHandler = fn;
|
||||
_origAddEventListener('message', (e) => {
|
||||
try {
|
||||
const msg = JSON.parse(e.data);
|
||||
if (msg.type === 'task_error_requires_response') {
|
||||
handleErrorResponseWsEvent({ detail: msg });
|
||||
}
|
||||
} catch {}
|
||||
if (_onmsgHandler) _onmsgHandler.call(ws, e);
|
||||
});
|
||||
},
|
||||
configurable: true,
|
||||
});
|
||||
return ws;
|
||||
};
|
||||
// Copy static properties
|
||||
Object.assign(window.WebSocket, _OrigWS);
|
||||
window.WebSocket.prototype = _OrigWS.prototype;
|
||||
window.WebSocket.CONNECTING = _OrigWS.CONNECTING;
|
||||
window.WebSocket.OPEN = _OrigWS.OPEN;
|
||||
window.WebSocket.CLOSING = _OrigWS.CLOSING;
|
||||
window.WebSocket.CLOSED = _OrigWS.CLOSED;
|
||||
}
|
||||
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', applyPatch);
|
||||
} else {
|
||||
applyPatch();
|
||||
}
|
||||
})();
|
||||
|
||||
function handleErrorResponseWsEvent(e) {
|
||||
const msg = e.detail || e;
|
||||
if (!msg || msg.type !== 'task_error_requires_response') return;
|
||||
showErrorResponsePanel(
|
||||
msg.taskId,
|
||||
msg.errorCategory,
|
||||
msg.errorMessage,
|
||||
msg.errorDetail,
|
||||
msg.template,
|
||||
);
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,340 @@
|
||||
// integrations.js — 웹훅 설정 + MCP 서버 연동 관리.
|
||||
// extracted from app.js (v4.3.19-3 split).
|
||||
|
||||
let _integTab = 'webhooks';
|
||||
|
||||
function setIntegTab(tab) {
|
||||
_integTab = tab;
|
||||
['webhooks', 'mcp'].forEach(t => {
|
||||
const btn = document.getElementById('itab-' + t);
|
||||
const panel = document.getElementById('itab-panel-' + t);
|
||||
if (btn) {
|
||||
btn.style.background = t === tab ? '#eaf2ff' : '#fff';
|
||||
btn.style.color = t === tab ? '#0d4faf' : 'var(--muted)';
|
||||
btn.style.borderColor = t === tab ? '#bdd3f6' : 'var(--line)';
|
||||
}
|
||||
if (panel) panel.style.display = t === tab ? 'block' : 'none';
|
||||
});
|
||||
}
|
||||
|
||||
async function loadIntegrationsTab() {
|
||||
setIntegTab(_integTab);
|
||||
await loadWebhookSettings();
|
||||
await loadMCPServers();
|
||||
}
|
||||
|
||||
// --- Webhooks -----------------------------------------------------------------
|
||||
|
||||
async function loadWebhookSettings() {
|
||||
try {
|
||||
const data = await api('/api/settings/hooks');
|
||||
const h = data.hooks || {};
|
||||
const cb = document.getElementById('wh-enabled');
|
||||
const inp = document.getElementById('wh-token');
|
||||
const pathInp = document.getElementById('wh-path');
|
||||
if (cb) cb.checked = h.enabled === true;
|
||||
if (inp) inp.value = h.tokenSet ? '••••••••' : '';
|
||||
if (pathInp) pathInp.value = h.path || '/hooks';
|
||||
updateWebhookStatus(h.enabled, h.tokenSet);
|
||||
updateWebhookUrlDisplay(h.enabled, h.tokenSet, h.path || '/hooks');
|
||||
} catch(e) {
|
||||
console.warn('loadWebhookSettings:', e);
|
||||
}
|
||||
}
|
||||
|
||||
function updateWebhookStatus(enabled, tokenSet) {
|
||||
const dot = document.getElementById('wh-status-dot');
|
||||
const txt = document.getElementById('wh-status-text');
|
||||
if (!dot || !txt) return;
|
||||
if (enabled && tokenSet) {
|
||||
dot.style.background = '#22c55e';
|
||||
txt.textContent = '활성 — 엔드포인트 실행 중';
|
||||
txt.style.color = '#166534';
|
||||
} else if (!enabled) {
|
||||
dot.style.background = '#ccc';
|
||||
txt.textContent = '비활성';
|
||||
txt.style.color = 'var(--muted)';
|
||||
} else {
|
||||
dot.style.background = '#f59e0b';
|
||||
txt.textContent = '활성화됨 — 토큰 미설정';
|
||||
txt.style.color = '#92400e';
|
||||
}
|
||||
}
|
||||
|
||||
function updateWebhookUrlDisplay(enabled, tokenSet, hookPath) {
|
||||
const el = document.getElementById('wh-url-display');
|
||||
if (!el) return;
|
||||
if (enabled && tokenSet) {
|
||||
const origin = window.location.origin || 'http://localhost:18789';
|
||||
el.style.display = 'block';
|
||||
el.textContent = origin + hookPath + '/agent';
|
||||
} else {
|
||||
el.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
function generateWebhookToken() {
|
||||
const arr = new Uint8Array(24);
|
||||
crypto.getRandomValues(arr);
|
||||
const token = Array.from(arr).map(b => b.toString(16).padStart(2,'0')).join('');
|
||||
const inp = document.getElementById('wh-token');
|
||||
if (inp) { inp.value = token; inp.type = 'text'; setTimeout(() => { inp.type = 'password'; }, 4000); }
|
||||
}
|
||||
|
||||
async function saveWebhookSettings() {
|
||||
const enabled = document.getElementById('wh-enabled')?.checked ?? false;
|
||||
const rawToken = document.getElementById('wh-token')?.value?.trim() || '';
|
||||
const hookPath = document.getElementById('wh-path')?.value?.trim() || '/hooks';
|
||||
try {
|
||||
const r = await api('/api/settings/hooks', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ enabled, token: rawToken, path: hookPath }),
|
||||
});
|
||||
if (r.success) {
|
||||
await loadWebhookSettings();
|
||||
showIntegMsg('? Webhook settings saved — restart gateway to apply', '#166534', '#f0fdf4');
|
||||
} else {
|
||||
showIntegMsg('Error: ' + (r.error || 'Unknown error'), '#991b1b', '#fef2f2');
|
||||
}
|
||||
} catch(e) {
|
||||
showIntegMsg('Save failed: ' + e.message, '#991b1b', '#fef2f2');
|
||||
}
|
||||
}
|
||||
|
||||
async function testWebhookEndpoint() {
|
||||
try {
|
||||
const r = await api('/api/settings/hooks/test', { method: 'POST' });
|
||||
if (r.success) {
|
||||
showIntegMsg('? ' + (r.message || 'Endpoint is active'), '#166534', '#f0fdf4');
|
||||
} else {
|
||||
showIntegMsg('? ' + (r.error || 'Test failed'), '#991b1b', '#fef2f2');
|
||||
}
|
||||
} catch(e) {
|
||||
showIntegMsg('Test failed: ' + e.message, '#991b1b', '#fef2f2');
|
||||
}
|
||||
}
|
||||
|
||||
function copyWebhookCurl() {
|
||||
const origin = window.location.origin || 'http://localhost:18789';
|
||||
const hookPath = document.getElementById('wh-path')?.value?.trim() || '/hooks';
|
||||
const curl = `curl -X POST ${origin}${hookPath}/agent \\
|
||||
-H "X-Gateway-Token: YOUR_TOKEN" \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-d '{"message": "Hello from webhook", "name": "MyApp", "deliver": true}'`;
|
||||
navigator.clipboard?.writeText(curl).then(() => {
|
||||
showIntegMsg('cURL example copied to clipboard', '#1e40af', '#eff6ff');
|
||||
}).catch(() => {
|
||||
showIntegMsg('Could not copy — check browser permissions', '#92400e', '#fffbeb');
|
||||
});
|
||||
}
|
||||
|
||||
// --- MCP ---------------------------------------------------------------------
|
||||
|
||||
let _mcpEditingId = null;
|
||||
|
||||
const MCP_PRESETS = {
|
||||
filesystem: { name: 'Filesystem', transport: 'stdio', command: 'npx', args: '-y\n@modelcontextprotocol/server-filesystem\nC:\\Users', env: '', description: 'Read/write local files' },
|
||||
github: { name: 'GitHub', transport: 'stdio', command: 'npx', args: '-y\n@modelcontextprotocol/server-github', env: 'GITHUB_PERSONAL_ACCESS_TOKEN=', description: 'Repos, PRs, issues' },
|
||||
postgres: { name: 'PostgreSQL', transport: 'stdio', command: 'npx', args: '-y\n@modelcontextprotocol/server-postgres\npostgresql://localhost/mydb', env: '', description: 'Query PostgreSQL' },
|
||||
sqlite: { name: 'SQLite', transport: 'stdio', command: 'npx', args: '-y\n@modelcontextprotocol/server-sqlite\n--db-path\nC:\\path\\to\\db.sqlite', env: '', description: 'Local database' },
|
||||
brave: { name: 'Brave Search', transport: 'stdio', command: 'npx', args: '-y\n@modelcontextprotocol/server-brave-search', env: 'BRAVE_API_KEY=', description: 'Web search' },
|
||||
memory: { name: 'Memory', transport: 'stdio', command: 'npx', args: '-y\n@modelcontextprotocol/server-memory', env: '', description: 'Persistent knowledge store' },
|
||||
};
|
||||
|
||||
async function loadMCPServers() {
|
||||
const el = document.getElementById('mcp-server-list');
|
||||
if (!el) return;
|
||||
try {
|
||||
const data = await api('/api/mcp/servers');
|
||||
const servers = data.servers || [];
|
||||
if (servers.length === 0) {
|
||||
el.innerHTML = '<div style="color:var(--muted);font-style:italic;padding:8px 0">No MCP servers configured yet.<br>Add one above or click a preset on the right.</div>';
|
||||
return;
|
||||
}
|
||||
el.innerHTML = servers.map(s => {
|
||||
const statusColor = s.status === 'connected' ? '#22c55e' : s.status === 'error' ? '#ef4444' : s.status === 'connecting' ? '#f59e0b' : '#9ca3af';
|
||||
const statusLabel = s.status === 'connected' ? `Connected · ${s.toolCount} tool${s.toolCount !== 1 ? 's' : ''}` : s.status === 'error' ? 'Error' : s.status === 'connecting' ? 'Connecting…' : 'Disconnected';
|
||||
const toolTip = s.toolNames?.length ? s.toolNames.join(', ') : '';
|
||||
return `<div style="display:flex;align-items:flex-start;gap:8px;padding:8px;border:1px solid var(--line);border-radius:8px;margin-bottom:6px;background:${s.enabled ? '#fff' : '#fafafa'}">
|
||||
<div style="padding-top:2px">
|
||||
<div style="width:8px;height:8px;border-radius:50%;background:${statusColor};flex-shrink:0"></div>
|
||||
</div>
|
||||
<div style="flex:1;min-width:0">
|
||||
<div style="font-weight:600;font-size:12px;color:var(--text)">${escHtml(s.name)} <span style="font-weight:400;color:var(--muted);font-size:11px">(${escHtml(s.id)})</span></div>
|
||||
<div style="font-size:11px;color:${statusColor};margin-top:1px" title="${escHtml(toolTip)}">${statusLabel}${s.error ? ` — ${escHtml(s.error.slice(0,60))}` : ''}</div>
|
||||
${toolTip ? `<div style="font-size:10px;color:var(--muted);margin-top:2px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${escHtml(toolTip)}">${escHtml(toolTip.slice(0,80))}${toolTip.length>80?'…':''}</div>` : ''}
|
||||
</div>
|
||||
<div style="display:flex;gap:4px;flex-shrink:0">
|
||||
${s.status === 'connected'
|
||||
? `<button onclick="disconnectMCPServer('${s.id}')" style="padding:3px 8px;border:1px solid var(--line);border-radius:5px;background:#fff;font-size:10px;cursor:pointer">Disconnect</button>`
|
||||
: `<button onclick="connectMCPServer('${s.id}')" style="padding:3px 8px;border:1px solid var(--brand);border-radius:5px;background:#fff;color:var(--brand);font-size:10px;font-weight:600;cursor:pointer">Connect</button>`
|
||||
}
|
||||
<button onclick="editMCPServer('${s.id}')" style="padding:3px 8px;border:1px solid var(--line);border-radius:5px;background:#fff;font-size:10px;cursor:pointer">Edit</button>
|
||||
<button onclick="deleteMCPServer('${s.id}')" style="padding:3px 8px;border:1px solid #fecaca;border-radius:5px;background:#fff;color:#ef4444;font-size:10px;cursor:pointer">?</button>
|
||||
</div>
|
||||
</div>`;
|
||||
}).join('');
|
||||
} catch(e) {
|
||||
el.innerHTML = `<div style="color:#ef4444">Failed to load: ${escHtml(e.message)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
function showMCPAddForm(editData) {
|
||||
_mcpEditingId = editData?.id || null;
|
||||
document.getElementById('mcp-add-form').style.display = 'block';
|
||||
document.getElementById('mcp-form-title').textContent = _mcpEditingId ? 'MCP 서버 편집' : 'MCP 서버 추가';
|
||||
document.getElementById('mcp-form-msg').textContent = '';
|
||||
|
||||
if (editData) {
|
||||
const v = (id, val) => { const el = document.getElementById(id); if (el && val !== undefined) el.value = val; };
|
||||
v('mcp-f-id', editData.id); v('mcp-f-name', editData.name);
|
||||
document.getElementById('mcp-f-transport').value = editData.transport || 'stdio';
|
||||
onMCPTransportChange();
|
||||
v('mcp-f-command', editData.command || '');
|
||||
v('mcp-f-args', (editData.args || []).join('\n'));
|
||||
v('mcp-f-env', Object.entries(editData.env || {}).map(([k,v]) => `${k}=${v}`).join('\n'));
|
||||
v('mcp-f-url', editData.url || '');
|
||||
v('mcp-f-headers', Object.entries(editData.headers || {}).map(([k,v]) => `${k}: ${v}`).join('\n'));
|
||||
const cb = document.getElementById('mcp-f-enabled');
|
||||
if (cb) cb.checked = editData.enabled !== false;
|
||||
} else {
|
||||
['mcp-f-id','mcp-f-name','mcp-f-command','mcp-f-args','mcp-f-env','mcp-f-url','mcp-f-headers'].forEach(id => {
|
||||
const el = document.getElementById(id); if (el) el.value = '';
|
||||
});
|
||||
document.getElementById('mcp-f-transport').value = 'stdio';
|
||||
onMCPTransportChange();
|
||||
const cb = document.getElementById('mcp-f-enabled'); if (cb) cb.checked = true;
|
||||
}
|
||||
document.getElementById('mcp-f-id').scrollIntoView({ behavior: 'smooth', block: 'nearest' });
|
||||
}
|
||||
|
||||
function hideMCPAddForm() {
|
||||
document.getElementById('mcp-add-form').style.display = 'none';
|
||||
_mcpEditingId = null;
|
||||
}
|
||||
|
||||
function onMCPTransportChange() {
|
||||
const t = document.getElementById('mcp-f-transport')?.value;
|
||||
document.getElementById('mcp-stdio-fields').style.display = t === 'stdio' ? 'block' : 'none';
|
||||
document.getElementById('mcp-sse-fields').style.display = t === 'sse' ? 'block' : 'none';
|
||||
}
|
||||
|
||||
function prefillMCPServer(presetKey) {
|
||||
const p = MCP_PRESETS[presetKey];
|
||||
if (!p) return;
|
||||
showMCPAddForm();
|
||||
const v = (id, val) => { const el = document.getElementById(id); if (el) el.value = val; };
|
||||
v('mcp-f-id', presetKey);
|
||||
v('mcp-f-name', p.name);
|
||||
document.getElementById('mcp-f-transport').value = p.transport;
|
||||
onMCPTransportChange();
|
||||
v('mcp-f-command', p.command || '');
|
||||
v('mcp-f-args', p.args || '');
|
||||
v('mcp-f-env', p.env || '');
|
||||
v('mcp-f-url', p.url || '');
|
||||
setIntegTab('mcp');
|
||||
}
|
||||
|
||||
async function saveMCPServer() {
|
||||
const id = document.getElementById('mcp-f-id')?.value?.trim();
|
||||
const name = document.getElementById('mcp-f-name')?.value?.trim();
|
||||
const transport = document.getElementById('mcp-f-transport')?.value || 'stdio';
|
||||
const enabled = document.getElementById('mcp-f-enabled')?.checked ?? true;
|
||||
const msgEl = document.getElementById('mcp-form-msg');
|
||||
|
||||
if (!id || !name) { if (msgEl) msgEl.textContent = 'ID와 이름은 필수입니다.'; return; }
|
||||
|
||||
const cfg = { id, name, transport, enabled };
|
||||
|
||||
if (transport === 'stdio') {
|
||||
cfg.command = document.getElementById('mcp-f-command')?.value?.trim() || '';
|
||||
const argsRaw = document.getElementById('mcp-f-args')?.value || '';
|
||||
cfg.args = argsRaw.split('\n').map(s => s.trim()).filter(Boolean);
|
||||
const envRaw = document.getElementById('mcp-f-env')?.value || '';
|
||||
cfg.env = {};
|
||||
envRaw.split('\n').map(l => l.trim()).filter(Boolean).forEach(line => {
|
||||
const eq = line.indexOf('='); if (eq > 0) cfg.env[line.slice(0,eq).trim()] = line.slice(eq+1);
|
||||
});
|
||||
} else {
|
||||
cfg.url = document.getElementById('mcp-f-url')?.value?.trim() || '';
|
||||
const headersRaw = document.getElementById('mcp-f-headers')?.value || '';
|
||||
cfg.headers = {};
|
||||
headersRaw.split('\n').map(l => l.trim()).filter(Boolean).forEach(line => {
|
||||
const colon = line.indexOf(':'); if (colon > 0) cfg.headers[line.slice(0,colon).trim()] = line.slice(colon+1).trim();
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const r = await api('/api/mcp/servers', { method: 'POST', body: JSON.stringify(cfg) });
|
||||
if (r.success) {
|
||||
if (msgEl) msgEl.textContent = '? Saved';
|
||||
setTimeout(() => hideMCPAddForm(), 600);
|
||||
await loadMCPServers();
|
||||
// Auto-connect if enabled
|
||||
if (enabled) connectMCPServer(id);
|
||||
} else {
|
||||
if (msgEl) msgEl.textContent = '오류: ' + (r.error || '알 수 없음');
|
||||
}
|
||||
} catch(e) {
|
||||
if (msgEl) msgEl.textContent = '저장 실패: ' + e.message;
|
||||
}
|
||||
}
|
||||
|
||||
async function editMCPServer(id) {
|
||||
try {
|
||||
const data = await api('/api/mcp/servers');
|
||||
const server = (data.servers || []).find(s => s.id === id);
|
||||
if (server) showMCPAddForm(server);
|
||||
} catch(e) { console.warn('editMCPServer:', e); }
|
||||
}
|
||||
|
||||
async function deleteMCPServer(id) {
|
||||
if (!confirm(`Delete MCP server "${id}"?`)) return;
|
||||
try {
|
||||
await api(`/api/mcp/servers/${id}`, { method: 'DELETE' });
|
||||
await loadMCPServers();
|
||||
} catch(e) { showIntegMsg('Delete failed: ' + e.message, '#991b1b', '#fef2f2'); }
|
||||
}
|
||||
|
||||
async function connectMCPServer(id) {
|
||||
showIntegMsg('Connecting to ' + id + '…', '#1e40af', '#eff6ff');
|
||||
try {
|
||||
const r = await api(`/api/mcp/servers/${id}/connect`, { method: 'POST' });
|
||||
if (r.success) {
|
||||
showIntegMsg(`? Connected — ${(r.tools||[]).length} tool(s) available`, '#166534', '#f0fdf4');
|
||||
} else {
|
||||
showIntegMsg('? Connection failed: ' + (r.error || 'Unknown'), '#991b1b', '#fef2f2');
|
||||
}
|
||||
await loadMCPServers();
|
||||
} catch(e) {
|
||||
showIntegMsg('Connect error: ' + e.message, '#991b1b', '#fef2f2');
|
||||
await loadMCPServers();
|
||||
}
|
||||
}
|
||||
|
||||
async function disconnectMCPServer(id) {
|
||||
try {
|
||||
await api(`/api/mcp/servers/${id}/disconnect`, { method: 'POST' });
|
||||
await loadMCPServers();
|
||||
showIntegMsg('Disconnected from ' + id, '#475569', '#f8fafc');
|
||||
} catch(e) { showIntegMsg('Disconnect error: ' + e.message, '#991b1b', '#fef2f2'); }
|
||||
}
|
||||
|
||||
// --- Shared helper ------------------------------------------------------------
|
||||
|
||||
function showIntegMsg(msg, color, bg) {
|
||||
let el = document.getElementById('integ-toast');
|
||||
if (!el) {
|
||||
el = document.createElement('div');
|
||||
el.id = 'integ-toast';
|
||||
el.style.cssText = 'position:fixed;bottom:80px;right:24px;z-index:9999;padding:10px 16px;border-radius:10px;font-size:12px;font-weight:600;max-width:320px;box-shadow:0 4px 16px rgba(0,0,0,0.12);transition:opacity .3s';
|
||||
document.body.appendChild(el);
|
||||
}
|
||||
el.style.background = bg || '#f0fdf4';
|
||||
el.style.color = color || '#166534';
|
||||
el.style.border = `1px solid ${color || '#166534'}33`;
|
||||
el.style.opacity = '1';
|
||||
el.textContent = msg;
|
||||
clearTimeout(el._timeout);
|
||||
el._timeout = setTimeout(() => { el.style.opacity = '0'; }, 3500);
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,203 @@
|
||||
// pptx-workflow.js — PPTX 마법사 사이드바 워크플로(이미지 캡처→아웃라인→생성).
|
||||
// extracted from app.js (v4.3.19-3 split).
|
||||
|
||||
let _pptxImages = []; // {url, thumb, label}
|
||||
let _pptxOutline = null; // parsed pptx-outline JSON
|
||||
let _pptxOutlineEdits = {}; // {index: {title, bullets}}
|
||||
|
||||
function setPptxSbTab(tab) {
|
||||
['setup','images','outline'].forEach(t => {
|
||||
document.getElementById('psb-tab-' + t).classList.toggle('active', t === tab);
|
||||
const el = document.getElementById('psb-' + t);
|
||||
if (el) el.style.display = t === tab ? (t === 'outline' ? 'flex' : (t === 'images' ? 'block' : 'flex')) : 'none';
|
||||
});
|
||||
}
|
||||
|
||||
function pptxSetStatus(msg) {
|
||||
const el = document.getElementById('psb-status');
|
||||
if (el) el.textContent = msg;
|
||||
}
|
||||
|
||||
function pptxStartWorkflow() {
|
||||
const topic = (document.getElementById('psb-topic').value || '').trim();
|
||||
const pmcidsRaw = (document.getElementById('psb-pmcids').value || '').trim();
|
||||
const template = document.getElementById('psb-template').value || 'dark';
|
||||
const slideCount = parseInt(document.getElementById('psb-slide-count').value) || 0;
|
||||
|
||||
if (!topic) { pptxSetStatus('주제를 입력하세요.'); return; }
|
||||
|
||||
const pmcids = pmcidsRaw
|
||||
.split(/[\n,]+/)
|
||||
.map(s => s.trim().replace(/^PMC/i, 'PMC'))
|
||||
.filter(Boolean);
|
||||
|
||||
_pptxImages = [];
|
||||
_pptxOutline = null;
|
||||
_pptxOutlineEdits = {};
|
||||
pptxRenderImageGrid();
|
||||
const cardsEl = document.getElementById('psb-outline-cards');
|
||||
if (cardsEl) cardsEl.innerHTML = '<div style="color:var(--muted);font-size:11px;padding:8px;text-align:center">아웃라인 생성 중...</div>';
|
||||
const genBtn = document.getElementById('psb-gen-btn');
|
||||
if (genBtn) { genBtn.disabled = true; genBtn.style.opacity = '.5'; }
|
||||
|
||||
// Build workflow message
|
||||
const pmcLine = pmcids.length
|
||||
? `\nPMCIDs: ${pmcids.join(', ')}`
|
||||
: '';
|
||||
const slideLine = slideCount ? `\n슬라이드 수: ${slideCount}장` : '';
|
||||
const msg = `[PPTX 워크플로 시작]\n주제: ${topic}${pmcLine}\n템플릿: ${template}${slideLine}\n\n아래 순서로 진행해주세요:\n1. 작업 폴더 생성 (주제 기반)\n2. PDF 다운로드 (pubmed_fulltext, 위 PMCIDs)\n3. 이미지 추출 (pdf_extract_images, 각 PDF)\n4. 소형 이미지 필터링 (python_eval)\n5. 슬라이드 구성을 \`\`\`pptx-outline 블록으로 출력 (JSON 형식)\n6. 확인 대기 (create_presentation은 아직 호출하지 마세요)`;
|
||||
|
||||
pptxSetStatus('워크플로 시작...');
|
||||
setSidebarTab('pptx');
|
||||
setPptxSbTab('setup');
|
||||
|
||||
// Send via main chat
|
||||
const input = document.getElementById('chat-input');
|
||||
if (input) {
|
||||
input.value = msg;
|
||||
sendChat();
|
||||
}
|
||||
}
|
||||
|
||||
function pptxCaptureImages(toolResultText) {
|
||||
// Parse image links from pdf_extract_images output: [label](/api/files/...)
|
||||
const re = /\[([^\]]*)\]\((\/api\/files\/[^)]+\.(?:png|jpg|jpeg|gif|webp))\)/gi;
|
||||
let m;
|
||||
while ((m = re.exec(toolResultText)) !== null) {
|
||||
const label = m[1];
|
||||
const url = m[2];
|
||||
if (!_pptxImages.some(i => i.url === url)) {
|
||||
_pptxImages.push({ url, label });
|
||||
}
|
||||
}
|
||||
if (_pptxImages.length) {
|
||||
pptxRenderImageGrid();
|
||||
const countEl = document.getElementById('psb-img-count');
|
||||
if (countEl) countEl.textContent = `(${_pptxImages.length})`;
|
||||
// Auto-switch to images tab if PPTX tab is active
|
||||
if (sidebarTab === 'pptx') setPptxSbTab('images');
|
||||
pptxSetStatus(`이미지 ${_pptxImages.length}개 추출됨`);
|
||||
}
|
||||
}
|
||||
|
||||
function pptxRenderImageGrid() {
|
||||
const grid = document.getElementById('psb-image-grid');
|
||||
if (!grid) return;
|
||||
if (!_pptxImages.length) {
|
||||
grid.innerHTML = '<div style="grid-column:1/-1;color:var(--muted);font-size:11px;padding:8px;text-align:center">이미지 추출 후 표시됩니다</div>';
|
||||
return;
|
||||
}
|
||||
grid.innerHTML = _pptxImages.map((img, idx) => `
|
||||
<div style="position:relative;border:1px solid var(--line);border-radius:6px;overflow:hidden;cursor:pointer;aspect-ratio:4/3;background:var(--panel-2)"
|
||||
onclick="pptxImageClick(${idx})" title="${escHtml(img.label)}">
|
||||
<img src="${escHtml(img.url)}" style="width:100%;height:100%;object-fit:cover" loading="lazy"
|
||||
onerror="this.parentNode.style.background='var(--panel)';this.style.display='none'">
|
||||
<div style="position:absolute;bottom:0;left:0;right:0;background:rgba(0,0,0,.5);color:#fff;font-size:9px;padding:2px 4px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${escHtml(img.label)}</div>
|
||||
</div>`).join('');
|
||||
}
|
||||
|
||||
function pptxImageClick(idx) {
|
||||
const img = _pptxImages[idx];
|
||||
if (!img) return;
|
||||
window.open(img.url, '_blank', 'noopener');
|
||||
}
|
||||
|
||||
function pptxSetOutline(data) {
|
||||
_pptxOutline = data;
|
||||
_pptxOutlineEdits = {};
|
||||
pptxRenderOutlineCards();
|
||||
const genBtn = document.getElementById('psb-gen-btn');
|
||||
if (genBtn) { genBtn.disabled = false; genBtn.style.opacity = '1'; }
|
||||
if (sidebarTab === 'pptx') setPptxSbTab('outline');
|
||||
pptxSetStatus(`아웃라인 준비 (${(data.slides || []).length}장)`);
|
||||
}
|
||||
|
||||
const SLIDE_TYPE_ICON = { title:'🏷', section:'📂', content:'📝', image:'🖼', table:'📊', chart:'📈', timeline:'⏳', compare:'⚖' };
|
||||
|
||||
function pptxRenderOutlineCards() {
|
||||
const container = document.getElementById('psb-outline-cards');
|
||||
if (!container || !_pptxOutline) return;
|
||||
const slides = _pptxOutline.slides || [];
|
||||
if (!slides.length) {
|
||||
container.innerHTML = '<div style="color:var(--muted);font-size:11px;padding:8px">슬라이드가 없습니다</div>';
|
||||
return;
|
||||
}
|
||||
container.innerHTML = slides.map((s, i) => {
|
||||
const icon = SLIDE_TYPE_ICON[s.type] || '📄';
|
||||
const imgThumb = s.image_url
|
||||
? `<img src="${escHtml(s.image_url)}" style="width:40px;height:30px;object-fit:cover;border-radius:4px;flex-shrink:0" loading="lazy">`
|
||||
: `<div style="width:40px;height:30px;border-radius:4px;background:var(--panel);flex-shrink:0;display:flex;align-items:center;justify-content:center;font-size:14px">🖼</div>`;
|
||||
const bulletsPreview = Array.isArray(s.bullets) && s.bullets.length
|
||||
? `<div style="font-size:10px;color:var(--muted);margin-top:3px;overflow:hidden;max-height:32px">${s.bullets.slice(0,2).map(b => `• ${b}`).join('<br>')}</div>`
|
||||
: '';
|
||||
return `<div class="psb-slide-card" style="border:1px solid var(--line);border-radius:8px;padding:7px 8px;background:var(--panel-2);cursor:pointer" onclick="pptxToggleEdit(${i})">
|
||||
<div style="display:flex;align-items:center;gap:7px">
|
||||
<span style="font-size:10px;color:var(--muted);flex-shrink:0;width:18px;text-align:right">${i+1}</span>
|
||||
${imgThumb}
|
||||
<div style="flex:1;min-width:0">
|
||||
<div style="font-size:12px;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${icon} ${escHtml(s.title || '(제목 없음)')}</div>
|
||||
<div style="font-size:10px;color:var(--muted)">${s.type}</div>
|
||||
${bulletsPreview}
|
||||
</div>
|
||||
</div>
|
||||
<div id="psb-edit-${i}" style="display:none;margin-top:7px;border-top:1px solid var(--line);padding-top:7px">
|
||||
<input type="text" value="${escHtml(s.title || '')}" oninput="pptxEditTitle(${i}, this.value)"
|
||||
style="width:100%;box-sizing:border-box;font-size:12px;padding:4px 6px;background:var(--panel);color:var(--text);border:1px solid var(--line);border-radius:6px;margin-bottom:4px">
|
||||
${Array.isArray(s.bullets) ? `<textarea rows="3" oninput="pptxEditBullets(${i}, this.value)"
|
||||
style="width:100%;box-sizing:border-box;font-size:11px;padding:4px 6px;background:var(--panel);color:var(--text);border:1px solid var(--line);border-radius:6px;resize:vertical;font-family:'IBM Plex Mono',monospace">${escHtml((s.bullets||[]).join('\n\n'))}</textarea>` : ''}
|
||||
</div>
|
||||
</div>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function pptxToggleEdit(idx) {
|
||||
const el = document.getElementById('psb-edit-' + idx);
|
||||
if (el) el.style.display = el.style.display === 'none' ? 'block' : 'none';
|
||||
}
|
||||
|
||||
function pptxEditTitle(idx, val) {
|
||||
if (!_pptxOutlineEdits[idx]) _pptxOutlineEdits[idx] = {};
|
||||
_pptxOutlineEdits[idx].title = val;
|
||||
}
|
||||
|
||||
function pptxEditBullets(idx, val) {
|
||||
if (!_pptxOutlineEdits[idx]) _pptxOutlineEdits[idx] = {};
|
||||
_pptxOutlineEdits[idx].bullets = val.split(/\n\n+/).map(g => g.replace(/^\n+|\n+$/g, '')).filter(g => g.trim() !== '');
|
||||
}
|
||||
|
||||
function pptxGenerate() {
|
||||
if (!_pptxOutline) return;
|
||||
// Apply edits to outline
|
||||
const slides = (_pptxOutline.slides || []).map((s, i) => {
|
||||
const ed = _pptxOutlineEdits[i];
|
||||
if (!ed) return s;
|
||||
return Object.assign({}, s, ed.title !== undefined ? { title: ed.title } : {}, ed.bullets !== undefined ? { bullets: ed.bullets } : {});
|
||||
});
|
||||
const edited = Object.assign({}, _pptxOutline, { slides });
|
||||
const hasEdits = Object.keys(_pptxOutlineEdits).length > 0;
|
||||
const msg = hasEdits
|
||||
? `아웃라인을 수정했습니다. 수정된 아웃라인으로 create_presentation을 호출해주세요:\n\`\`\`json\n${JSON.stringify(edited, null, 2)}\n\`\`\``
|
||||
: `아웃라인 확인했습니다. create_presentation으로 슬라이드를 생성해주세요.`;
|
||||
|
||||
const genBtn = document.getElementById('psb-gen-btn');
|
||||
if (genBtn) { genBtn.disabled = true; genBtn.style.opacity = '.5'; }
|
||||
pptxSetStatus('생성 중...');
|
||||
|
||||
const input = document.getElementById('chat-input');
|
||||
if (input) { input.value = msg; sendChat(); }
|
||||
}
|
||||
|
||||
function pptxResetWorkflow() {
|
||||
_pptxImages = [];
|
||||
_pptxOutline = null;
|
||||
_pptxOutlineEdits = {};
|
||||
pptxRenderImageGrid();
|
||||
const cardsEl = document.getElementById('psb-outline-cards');
|
||||
if (cardsEl) cardsEl.innerHTML = '<div style="color:var(--muted);font-size:11px;padding:8px;text-align:center">아웃라인 생성 후 표시됩니다</div>';
|
||||
const genBtn = document.getElementById('psb-gen-btn');
|
||||
if (genBtn) { genBtn.disabled = true; genBtn.style.opacity = '.5'; }
|
||||
const countEl = document.getElementById('psb-img-count');
|
||||
if (countEl) countEl.textContent = '';
|
||||
pptxSetStatus('');
|
||||
setPptxSbTab('setup');
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
// schedules.js — 예약 작업(cron) 목록/생성/수정/삭제.
|
||||
// extracted from app.js (v4.3.19-3 split).
|
||||
|
||||
let schedules = [];
|
||||
let editingScheduleId = null;
|
||||
|
||||
async function refreshSchedules() {
|
||||
try {
|
||||
const result = await api('/api/schedules');
|
||||
if (result.success && Array.isArray(result.schedules)) {
|
||||
schedules = result.schedules;
|
||||
renderScheduleList();
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to load schedules:', err);
|
||||
}
|
||||
}
|
||||
|
||||
function renderScheduleList() {
|
||||
const list = document.getElementById('schedule-list');
|
||||
const count = document.getElementById('schedule-count');
|
||||
if (!list) return;
|
||||
|
||||
if (schedules.length === 0) {
|
||||
list.innerHTML = '<div class="empty-state" style="text-align:center;color:var(--muted);padding:40px 20px">No schedules yet. <strong>+ 새 일정</strong> to get started.</div>';
|
||||
if (count) count.textContent = '0 schedules';
|
||||
return;
|
||||
}
|
||||
|
||||
if (count) count.textContent = `${schedules.length} schedule${schedules.length !== 1 ? 's' : ''}`;
|
||||
|
||||
list.innerHTML = schedules.map(job => {
|
||||
const nextRun = job.next_run ? new Date(job.next_run).toLocaleString() : 'Never';
|
||||
const lastRun = job.last_run ? new Date(job.last_run).toLocaleString() : 'Never';
|
||||
const statusClass = job.status === 'active' ? 'status-active' : job.status === 'paused' ? 'status-paused' : 'status-failed';
|
||||
|
||||
return `
|
||||
<div style="display:flex;align-items:start;justify-content:space-between;gap:12px;padding:12px;background:var(--panel);border:1px solid var(--line);border-radius:10px;cursor:pointer" onclick="editSchedule('${job.id}')">
|
||||
<div style="flex:1;min-width:0">
|
||||
<div style="display:flex;align-items:center;gap:8px;margin-bottom:6px">
|
||||
<div style="font-weight:700;font-size:13px">${job.name || 'Untitled'}</div>
|
||||
<span class="${statusClass}" style="font-size:10px;font-weight:700;padding:2px 8px;border-radius:6px;${job.status === 'active' ? 'background:#c8f0c4;color:#0d5c2f' : job.status === 'paused' ? 'background:#fff4d6;color:#7d5700' : 'background:#ffd6d6;color:#8b0000'}">${job.status || 'unknown'}</span>
|
||||
</div>
|
||||
<div style="font-size:12px;color:var(--muted);line-height:1.4;margin-bottom:6px">${job.prompt ? job.prompt.slice(0, 60) + (job.prompt.length > 60 ? '...' : '') : 'No prompt'}</div>
|
||||
<div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;font-size:11px;color:var(--muted)">
|
||||
<div><strong>Next:</strong> ${nextRun}</div>
|
||||
<div><strong>Last:</strong> ${lastRun}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div style="display:flex;flex-direction:column;gap:6px;flex-shrink:0">
|
||||
<button onclick="event.stopPropagation(); runScheduleNow('${job.id}')" style="border:1px solid var(--line);background:var(--panel-2);color:var(--muted);border-radius:6px;padding:4px 10px;font-size:11px;font-weight:600;cursor:pointer;white-space:nowrap" title="Run now">Run Now</button>
|
||||
<button onclick="event.stopPropagation(); toggleSchedulePause('${job.id}')" style="border:1px solid var(--line);background:var(--panel-2);color:var(--muted);border-radius:6px;padding:4px 10px;font-size:11px;font-weight:600;cursor:pointer;white-space:nowrap" title="Toggle pause">${job.status === 'active' ? 'Pause' : 'Resume'}</button>
|
||||
<button onclick="event.stopPropagation(); deleteSchedule('${job.id}')" style="border:1px solid #ff6b6b;background:#ffe0e0;color:#8b0000;border-radius:6px;padding:4px 10px;font-size:11px;font-weight:600;cursor:pointer;white-space:nowrap" title="Delete">삭제</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function openScheduleCreateModal() {
|
||||
editingScheduleId = null;
|
||||
document.getElementById('schedule-modal-title').textContent = '일정 생성';
|
||||
document.getElementById('schedule-save-btn').textContent = '일정 생성';
|
||||
document.getElementById('schedule-name').value = '';
|
||||
document.getElementById('schedule-pattern').value = '';
|
||||
document.getElementById('schedule-prompt').value = '';
|
||||
document.getElementById('schedule-timezone').value = 'UTC';
|
||||
document.getElementById('schedule-channel').value = 'web';
|
||||
document.getElementById('schedule-pattern-preview').style.display = 'none';
|
||||
document.getElementById('schedule-modal').style.display = 'flex';
|
||||
}
|
||||
|
||||
function editSchedule(jobId) {
|
||||
const job = schedules.find(j => j.id === jobId);
|
||||
if (!job) return;
|
||||
|
||||
editingScheduleId = jobId;
|
||||
document.getElementById('schedule-modal-title').textContent = '일정 편집';
|
||||
document.getElementById('schedule-save-btn').textContent = '변경 저장';
|
||||
document.getElementById('schedule-name').value = job.name || '';
|
||||
document.getElementById('schedule-pattern').value = job.cron || job.run_at || '';
|
||||
document.getElementById('schedule-prompt').value = job.prompt || '';
|
||||
document.getElementById('schedule-timezone').value = job.timezone || 'UTC';
|
||||
document.getElementById('schedule-channel').value = job.delivery_channel || 'web';
|
||||
document.getElementById('schedule-pattern-preview').style.display = 'none';
|
||||
document.getElementById('schedule-modal').style.display = 'flex';
|
||||
}
|
||||
|
||||
function closeScheduleModal() {
|
||||
document.getElementById('schedule-modal').style.display = 'none';
|
||||
editingScheduleId = null;
|
||||
}
|
||||
|
||||
async function parseSchedulePattern() {
|
||||
const pattern = document.getElementById('schedule-pattern').value.trim();
|
||||
const timezone = document.getElementById('schedule-timezone').value;
|
||||
if (!pattern) {
|
||||
alert('Enter a schedule pattern (e.g., "daily at 09:00" or "0 9 * * *")');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await api('/api/schedules/parse', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ text: pattern, timezone })
|
||||
});
|
||||
|
||||
const preview = document.getElementById('schedule-pattern-preview');
|
||||
if (result.success) {
|
||||
preview.textContent = `✓ ${result.preview || result.human_text || 'Valid pattern'}`;
|
||||
preview.style.display = 'block';
|
||||
preview.style.color = 'var(--muted)';
|
||||
} else {
|
||||
preview.textContent = `⚠ ${result.error || 'Invalid pattern'}`;
|
||||
preview.style.display = 'block';
|
||||
preview.style.color = '#ff6b6b';
|
||||
}
|
||||
} catch (err) {
|
||||
document.getElementById('schedule-pattern-preview').textContent = '⚠ Parse failed';
|
||||
document.getElementById('schedule-pattern-preview').style.display = 'block';
|
||||
document.getElementById('schedule-pattern-preview').style.color = '#ff6b6b';
|
||||
}
|
||||
}
|
||||
|
||||
async function saveSchedule() {
|
||||
const name = document.getElementById('schedule-name').value.trim();
|
||||
const pattern = document.getElementById('schedule-pattern').value.trim();
|
||||
const prompt = document.getElementById('schedule-prompt').value.trim();
|
||||
const timezone = document.getElementById('schedule-timezone').value;
|
||||
const channel = document.getElementById('schedule-channel').value;
|
||||
|
||||
if (!name) return alert('Schedule name is required');
|
||||
if (!pattern) return alert('Schedule pattern is required');
|
||||
if (!prompt) return alert('Prompt/action is required');
|
||||
|
||||
const method = editingScheduleId ? 'PUT' : 'POST';
|
||||
const path = editingScheduleId ? `/api/schedules/${editingScheduleId}` : '/api/schedules';
|
||||
|
||||
try {
|
||||
const result = await api(path, {
|
||||
method,
|
||||
body: JSON.stringify({
|
||||
name,
|
||||
pattern,
|
||||
prompt,
|
||||
timezone,
|
||||
delivery_channel: channel,
|
||||
confirm: true // Confirmation (as per scheduler rules)
|
||||
})
|
||||
});
|
||||
|
||||
if (result.success) {
|
||||
closeScheduleModal();
|
||||
await refreshSchedules();
|
||||
} else {
|
||||
alert('Error: ' + (result.error || 'Unknown error'));
|
||||
}
|
||||
} catch (err) {
|
||||
alert('Failed to save schedule: ' + err.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteSchedule(jobId) {
|
||||
if (!confirm('Delete this schedule? This action cannot be undone.')) return;
|
||||
|
||||
try {
|
||||
const result = await api(`/api/schedules/${jobId}`, {
|
||||
method: 'DELETE',
|
||||
body: JSON.stringify({ confirm: true })
|
||||
});
|
||||
|
||||
if (result.success) {
|
||||
await refreshSchedules();
|
||||
} else {
|
||||
alert('Error: ' + (result.error || 'Failed to delete'));
|
||||
}
|
||||
} catch (err) {
|
||||
alert('Failed to delete schedule: ' + err.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleSchedulePause(jobId) {
|
||||
const job = schedules.find(j => j.id === jobId);
|
||||
if (!job) return;
|
||||
|
||||
const newStatus = job.status === 'active' ? 'paused' : 'active';
|
||||
|
||||
try {
|
||||
const result = await api(`/api/schedules/${jobId}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ status: newStatus })
|
||||
});
|
||||
|
||||
if (result.success) {
|
||||
await refreshSchedules();
|
||||
} else {
|
||||
alert('Error: ' + (result.error || 'Failed to update'));
|
||||
}
|
||||
} catch (err) {
|
||||
alert('Failed to toggle pause: ' + err.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function runScheduleNow(jobId) {
|
||||
try {
|
||||
const result = await api(`/api/schedules/${jobId}/run`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({})
|
||||
});
|
||||
|
||||
if (result.success) {
|
||||
await refreshSchedules();
|
||||
alert('Schedule running now...');
|
||||
} else {
|
||||
alert('Error: ' + (result.error || 'Failed to run'));
|
||||
}
|
||||
} catch (err) {
|
||||
alert('Failed to run schedule: ' + err.message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,490 @@
|
||||
// settings-agents.js — 설정: AI 에이전트 관리(AGENTS.md 에디터), 스킬 설치/토글/편집.
|
||||
// extracted from app.js (v4.3.19-3 split).
|
||||
|
||||
function closeSettings() {
|
||||
document.getElementById('settings-modal').style.display = 'none';
|
||||
_searchSettingsLoaded = false;
|
||||
_modelSettingsLoaded = false;
|
||||
}
|
||||
|
||||
function ensureAgentMdEditor() {
|
||||
if (agentMdEditor || typeof CodeMirror === 'undefined') return;
|
||||
const wrap = document.getElementById('agent-md-editor-wrap');
|
||||
if (!wrap) return;
|
||||
agentMdEditor = CodeMirror(wrap, {
|
||||
value: '',
|
||||
mode: 'markdown',
|
||||
lineNumbers: true,
|
||||
lineWrapping: true,
|
||||
tabSize: 2,
|
||||
indentWithTabs: false,
|
||||
theme: 'default',
|
||||
});
|
||||
agentMdEditor.setSize('100%', 240);
|
||||
}
|
||||
|
||||
function getAgentFromForm() {
|
||||
const profile = document.getElementById('agent-edit-profile').value.trim();
|
||||
const maxStepsRaw = document.getElementById('agent-edit-max-steps').value;
|
||||
const maxSteps = Number(maxStepsRaw);
|
||||
const spawnAllowlist = (document.getElementById('agent-edit-spawn-allowlist').value || '')
|
||||
.split(',')
|
||||
.map(s => s.trim())
|
||||
.filter(Boolean);
|
||||
const agent = {
|
||||
id: document.getElementById('agent-edit-id').value.trim(),
|
||||
name: document.getElementById('agent-edit-name').value.trim(),
|
||||
emoji: document.getElementById('agent-edit-emoji').value.trim(),
|
||||
description: document.getElementById('agent-edit-description').value.trim(),
|
||||
workspace: document.getElementById('agent-edit-workspace').value.trim(),
|
||||
model: document.getElementById('agent-edit-model').value.trim(),
|
||||
cronSchedule: document.getElementById('agent-edit-cron').value.trim(),
|
||||
minimalPrompt: document.getElementById('agent-edit-minimal').checked,
|
||||
default: document.getElementById('agent-edit-default').checked,
|
||||
canSpawn: document.getElementById('agent-edit-can-spawn').checked,
|
||||
spawnAllowlist,
|
||||
tools: {},
|
||||
};
|
||||
if (profile) agent.tools.profile = profile;
|
||||
if (Number.isFinite(maxSteps) && maxSteps > 0) agent.maxSteps = Math.floor(maxSteps);
|
||||
if (!agent.tools.profile) delete agent.tools;
|
||||
if (!agent.spawnAllowlist.length) delete agent.spawnAllowlist;
|
||||
return agent;
|
||||
}
|
||||
|
||||
function setAgentForm(agent) {
|
||||
const a = agent || {};
|
||||
document.getElementById('agent-edit-id').value = a.id || '';
|
||||
document.getElementById('agent-edit-name').value = a.name || '';
|
||||
document.getElementById('agent-edit-emoji').value = a.emoji || '';
|
||||
document.getElementById('agent-edit-description').value = a.description || '';
|
||||
document.getElementById('agent-edit-workspace').value = a.workspace || '';
|
||||
document.getElementById('agent-edit-model').value = a.model || '';
|
||||
document.getElementById('agent-edit-cron').value = a.cronSchedule || '';
|
||||
document.getElementById('agent-edit-max-steps').value = (a.maxSteps || '') + '';
|
||||
document.getElementById('agent-edit-default').checked = a.default === true;
|
||||
document.getElementById('agent-edit-minimal').checked = a.minimalPrompt === true;
|
||||
document.getElementById('agent-edit-can-spawn').checked = a.canSpawn === true;
|
||||
document.getElementById('agent-edit-spawn-allowlist').value = Array.isArray(a.spawnAllowlist) ? a.spawnAllowlist.join(',') : '';
|
||||
document.getElementById('agent-edit-profile').value = a.tools?.profile || '';
|
||||
}
|
||||
|
||||
function renderAgentsList() {
|
||||
const el = document.getElementById('settings-agents-list');
|
||||
if (!el) return;
|
||||
if (!agentsConfigList.length) {
|
||||
el.innerHTML = '<div style="color:var(--muted)">No agents found.</div>';
|
||||
return;
|
||||
}
|
||||
el.innerHTML = agentsConfigList.map((a) => {
|
||||
const selected = a.id === selectedAgentId;
|
||||
const lastRun = a.lastRun?.finishedAt ? new Date(a.lastRun.finishedAt).toLocaleString() : 'never';
|
||||
const heartbeat = a.lastHeartbeatAt ? new Date(a.lastHeartbeatAt).toLocaleString() : 'never';
|
||||
const badge = a.default ? '<span style="font-size:10px;padding:2px 6px;border-radius:999px;background:#eaf2ff;color:#0d4faf;border:1px solid #bdd3f6">default</span>' : '';
|
||||
return `
|
||||
<button onclick="selectAgent('${escHtml(a.id)}')" style="text-align:left;border:1px solid ${selected ? '#bdd3f6' : 'var(--line)'};border-radius:10px;padding:8px;background:${selected ? '#f5f9ff' : '#fff'};cursor:pointer">
|
||||
<div style="display:flex;align-items:center;gap:6px">
|
||||
<div style="font-size:15px">${escHtml(a.emoji || '🤖')}</div>
|
||||
<div style="font-weight:700;color:var(--text)">${escHtml(a.name || a.id)}</div>
|
||||
${badge}
|
||||
</div>
|
||||
<div style="margin-top:4px;font-family:'IBM Plex Mono',monospace;color:var(--muted)">${escHtml(a.id)}</div>
|
||||
<div style="margin-top:4px;font-size:11px;color:var(--muted)">last run: ${escHtml(lastRun)}</div>
|
||||
<div style="font-size:11px;color:var(--muted)">last heartbeat: ${escHtml(heartbeat)}</div>
|
||||
</button>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function findSelectedAgent() {
|
||||
return agentsConfigList.find(a => a.id === selectedAgentId) || null;
|
||||
}
|
||||
|
||||
function agentFormNew() {
|
||||
selectedAgentId = '';
|
||||
setAgentForm({
|
||||
id: '',
|
||||
name: '',
|
||||
emoji: '',
|
||||
description: '',
|
||||
workspace: '',
|
||||
model: '',
|
||||
cronSchedule: '',
|
||||
maxSteps: '',
|
||||
default: false,
|
||||
minimalPrompt: true,
|
||||
canSpawn: false,
|
||||
spawnAllowlist: [],
|
||||
tools: {},
|
||||
});
|
||||
if (agentMdEditor) agentMdEditor.setValue('');
|
||||
const mdPath = document.getElementById('agent-md-path');
|
||||
if (mdPath) mdPath.textContent = '에이전트를 선택하거나 저장하면 AGENTS.md를 불러옵니다';
|
||||
const resultEl = document.getElementById('agent-spawn-result');
|
||||
if (resultEl) resultEl.textContent = '';
|
||||
renderAgentsList();
|
||||
}
|
||||
|
||||
async function selectAgent(id) {
|
||||
selectedAgentId = id;
|
||||
const selected = findSelectedAgent();
|
||||
setAgentForm(selected);
|
||||
renderAgentsList();
|
||||
await loadSelectedAgentMd();
|
||||
await loadAgentRunHistory();
|
||||
}
|
||||
|
||||
async function loadAgentsTab() {
|
||||
ensureAgentMdEditor();
|
||||
try {
|
||||
const data = await api('/api/agents');
|
||||
agentsConfigList = Array.isArray(data?.agents) ? data.agents : [];
|
||||
if (!selectedAgentId || !agentsConfigList.some(a => a.id === selectedAgentId)) {
|
||||
selectedAgentId = data?.defaultAgentId || agentsConfigList[0]?.id || '';
|
||||
}
|
||||
renderAgentsList();
|
||||
const selected = findSelectedAgent();
|
||||
setAgentForm(selected);
|
||||
if (selected) {
|
||||
await loadSelectedAgentMd();
|
||||
await loadAgentRunHistory();
|
||||
} else {
|
||||
agentFormNew();
|
||||
}
|
||||
} catch (err) {
|
||||
addProcessEntry('error', `Failed to load agents: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function saveAgentFromForm() {
|
||||
const agent = getAgentFromForm();
|
||||
if (!agent.id) {
|
||||
alert('Agent ID is required');
|
||||
return;
|
||||
}
|
||||
if (!agent.name) {
|
||||
alert('Agent name is required');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const exists = agentsConfigList.some(a => a.id === agent.id);
|
||||
const endpoint = exists ? `/api/agents/${encodeURIComponent(agent.id)}` : '/api/agents';
|
||||
const method = exists ? 'PUT' : 'POST';
|
||||
const data = await api(endpoint, {
|
||||
method,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ agent }),
|
||||
});
|
||||
if (!data?.success) throw new Error(data?.error || 'save failed');
|
||||
selectedAgentId = data?.agent?.id || agent.id;
|
||||
addProcessEntry('info', `Agent "${selectedAgentId}" saved.`);
|
||||
await loadAgentsTab();
|
||||
} catch (err) {
|
||||
alert(`Failed to save agent: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteSelectedAgent() {
|
||||
if (!selectedAgentId) return;
|
||||
if (!confirm(`Delete agent "${selectedAgentId}"?`)) return;
|
||||
try {
|
||||
await api(`/api/agents/${encodeURIComponent(selectedAgentId)}`, { method: 'DELETE' });
|
||||
addProcessEntry('info', `Agent "${selectedAgentId}" deleted.`);
|
||||
selectedAgentId = '';
|
||||
await loadAgentsTab();
|
||||
} catch (err) {
|
||||
alert(`Failed to delete agent: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadSelectedAgentMd() {
|
||||
ensureAgentMdEditor();
|
||||
if (!selectedAgentId || !agentMdEditor) return;
|
||||
try {
|
||||
const data = await api(`/api/agents/${encodeURIComponent(selectedAgentId)}/agents-md`);
|
||||
agentMdEditor.setValue(data?.content || '');
|
||||
const pathEl = document.getElementById('agent-md-path');
|
||||
if (pathEl) pathEl.textContent = data?.path || '';
|
||||
} catch (err) {
|
||||
addProcessEntry('error', `Failed to load AGENTS.md: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function saveSelectedAgentMd() {
|
||||
if (!selectedAgentId || !agentMdEditor) return;
|
||||
try {
|
||||
const content = agentMdEditor.getValue();
|
||||
await api(`/api/agents/${encodeURIComponent(selectedAgentId)}/agents-md`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ content }),
|
||||
});
|
||||
addProcessEntry('final', `Saved AGENTS.md for "${selectedAgentId}".`);
|
||||
} catch (err) {
|
||||
alert(`Failed to save AGENTS.md: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function runSelectedAgentOnce() {
|
||||
if (!selectedAgentId) return;
|
||||
const task = (document.getElementById('agent-spawn-task').value || '').trim();
|
||||
if (!task) {
|
||||
alert('Provide a task first.');
|
||||
return;
|
||||
}
|
||||
const out = document.getElementById('agent-spawn-result');
|
||||
if (out) out.textContent = '실행 중...';
|
||||
try {
|
||||
const data = await api(`/api/agents/${encodeURIComponent(selectedAgentId)}/spawn`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ task }),
|
||||
});
|
||||
const result = data?.result || {};
|
||||
if (out) {
|
||||
const head = result.success ? `Success (${result.durationMs || 0}ms)` : `Failed: ${result.error || 'unknown error'}`;
|
||||
out.textContent = `${head}\n\n${String(result.result || '').slice(0, 2500)}`;
|
||||
}
|
||||
await loadAgentsTab();
|
||||
} catch (err) {
|
||||
if (out) out.textContent = `Run failed: ${err.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadAgentRunHistory() {
|
||||
const el = document.getElementById('agent-run-history');
|
||||
if (!el) return;
|
||||
if (!selectedAgentId) { el.innerHTML = ''; return; }
|
||||
try {
|
||||
const data = await api(`/api/agents/history?agentId=${encodeURIComponent(selectedAgentId)}&limit=12`);
|
||||
const rows = Array.isArray(data?.history) ? data.history : [];
|
||||
if (!rows.length) {
|
||||
el.innerHTML = '<div style="color:var(--muted)">No runs yet.</div>';
|
||||
return;
|
||||
}
|
||||
el.innerHTML = rows.map((r) => {
|
||||
const color = r.success ? '#1a6e35' : '#9c1a1a';
|
||||
const when = new Date(r.finishedAt || r.startedAt || Date.now()).toLocaleString();
|
||||
const label = `${r.trigger || 'manual'} • ${r.durationMs || 0}ms`;
|
||||
const preview = String(r.resultPreview || r.error || '').slice(0, 140);
|
||||
return `<div style="border:1px solid var(--line);border-radius:8px;padding:6px 8px">
|
||||
<div style="display:flex;justify-content:space-between;gap:8px">
|
||||
<span style="font-weight:700;color:${color}">${r.success ? 'success' : 'failed'}</span>
|
||||
<span style="font-size:11px;color:var(--muted)">${escHtml(when)}</span>
|
||||
</div>
|
||||
<div style="font-size:11px;color:var(--muted)">${escHtml(label)}</div>
|
||||
<div style="font-size:11px;color:var(--text);margin-top:2px">${escHtml(preview)}</div>
|
||||
</div>`;
|
||||
}).join('');
|
||||
} catch (err) {
|
||||
el.innerHTML = `<div style="color:#9c1a1a">Failed to load history: ${escHtml(err.message)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
const logLines = [];
|
||||
function log(text, type = 'log') {
|
||||
const ts = new Date().toLocaleTimeString();
|
||||
logLines.push({ text: `[${ts}] ${text}`, type });
|
||||
if (logLines.length > 100) logLines.shift();
|
||||
const lp = document.getElementById('log-panel');
|
||||
if (lp) {
|
||||
lp.innerHTML = logLines.map(l => `<div class="log-line ${l.type}">${l.text}</div>`).join('');
|
||||
lp.scrollTop = lp.scrollHeight;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Skills management (v2 - local skills system) ----
|
||||
let skillsCache = [];
|
||||
let editingSkillId = null;
|
||||
|
||||
let skillsTargetUser = ''; // '' = global (admin) or own username (regular user)
|
||||
|
||||
async function initSkillsUserSelector() {
|
||||
const selector = document.getElementById('skills-user-selector');
|
||||
if (!selector) return;
|
||||
if (!currentUser) { selector.style.display = 'none'; return; }
|
||||
if (currentUser.role !== 'admin') {
|
||||
selector.style.display = 'none';
|
||||
skillsTargetUser = currentUser.username || '';
|
||||
return;
|
||||
}
|
||||
selector.style.display = 'block';
|
||||
try {
|
||||
const data = await api('/api/users');
|
||||
const sel = document.getElementById('skills-target-user');
|
||||
if (!sel || !data.users) return;
|
||||
const opts = ['<option value="">글로벌 기본값</option>'];
|
||||
for (const u of data.users) {
|
||||
const selected = u.username === skillsTargetUser ? ' selected' : '';
|
||||
opts.push(`<option value="${escHtml(u.username)}"${selected}>${escHtml(u.username)}</option>`);
|
||||
}
|
||||
sel.innerHTML = opts.join('');
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function onSkillsUserChange() {
|
||||
const sel = document.getElementById('skills-target-user');
|
||||
skillsTargetUser = sel ? sel.value : '';
|
||||
loadInstalledSkills();
|
||||
}
|
||||
|
||||
async function loadInstalledSkills() {
|
||||
const el = document.getElementById('skills-list');
|
||||
el.innerHTML = '<div style="padding:12px;color:var(--muted);font-size:11px"><span class="spinner"></span> Loading...</div>';
|
||||
try {
|
||||
const effectiveUser = skillsTargetUser || currentUser?.username || null;
|
||||
const url = effectiveUser ? `/api/skills?username=${encodeURIComponent(effectiveUser)}` : '/api/skills';
|
||||
const data = await api(url);
|
||||
const skills = data.skills || [];
|
||||
skillsCache = skills;
|
||||
if (skills.length === 0) {
|
||||
el.innerHTML = '<div class="empty-state" style="padding:16px">No skills yet.<br>Click "+ Create" to make one!</div>';
|
||||
} else {
|
||||
el.innerHTML = skills.map(s => {
|
||||
const skillEmoji = (s.emoji && s.emoji !== '🦞' && s.emoji !== '⚠️') ? s.emoji : '🧩';
|
||||
const globalBadge = s.globalOnly ? '<span style="font-size:9px;opacity:.6;margin-left:4px">[전체]</span>' : '';
|
||||
return `
|
||||
<div class="skill-card ${s.enabled ? 'enabled' : ''}" data-skill-id="${escHtml(s.id)}" onclick="toggleSkill('${escHtml(s.id)}')">
|
||||
<div class="skill-card-top">
|
||||
<div class="skill-card-emoji">${escHtml(skillEmoji)}</div>
|
||||
<div class="skill-card-info">
|
||||
<div class="skill-card-name">${escHtml(s.name)}${globalBadge}</div>
|
||||
<div class="skill-card-desc">${escHtml(s.description || 'No description')}</div>
|
||||
</div>
|
||||
<div class="skill-card-actions">
|
||||
<button class="skill-mini-btn" onclick="event.stopPropagation();editSkill('${escHtml(s.id)}')" title="Edit" aria-label="Edit skill">✎</button>
|
||||
<button class="skill-remove-btn" onclick="event.stopPropagation();deleteSkill('${escHtml(s.id)}')" title="Delete" aria-label="Delete skill">✕</button>
|
||||
<div class="skill-card-dot"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
renderSkillEligibility(skills);
|
||||
}
|
||||
} catch (err) {
|
||||
el.innerHTML = `<div style="padding:12px;color:var(--err);font-size:11px">Error: ${err.message}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleSkill(id) {
|
||||
const skillMeta = (skillsCache || []).find(s => s.id === id);
|
||||
if (skillMeta && skillMeta.eligible === false && !skillMeta.enabled) {
|
||||
addProcessEntry('error', skillMeta.eligibleReason || 'This skill is currently unavailable.');
|
||||
return;
|
||||
}
|
||||
// globalOnly 스킬은 per-user 모드에서 토글 불가 (서버가 전역으로 처리)
|
||||
if (skillMeta?.globalOnly && skillsTargetUser) {
|
||||
addProcessEntry('error', `"${skillMeta.name}" 스킬은 글로벌 전용입니다.`);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const effectiveUser = skillsTargetUser || currentUser?.username || null;
|
||||
const body = effectiveUser ? JSON.stringify({ username: effectiveUser }) : undefined;
|
||||
const res = await api(`/api/skills/${encodeURIComponent(id)}/toggle`, { method: 'POST', body });
|
||||
if (!res.success) {
|
||||
addProcessEntry('error', res.error || 'Failed to toggle skill.');
|
||||
return;
|
||||
}
|
||||
const label = res.targetUser ? ` (${res.targetUser})` : '';
|
||||
addProcessEntry('info', `Skill "${res.skill.name}"${label}: ${res.skill.enabled ? 'ENABLED' : 'DISABLED'}`);
|
||||
loadInstalledSkills();
|
||||
} catch (err) {
|
||||
addProcessEntry('error', `Failed to toggle skill: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteSkill(id) {
|
||||
if (!confirm(`Delete skill "${id}"?`)) return;
|
||||
try {
|
||||
const res = await api(`/api/skills/${encodeURIComponent(id)}`, { method: 'DELETE' });
|
||||
if (res.success) {
|
||||
addProcessEntry('info', `Skill "${id}" deleted.`);
|
||||
loadInstalledSkills();
|
||||
} else {
|
||||
alert(`Delete failed: ${res.error}`);
|
||||
}
|
||||
} catch (err) {
|
||||
alert(`Error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function openCreateSkillModal() {
|
||||
editingSkillId = null;
|
||||
document.getElementById('skill-modal-title').textContent = '스킬 생성';
|
||||
document.getElementById('skill-modal-save-btn').textContent = '스킬 생성';
|
||||
document.getElementById('skill-modal-name').value = '';
|
||||
document.getElementById('skill-modal-emoji').value = '';
|
||||
document.getElementById('skill-modal-desc').value = '';
|
||||
document.getElementById('skill-modal-instructions').value = '';
|
||||
document.getElementById('skill-modal').style.display = 'flex';
|
||||
document.getElementById('skill-modal-name').focus();
|
||||
}
|
||||
|
||||
async function editSkill(id) {
|
||||
try {
|
||||
const res = await api(`/api/skills/${encodeURIComponent(id)}`);
|
||||
if (!res.success) { alert('Skill not found'); return; }
|
||||
const s = res.skill;
|
||||
editingSkillId = id;
|
||||
document.getElementById('skill-modal-title').textContent = '스킬 편집';
|
||||
document.getElementById('skill-modal-save-btn').textContent = '변경 저장';
|
||||
document.getElementById('skill-modal-name').value = s.name || '';
|
||||
document.getElementById('skill-modal-emoji').value = s.emoji || '';
|
||||
document.getElementById('skill-modal-desc').value = s.description || '';
|
||||
document.getElementById('skill-modal-instructions').value = s.instructions || '';
|
||||
document.getElementById('skill-modal').style.display = 'flex';
|
||||
document.getElementById('skill-modal-name').focus();
|
||||
} catch (err) {
|
||||
alert(`Error loading skill: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function closeSkillModal() {
|
||||
document.getElementById('skill-modal').style.display = 'none';
|
||||
editingSkillId = null;
|
||||
}
|
||||
|
||||
async function saveSkillFromModal() {
|
||||
const name = document.getElementById('skill-modal-name').value.trim();
|
||||
const rawEmoji = document.getElementById('skill-modal-emoji').value.trim();
|
||||
const emoji = (rawEmoji === '🧩' || rawEmoji === '🦞' || rawEmoji === '⚠️') ? rawEmoji : '🧩';
|
||||
const description = document.getElementById('skill-modal-desc').value.trim();
|
||||
const instructions = document.getElementById('skill-modal-instructions').value.trim();
|
||||
|
||||
if (!name) { alert('Name is required'); return; }
|
||||
if (!instructions) { alert('Instructions are required'); return; }
|
||||
|
||||
const btn = document.getElementById('skill-modal-save-btn');
|
||||
btn.disabled = true;
|
||||
btn.textContent = '저장 중...';
|
||||
|
||||
try {
|
||||
let res;
|
||||
if (editingSkillId) {
|
||||
// Update existing
|
||||
res = await api(`/api/skills/${encodeURIComponent(editingSkillId)}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ name, emoji, description, instructions }),
|
||||
});
|
||||
} else {
|
||||
// Create new
|
||||
res = await api('/api/skills', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ name, emoji, description, instructions }),
|
||||
});
|
||||
}
|
||||
if (res.success) {
|
||||
addProcessEntry('info', `Skill "${name}" ${editingSkillId ? 'updated' : 'created'}!`);
|
||||
closeSkillModal();
|
||||
loadInstalledSkills();
|
||||
} else {
|
||||
alert(`Failed: ${res.error}`);
|
||||
}
|
||||
} catch (err) {
|
||||
alert(`Error: ${err.message}`);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.textContent = editingSkillId ? '변경 저장' : '스킬 생성';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,636 @@
|
||||
// settings-channels.js — 설정: 알림 채널(텔레그램/이메일/카카오) 연결 및 테스트.
|
||||
// extracted from app.js (v4.3.19-3 split).
|
||||
|
||||
function toggleUserTelegram(username) {
|
||||
const panel = document.getElementById(`user-telegram-panel-${username}`);
|
||||
if (!panel) return;
|
||||
if (panel.style.display === 'none') {
|
||||
panel.style.display = 'block';
|
||||
loadUserTelegramBot(username);
|
||||
} else {
|
||||
panel.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
async function loadUserTelegramBot(username) {
|
||||
const panel = document.getElementById(`user-telegram-panel-${username}`);
|
||||
if (!panel) return;
|
||||
panel.innerHTML = '<div style="font-size:12px;color:var(--muted)">불러오는 중...</div>';
|
||||
try {
|
||||
const data = await api(`/api/users/${encodeURIComponent(username)}/telegram-bot`);
|
||||
const statusColor = data.running ? 'var(--ok)' : 'var(--muted)';
|
||||
const statusText = data.running ? `연결됨 (@${data.botUsername || '?'})` : '중지됨';
|
||||
panel.innerHTML = `
|
||||
<div style="font-size:12px;font-weight:600;margin-bottom:8px">텔레그램 전용 봇 — ${username}</div>
|
||||
<div style="font-size:11px;color:${statusColor};margin-bottom:8px">● ${statusText}</div>
|
||||
<div style="display:flex;gap:6px;align-items:center">
|
||||
<input id="tg-token-${username}" type="password" placeholder="${data.hasToken ? '●●●●●●●● (저장됨 — 변경 시 입력)' : '봇 토큰 입력 (BotFather에서 발급)'}"
|
||||
style="flex:1;padding:5px 8px;border:1px solid var(--line);border-radius:6px;font-size:12px;background:var(--panel-1);color:var(--text)">
|
||||
<button onclick="saveUserTelegramBot('${username}')" style="padding:5px 12px;font-size:11px;background:var(--brand);color:#fff;border:none;border-radius:6px;cursor:pointer">저장</button>
|
||||
${data.hasToken ? `<button onclick="deleteUserTelegramBot('${username}')" style="padding:5px 10px;font-size:11px;background:var(--err);color:#fff;border:none;border-radius:6px;cursor:pointer">삭제</button>` : ''}
|
||||
</div>
|
||||
<div id="tg-bot-msg-${username}" style="font-size:11px;margin-top:6px"></div>
|
||||
`;
|
||||
} catch (e) {
|
||||
panel.innerHTML = `<div style="font-size:12px;color:var(--err)">${e.message}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
async function saveUserTelegramBot(username) {
|
||||
const input = document.getElementById(`tg-token-${username}`);
|
||||
const msg = document.getElementById(`tg-bot-msg-${username}`);
|
||||
const token = input ? input.value.trim() : '';
|
||||
if (!token) { if (msg) msg.textContent = '토큰을 입력해 주세요.'; return; }
|
||||
try {
|
||||
const data = await api(`/api/users/${encodeURIComponent(username)}/telegram-bot`, {
|
||||
method: 'POST', headers: {'Content-Type':'application/json'},
|
||||
body: JSON.stringify({ botToken: token }),
|
||||
});
|
||||
if (data.success) {
|
||||
if (msg) { msg.style.color = 'var(--ok)'; msg.textContent = '저장됨. 봇 연결 중...'; }
|
||||
setTimeout(() => loadUserTelegramBot(username), 2000);
|
||||
} else {
|
||||
if (msg) { msg.style.color = 'var(--err)'; msg.textContent = data.error || '저장 실패'; }
|
||||
}
|
||||
} catch (e) {
|
||||
if (msg) { msg.style.color = 'var(--err)'; msg.textContent = e.message; }
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteUserTelegramBot(username) {
|
||||
if (!confirm(`${username}의 텔레그램 봇을 삭제하시겠습니까?`)) return;
|
||||
const msg = document.getElementById(`tg-bot-msg-${username}`);
|
||||
try {
|
||||
const data = await api(`/api/users/${encodeURIComponent(username)}/telegram-bot`, {
|
||||
method: 'POST', headers: {'Content-Type':'application/json'},
|
||||
body: JSON.stringify({ botToken: '' }),
|
||||
});
|
||||
if (data.success) loadUserTelegramBot(username);
|
||||
else if (msg) { msg.style.color = 'var(--err)'; msg.textContent = data.error || '삭제 실패'; }
|
||||
} catch (e) {
|
||||
if (msg) { msg.style.color = 'var(--err)'; msg.textContent = e.message; }
|
||||
}
|
||||
}
|
||||
|
||||
// --- Per-User Email Accounts -------------------------------------------------
|
||||
|
||||
function toggleUserEmail(username) {
|
||||
const panel = document.getElementById(`user-email-panel-${username}`);
|
||||
if (!panel) return;
|
||||
if (panel.style.display === 'none') {
|
||||
panel.style.display = 'block';
|
||||
loadUserEmailAccounts(username);
|
||||
} else {
|
||||
panel.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
async function loadUserEmailAccounts(username) {
|
||||
const panel = document.getElementById(`user-email-panel-${username}`);
|
||||
if (!panel) return;
|
||||
panel.innerHTML = '<div style="font-size:12px;color:var(--muted)">불러오는 중…</div>';
|
||||
try {
|
||||
const data = await api(`/api/users/${encodeURIComponent(username)}/email/config`);
|
||||
const accounts = data.accounts || [];
|
||||
const def = data.default || '';
|
||||
const formId = `email-form-${username}`;
|
||||
const list = accounts.length === 0
|
||||
? '<div style="font-size:12px;color:var(--muted);margin-bottom:8px">등록된 이메일 계정이 없습니다.</div>'
|
||||
: accounts.map(a => `
|
||||
<div style="display:flex;align-items:center;gap:8px;padding:6px 8px;background:#fff;border:1px solid var(--line);border-radius:8px;margin-bottom:6px;font-size:12px">
|
||||
<strong style="min-width:90px">${escapeHtml(a.id)}</strong>
|
||||
${def === a.id ? '<span style="font-size:10px;background:var(--brand);color:#fff;padding:1px 6px;border-radius:6px">기본</span>' : ''}
|
||||
<span style="color:var(--muted);flex:1;font-family:'IBM Plex Mono',monospace;font-size:11px">${escapeHtml(a.username)} @ ${escapeHtml(a.imap_host)}:${a.imap_port}</span>
|
||||
${a.password_set ? '' : '<span style="font-size:10px;color:var(--err)">비번 없음</span>'}
|
||||
${def !== a.id ? `<button class="btn" style="padding:2px 8px;font-size:10px;background:var(--panel-2);border:1px solid var(--line);border-radius:6px;cursor:pointer" onclick="setDefaultUserEmailAccount('${username}','${escapeHtml(a.id)}')">기본 설정</button>` : ''}
|
||||
<button class="btn" style="padding:2px 8px;font-size:10px;background:var(--panel-2);border:1px solid var(--line);border-radius:6px;cursor:pointer" onclick="testUserEmailAccount('${username}','${escapeHtml(a.id)}',this)" ${a.password_set ? '' : 'disabled'}>테스트</button>
|
||||
<button class="btn" style="padding:2px 8px;font-size:10px;background:var(--err);color:#fff;border:none;border-radius:6px;cursor:pointer" onclick="deleteUserEmailAccount('${username}','${escapeHtml(a.id)}')">삭제</button>
|
||||
</div>`).join('');
|
||||
panel.innerHTML = `
|
||||
<div style="font-size:11px;color:var(--muted);margin-bottom:6px">이메일 계정 (${accounts.length})</div>
|
||||
${list}
|
||||
<details style="margin-top:8px"><summary style="font-size:12px;cursor:pointer;color:var(--muted)">+ 계정 추가/수정</summary>
|
||||
<div id="${formId}" style="margin-top:8px;padding:10px;background:#fff;border:1px solid var(--line);border-radius:8px;display:grid;grid-template-columns:1fr 1fr;gap:6px;font-size:12px">
|
||||
<label style="grid-column:1/3"><span style="color:var(--muted);font-size:11px">계정 ID (예: applecherry)</span>
|
||||
<input data-f="id" type="text" placeholder="applecherry" style="width:100%;border:1px solid var(--line);border-radius:6px;padding:5px 8px;font-size:12px;font-family:'IBM Plex Mono',monospace" /></label>
|
||||
<label><span style="color:var(--muted);font-size:11px">IMAP 호스트</span>
|
||||
<input data-f="imap_host" type="text" placeholder="imap.example.com" style="width:100%;border:1px solid var(--line);border-radius:6px;padding:5px 8px;font-size:12px" /></label>
|
||||
<label><span style="color:var(--muted);font-size:11px">IMAP 포트</span>
|
||||
<input data-f="imap_port" type="number" value="993" style="width:100%;border:1px solid var(--line);border-radius:6px;padding:5px 8px;font-size:12px" /></label>
|
||||
<label><span style="color:var(--muted);font-size:11px">SMTP 호스트</span>
|
||||
<input data-f="smtp_host" type="text" placeholder="smtp.example.com" style="width:100%;border:1px solid var(--line);border-radius:6px;padding:5px 8px;font-size:12px" /></label>
|
||||
<label><span style="color:var(--muted);font-size:11px">SMTP 포트</span>
|
||||
<input data-f="smtp_port" type="number" value="587" style="width:100%;border:1px solid var(--line);border-radius:6px;padding:5px 8px;font-size:12px" /></label>
|
||||
<label><span style="color:var(--muted);font-size:11px">사용자명 (이메일)</span>
|
||||
<input data-f="username" type="text" placeholder="user@example.com" style="width:100%;border:1px solid var(--line);border-radius:6px;padding:5px 8px;font-size:12px" /></label>
|
||||
<label><span style="color:var(--muted);font-size:11px">비밀번호 (vault에 암호화 저장)</span>
|
||||
<input data-f="password" type="password" autocomplete="new-password" style="width:100%;border:1px solid var(--line);border-radius:6px;padding:5px 8px;font-size:12px" /></label>
|
||||
<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:var(--muted)">
|
||||
<input data-f="imap_tls" type="checkbox" checked /> IMAP TLS</label>
|
||||
<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:var(--muted)">
|
||||
<input data-f="smtp_secure" type="checkbox" /> SMTP secure (465)</label>
|
||||
<button class="btn btn-primary" style="grid-column:1/3;padding:7px;margin-top:6px;font-size:12px" onclick="submitUserEmailAccount('${username}')">저장</button>
|
||||
<div id="${formId}-msg" style="grid-column:1/3;font-size:11px;color:var(--err)"></div>
|
||||
</div>
|
||||
</details>`;
|
||||
} catch (e) {
|
||||
panel.innerHTML = `<div style="font-size:12px;color:var(--err)">불러오기 실패: ${escapeHtml(e.message || e)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
async function submitUserEmailAccount(username) {
|
||||
const form = document.getElementById(`email-form-${username}`);
|
||||
const msg = document.getElementById(`email-form-${username}-msg`);
|
||||
if (!form) return;
|
||||
const get = (k) => form.querySelector(`[data-f="${k}"]`);
|
||||
const id = (get('id').value || '').trim();
|
||||
if (!/^[a-zA-Z0-9_-]{1,32}$/.test(id)) { msg.textContent = '계정 ID는 1-32자 영숫자/대시/언더스코어'; return; }
|
||||
const body = {
|
||||
imap_host: get('imap_host').value.trim(),
|
||||
imap_port: Number(get('imap_port').value) || 993,
|
||||
imap_tls: get('imap_tls').checked,
|
||||
smtp_host: get('smtp_host').value.trim(),
|
||||
smtp_port: Number(get('smtp_port').value) || 587,
|
||||
smtp_secure: get('smtp_secure').checked,
|
||||
username: get('username').value.trim(),
|
||||
password: get('password').value,
|
||||
};
|
||||
if (!body.imap_host || !body.smtp_host || !body.username) { msg.textContent = 'IMAP/SMTP 호스트와 사용자명은 필수'; return; }
|
||||
msg.textContent = '저장 중…'; msg.style.color = 'var(--muted)';
|
||||
try {
|
||||
await api(`/api/users/${encodeURIComponent(username)}/email/accounts/${encodeURIComponent(id)}`, {
|
||||
method: 'PUT', body: JSON.stringify(body),
|
||||
});
|
||||
loadUserEmailAccounts(username);
|
||||
} catch (e) {
|
||||
msg.textContent = e.message || '저장 실패'; msg.style.color = 'var(--err)';
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteUserEmailAccount(username, accountId) {
|
||||
if (!confirm(`계정 "${accountId}" 삭제하시겠습니까? (vault의 비밀번호도 함께 삭제됩니다)`)) return;
|
||||
try {
|
||||
await api(`/api/users/${encodeURIComponent(username)}/email/accounts/${encodeURIComponent(accountId)}`, { method: 'DELETE' });
|
||||
loadUserEmailAccounts(username);
|
||||
} catch (e) { alert(e.message || '삭제 실패'); }
|
||||
}
|
||||
|
||||
async function setDefaultUserEmailAccount(username, accountId) {
|
||||
try {
|
||||
await api(`/api/users/${encodeURIComponent(username)}/email/default`, {
|
||||
method: 'PUT', body: JSON.stringify({ accountId }),
|
||||
});
|
||||
loadUserEmailAccounts(username);
|
||||
} catch (e) { alert(e.message || '기본 설정 실패'); }
|
||||
}
|
||||
|
||||
async function testUserEmailAccount(username, accountId, btn) {
|
||||
const orig = btn.textContent;
|
||||
btn.disabled = true; btn.textContent = '연결 중…';
|
||||
try {
|
||||
const r = await api(`/api/users/${encodeURIComponent(username)}/email/accounts/${encodeURIComponent(accountId)}/test`, { method: 'POST' });
|
||||
if (r.success) { btn.textContent = '✓ 성공'; setTimeout(() => { btn.textContent = orig; btn.disabled = false; }, 1500); }
|
||||
else { alert(`테스트 실패: ${r.error || 'unknown'}`); btn.textContent = orig; btn.disabled = false; }
|
||||
} catch (e) {
|
||||
alert(e.message || '테스트 실패'); btn.textContent = orig; btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
let channelsStatusLoaded = false;
|
||||
|
||||
function setChannelStatus(idPrefix, state, message) {
|
||||
const dot = document.getElementById(`${idPrefix}-status-dot`);
|
||||
const text = document.getElementById(`${idPrefix}-status-text`);
|
||||
if (!dot || !text) return;
|
||||
if (state === 'ok') {
|
||||
dot.style.background = 'var(--ok)';
|
||||
text.style.color = 'var(--text)';
|
||||
} else if (state === 'warn') {
|
||||
dot.style.background = '#f0ad4e';
|
||||
text.style.color = '#b87b00';
|
||||
} else {
|
||||
dot.style.background = '#ccc';
|
||||
text.style.color = 'var(--muted)';
|
||||
}
|
||||
text.textContent = message || '미설정';
|
||||
}
|
||||
|
||||
function readChannelPayload(channel) {
|
||||
if (channel === 'kakao') {
|
||||
let userMap = {};
|
||||
try { userMap = JSON.parse(document.getElementById('settings-kk-usermap')?.value || '{}'); } catch {}
|
||||
return {
|
||||
appKey: (document.getElementById('settings-kk-appkey')?.value || '').trim(),
|
||||
channelEnabled: !!document.getElementById('settings-kk-channel-enabled')?.checked,
|
||||
userMap,
|
||||
};
|
||||
}
|
||||
if (channel === 'telegram') {
|
||||
const userIdStr = (document.getElementById('settings-tg-userid')?.value || '').trim();
|
||||
const allowedUserIds = userIdStr ? userIdStr.split(/[,\s]+/).map(Number).filter(n => !isNaN(n) && n > 0) : [];
|
||||
return {
|
||||
enabled: !!document.getElementById('settings-tg-enabled')?.checked,
|
||||
botToken: (document.getElementById('settings-tg-token')?.value || '').trim(),
|
||||
allowedUserIds,
|
||||
streamMode: 'full',
|
||||
};
|
||||
}
|
||||
if (channel === 'discord') {
|
||||
return {
|
||||
enabled: !!document.getElementById('settings-dc-enabled')?.checked,
|
||||
botToken: (document.getElementById('settings-dc-token')?.value || '').trim(),
|
||||
applicationId: (document.getElementById('settings-dc-appid')?.value || '').trim(),
|
||||
guildId: (document.getElementById('settings-dc-guildid')?.value || '').trim(),
|
||||
channelId: (document.getElementById('settings-dc-channelid')?.value || '').trim(),
|
||||
webhookUrl: (document.getElementById('settings-dc-webhook')?.value || '').trim(),
|
||||
};
|
||||
}
|
||||
return {
|
||||
enabled: !!document.getElementById('settings-wa-enabled')?.checked,
|
||||
accessToken: (document.getElementById('settings-wa-token')?.value || '').trim(),
|
||||
phoneNumberId: (document.getElementById('settings-wa-phoneid')?.value || '').trim(),
|
||||
businessAccountId: (document.getElementById('settings-wa-baid')?.value || '').trim(),
|
||||
verifyToken: (document.getElementById('settings-wa-verify')?.value || '').trim(),
|
||||
webhookSecret: (document.getElementById('settings-wa-secret')?.value || '').trim(),
|
||||
testRecipient: (document.getElementById('settings-wa-recipient')?.value || '').trim(),
|
||||
};
|
||||
}
|
||||
|
||||
function setButtonBusy(id, busy, busyLabel, normalLabel) {
|
||||
const btn = document.getElementById(id);
|
||||
if (!btn) return;
|
||||
btn.disabled = !!busy;
|
||||
btn.textContent = busy ? busyLabel : normalLabel;
|
||||
}
|
||||
|
||||
function getSelectedChannelType() {
|
||||
return String(document.getElementById('settings-channel-select')?.value || 'telegram');
|
||||
}
|
||||
|
||||
function onChannelTypeChange() {
|
||||
const ch = getSelectedChannelType();
|
||||
const formMap = {
|
||||
telegram: 'channel-form-telegram',
|
||||
kakao: 'channel-form-kakao',
|
||||
discord: 'channel-form-discord',
|
||||
whatsapp: 'channel-form-whatsapp',
|
||||
email: 'channel-form-email',
|
||||
};
|
||||
const guideMap = {
|
||||
telegram: 'channel-guide-telegram',
|
||||
kakao: 'channel-guide-kakao',
|
||||
discord: 'channel-guide-discord',
|
||||
whatsapp: 'channel-guide-whatsapp',
|
||||
email: 'channel-guide-email',
|
||||
};
|
||||
const statusMap = {
|
||||
telegram: 'tg-status-bar',
|
||||
kakao: 'kk-status-bar',
|
||||
discord: 'dc-status-bar',
|
||||
whatsapp: 'wa-status-bar',
|
||||
email: 'em-status-bar',
|
||||
};
|
||||
['telegram', 'kakao', 'discord', 'whatsapp', 'email'].forEach((k) => {
|
||||
const form = document.getElementById(formMap[k]);
|
||||
const guide = document.getElementById(guideMap[k]);
|
||||
const status = document.getElementById(statusMap[k]);
|
||||
if (form) form.style.display = (k === ch) ? 'block' : 'none';
|
||||
if (guide) guide.style.display = (k === ch) ? 'block' : 'none';
|
||||
if (status) status.style.display = (k === ch) ? 'flex' : 'none';
|
||||
});
|
||||
// Email: hide test/send-test buttons (email has per-account test)
|
||||
// Kakao: hide "테스트" (연결 확인 없음), 테스트 전송만 노출
|
||||
const testBtn = document.getElementById('channel-test-btn');
|
||||
const sendTestBtn = document.getElementById('channel-send-test-btn');
|
||||
if (testBtn) testBtn.style.display = (ch === 'email' || ch === 'kakao') ? 'none' : '';
|
||||
if (sendTestBtn) sendTestBtn.style.display = (ch === 'email') ? 'none' : '';
|
||||
if (ch === 'email') loadEmailAccounts();
|
||||
if (ch === 'kakao') loadKakaoStatus();
|
||||
}
|
||||
|
||||
async function saveSelectedChannelSettings() {
|
||||
await saveChannelSettings(getSelectedChannelType());
|
||||
}
|
||||
|
||||
async function testSelectedChannel() {
|
||||
await testChannel(getSelectedChannelType());
|
||||
}
|
||||
|
||||
async function sendSelectedChannelTest() {
|
||||
await sendChannelTest(getSelectedChannelType());
|
||||
}
|
||||
|
||||
async function loadChannelsStatus() {
|
||||
try {
|
||||
const data = await api('/api/channels/status');
|
||||
if (!data?.success) return;
|
||||
const tg = data.telegram || {};
|
||||
const dc = data.discord || {};
|
||||
const wa = data.whatsapp || {};
|
||||
|
||||
if (tg.connected && tg.polling) setChannelStatus('tg', 'ok', `Connected as @${tg.username || 'bot'}`);
|
||||
else if (tg.hasToken) setChannelStatus('tg', 'warn', 'Token saved, not connected');
|
||||
else setChannelStatus('tg', 'off', '미설정');
|
||||
|
||||
if (dc.hasToken || dc.hasWebhook) setChannelStatus('dc', 'warn', 'Credentials saved');
|
||||
else setChannelStatus('dc', 'off', '미설정');
|
||||
|
||||
if (wa.hasAccessToken && wa.phoneNumberId) setChannelStatus('wa', 'warn', 'Credentials saved');
|
||||
else setChannelStatus('wa', 'off', '미설정');
|
||||
|
||||
if (!channelsStatusLoaded) {
|
||||
channelsStatusLoaded = true;
|
||||
if (tg.hasToken) document.getElementById('settings-tg-token').placeholder = '\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022 (saved)';
|
||||
if (dc.hasToken) document.getElementById('settings-dc-token').placeholder = '\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022 (saved)';
|
||||
if (wa.hasAccessToken) document.getElementById('settings-wa-token').placeholder = '\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022 (saved)';
|
||||
|
||||
document.getElementById('settings-tg-enabled').checked = !!tg.enabled;
|
||||
document.getElementById('settings-tg-userid').value = (tg.allowedUserIds || []).join(', ');
|
||||
|
||||
document.getElementById('settings-dc-enabled').checked = !!dc.enabled;
|
||||
document.getElementById('settings-dc-appid').value = dc.applicationId || '';
|
||||
document.getElementById('settings-dc-guildid').value = dc.guildId || '';
|
||||
document.getElementById('settings-dc-channelid').value = dc.channelId || '';
|
||||
|
||||
document.getElementById('settings-wa-enabled').checked = !!wa.enabled;
|
||||
document.getElementById('settings-wa-phoneid').value = wa.phoneNumberId || '';
|
||||
document.getElementById('settings-wa-baid').value = wa.businessAccountId || '';
|
||||
document.getElementById('settings-wa-recipient').value = wa.testRecipient || '';
|
||||
}
|
||||
onChannelTypeChange();
|
||||
} catch (err) {
|
||||
console.error('[Channels] Status load failed:', err);
|
||||
}
|
||||
// Load heartbeat notify toggle
|
||||
try {
|
||||
const hbData = await api('/api/heartbeat/config');
|
||||
if (hbData?.success) {
|
||||
document.getElementById('settings-hb-notify').checked = hbData.config.notifyEnabled !== false;
|
||||
updateHbNotifyLabel();
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
async function loadKakaoStatus() {
|
||||
try {
|
||||
const data = await api('/api/kakao/status');
|
||||
const n = data?.notify || {};
|
||||
const c = data?.channel || {};
|
||||
if (n.hasAppKey && n.hasRefreshToken) setChannelStatus('kk', 'ok', '알림 연동됨' + (c.enabled ? ' + 챗봇 활성' : ''));
|
||||
else if (n.hasAppKey) setChannelStatus('kk', 'warn', 'API 키 있음 — OAuth 로그인 필요');
|
||||
else setChannelStatus('kk', 'off', '미설정');
|
||||
if (n.hasAppKey) document.getElementById('settings-kk-appkey').placeholder = '•••••••• (저장됨)';
|
||||
document.getElementById('settings-kk-channel-enabled').checked = !!c.enabled;
|
||||
const linkBtn = document.getElementById('kk-send-link-btn');
|
||||
if (linkBtn) linkBtn.style.display = (n.hasRefreshToken) ? 'inline-block' : 'none';
|
||||
} catch {}
|
||||
}
|
||||
|
||||
async function kakaoOAuthStart() {
|
||||
const appKey = (document.getElementById('settings-kk-appkey')?.value || '').trim();
|
||||
if (appKey) {
|
||||
// 먼저 appKey 저장
|
||||
await saveChannelSettings('kakao');
|
||||
}
|
||||
const status = document.getElementById('kk-oauth-status');
|
||||
if (status) status.textContent = '새 창에서 로그인 중...';
|
||||
const w = window.open('/api/kakao/auth/start', '_blank', 'width=600,height=700');
|
||||
if (!w) { alert('팝업이 차단됐습니다. 팝업을 허용해 주세요.'); return; }
|
||||
const timer = setInterval(async () => {
|
||||
if (w.closed) {
|
||||
clearInterval(timer);
|
||||
await loadKakaoStatus();
|
||||
if (status) status.textContent = '';
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
async function kakaoSendChannelLink() {
|
||||
const btn = document.getElementById('kk-send-link-btn');
|
||||
const orig = btn?.textContent;
|
||||
if (btn) btn.textContent = '전송 중...';
|
||||
try {
|
||||
const data = await api('/api/kakao/send-channel-link', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ channelUrl: 'http://pf.kakao.com/_KxjxexfX/chat' }),
|
||||
});
|
||||
if (btn) btn.textContent = data.success ? '✅ 전송됨!' : '❌ 실패';
|
||||
} catch {
|
||||
if (btn) btn.textContent = '❌ 실패';
|
||||
}
|
||||
setTimeout(() => { if (btn) btn.textContent = orig; }, 3000);
|
||||
}
|
||||
|
||||
async function saveChannelSettings(channel) {
|
||||
const payload = readChannelPayload(channel);
|
||||
try {
|
||||
const data = await api('/api/channels/config', {
|
||||
method: 'POST',
|
||||
headers:{'Content-Type':'application/json'},
|
||||
body: JSON.stringify({ channels: { [channel]: payload } }),
|
||||
});
|
||||
if (data?.success) {
|
||||
addProcessEntry('final', `${channel} settings saved.`);
|
||||
channelsStatusLoaded = false;
|
||||
await loadChannelsStatus();
|
||||
} else {
|
||||
alert('Save failed: ' + (data?.error || 'unknown error'));
|
||||
}
|
||||
} catch (err) {
|
||||
alert('Save failed: ' + err.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function testChannel(channel) {
|
||||
const btnId = document.getElementById('channel-test-btn')
|
||||
? 'channel-test-btn'
|
||||
: channel === 'telegram' ? 'tg-test-btn' : channel === 'discord' ? 'dc-test-btn' : 'wa-test-btn';
|
||||
setButtonBusy(btnId, true, 'Testing...', 'Test');
|
||||
try {
|
||||
const payload = readChannelPayload(channel);
|
||||
const data = await api(`/api/channels/test/${channel}`, {
|
||||
method: 'POST',
|
||||
headers:{'Content-Type':'application/json'},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (data?.success) {
|
||||
if (channel === 'telegram') setChannelStatus('tg', 'ok', `Valid bot @${data?.bot?.username || 'telegram'}`);
|
||||
if (channel === 'discord') setChannelStatus('dc', 'ok', `Valid bot @${data?.bot?.username || 'discord'}`);
|
||||
if (channel === 'whatsapp') setChannelStatus('wa', 'ok', `Valid phone ${data?.account?.display_phone_number || data?.account?.id || ''}`.trim());
|
||||
addProcessEntry('final', `${channel} connection test passed.`);
|
||||
} else {
|
||||
alert(`${channel} test failed: ${data?.error || 'unknown error'}`);
|
||||
}
|
||||
} catch (err) {
|
||||
alert(`${channel} test failed: ${err.message}`);
|
||||
}
|
||||
setButtonBusy(btnId, false, 'Testing...', 'Test');
|
||||
}
|
||||
|
||||
async function sendChannelTest(channel) {
|
||||
const btnId = document.getElementById('channel-send-test-btn')
|
||||
? 'channel-send-test-btn'
|
||||
: channel === 'telegram' ? 'tg-send-test-btn' : channel === 'discord' ? 'dc-send-test-btn' : 'wa-send-test-btn';
|
||||
setButtonBusy(btnId, true, 'Sending...', 'Send Test');
|
||||
try {
|
||||
const payload = readChannelPayload(channel);
|
||||
const data = await api(`/api/channels/send-test/${channel}`, {
|
||||
method: 'POST',
|
||||
headers:{'Content-Type':'application/json'},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (data?.success) {
|
||||
addProcessEntry('final', `Test message sent via ${channel}.`);
|
||||
} else {
|
||||
alert(`${channel} send-test failed: ${data?.error || 'unknown error'}`);
|
||||
}
|
||||
} catch (err) {
|
||||
alert(`${channel} send-test failed: ${err.message}`);
|
||||
}
|
||||
setButtonBusy(btnId, false, 'Sending...', 'Send Test');
|
||||
}
|
||||
|
||||
let emailAccountsCache = [];
|
||||
|
||||
function getCurrentUsername() {
|
||||
if (typeof currentUser === 'object' && currentUser?.username) return currentUser.username;
|
||||
try { return localStorage.getItem(LAST_USER_KEY) || ''; } catch { return ''; }
|
||||
}
|
||||
|
||||
async function loadEmailAccounts() {
|
||||
const username = getCurrentUsername();
|
||||
if (!username) {
|
||||
document.getElementById('email-accounts-list').innerHTML = '<div style="font-size:12px;color:var(--muted)">사용자 정보를 불러올 수 없습니다.</div>';
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const data = await api(`/api/users/${encodeURIComponent(username)}/email/config`);
|
||||
const accounts = data?.accounts || [];
|
||||
emailAccountsCache = accounts;
|
||||
const count = accounts.length;
|
||||
if (count > 0) setChannelStatus('em', 'ok', `${count}개 계정 연결됨`);
|
||||
else setChannelStatus('em', 'off', '미설정');
|
||||
renderEmailAccountsList(accounts);
|
||||
} catch (err) {
|
||||
document.getElementById('email-accounts-list').innerHTML = '<div style="font-size:12px;color:var(--muted)">이메일 계정을 불러올 수 없습니다.</div>';
|
||||
}
|
||||
}
|
||||
|
||||
function renderEmailAccountsList(accounts) {
|
||||
const container = document.getElementById('email-accounts-list');
|
||||
if (!accounts.length) {
|
||||
container.innerHTML = '<div style="font-size:12px;color:var(--muted);margin-bottom:6px">등록된 이메일 계정이 없습니다.</div>';
|
||||
return;
|
||||
}
|
||||
container.innerHTML = accounts.map(a => {
|
||||
const esc = s => String(s||'').replace(/</g,'<');
|
||||
return `<div style="border:1px solid var(--line);border-radius:8px;padding:8px 10px;margin-bottom:6px;background:var(--panel-2)">
|
||||
<div style="display:flex;align-items:center;justify-content:space-between">
|
||||
<div>
|
||||
<span style="font-weight:600;font-size:13px">${esc(a.id)}</span>
|
||||
<span style="font-size:11px;color:var(--muted);margin-left:6px">${esc(a.username)}</span>
|
||||
</div>
|
||||
<div style="display:flex;gap:4px">
|
||||
<button class="btn btn-sm" onclick="testEmailAccount('${esc(a.id)}')" style="background:#fff;border:1px solid var(--line);color:var(--text);padding:3px 8px;font-size:11px">테스트</button>
|
||||
<button class="btn btn-sm" onclick="editEmailAccount('${esc(a.id)}')" style="background:#fff;border:1px solid var(--line);color:var(--text);padding:3px 8px;font-size:11px">수정</button>
|
||||
<button class="btn btn-sm" onclick="deleteEmailAccount('${esc(a.id)}')" style="background:#fff;border:1px solid #e55;color:#e55;padding:3px 8px;font-size:11px">삭제</button>
|
||||
</div>
|
||||
</div>
|
||||
<div style="font-size:11px;color:var(--muted);margin-top:2px">IMAP: ${esc(a.imap_host)}:${a.imap_port} | SMTP: ${esc(a.smtp_host)}:${a.smtp_port}</div>
|
||||
</div>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
async function saveEmailAccount() {
|
||||
const username = getCurrentUsername();
|
||||
if (!username) { alert('사용자 정보를 확인할 수 없습니다.'); return; }
|
||||
const id = document.getElementById('em-id').value.trim();
|
||||
if (!id) { alert('계정 ID를 입력하세요.'); return; }
|
||||
if (!/^[a-zA-Z0-9_-]{1,32}$/.test(id)) { alert('계정 ID는 1-32자의 영문, 숫자, 대시, 언더스코어만 가능합니다.'); return; }
|
||||
const username_field = document.getElementById('em-username').value.trim();
|
||||
if (!username_field) { alert('이메일 주소를 입력하세요.'); return; }
|
||||
const imap_host = document.getElementById('em-imap-host').value.trim();
|
||||
if (!imap_host) { alert('IMAP 서버를 입력하세요.'); return; }
|
||||
const smtp_host = document.getElementById('em-smtp-host').value.trim();
|
||||
if (!smtp_host) { alert('SMTP 서버를 입력하세요.'); return; }
|
||||
const payload = {
|
||||
imap_host,
|
||||
imap_port: Number(document.getElementById('em-imap-port').value) || 993,
|
||||
imap_tls: !!document.getElementById('em-imap-tls').checked,
|
||||
imap_reject_unauthorized: true,
|
||||
smtp_host,
|
||||
smtp_port: Number(document.getElementById('em-smtp-port').value) || 587,
|
||||
smtp_secure: !!document.getElementById('em-smtp-secure').checked,
|
||||
smtp_reject_unauthorized: true,
|
||||
username: username_field,
|
||||
password: document.getElementById('em-password').value || undefined,
|
||||
};
|
||||
try {
|
||||
const data = await api(`/api/users/${encodeURIComponent(username)}/email/accounts/${encodeURIComponent(id)}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (data?.success) {
|
||||
addProcessEntry('final', `Email account "${id}" saved.`);
|
||||
document.getElementById('em-password').value = '';
|
||||
await loadEmailAccounts();
|
||||
} else {
|
||||
alert('저장 실패: ' + (data?.error || '알 수 없는 오류'));
|
||||
}
|
||||
} catch (err) {
|
||||
alert('저장 실패: ' + err.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function testEmailAccount(accountId) {
|
||||
const username = getCurrentUsername();
|
||||
if (!username) return;
|
||||
try {
|
||||
const data = await api(`/api/users/${encodeURIComponent(username)}/email/accounts/${encodeURIComponent(accountId)}/test`, {
|
||||
method: 'POST',
|
||||
});
|
||||
if (data?.success) {
|
||||
addProcessEntry('final', `Email account "${accountId}" IMAP connection OK.`);
|
||||
} else {
|
||||
alert(`테스트 실패: ${data?.error || '알 수 없는 오류'}`);
|
||||
}
|
||||
} catch (err) {
|
||||
alert('테스트 실패: ' + err.message);
|
||||
}
|
||||
}
|
||||
|
||||
function editEmailAccount(accountId) {
|
||||
const acct = emailAccountsCache.find(a => a.id === accountId);
|
||||
if (!acct) return;
|
||||
document.getElementById('em-id').value = acct.id;
|
||||
document.getElementById('em-username').value = acct.username || '';
|
||||
document.getElementById('em-imap-host').value = acct.imap_host || '';
|
||||
document.getElementById('em-imap-port').value = acct.imap_port || 993;
|
||||
document.getElementById('em-smtp-host').value = acct.smtp_host || '';
|
||||
document.getElementById('em-smtp-port').value = acct.smtp_port || 587;
|
||||
document.getElementById('em-imap-tls').checked = acct.imap_tls !== false;
|
||||
document.getElementById('em-smtp-secure').checked = acct.smtp_secure === true;
|
||||
document.getElementById('em-password').value = '';
|
||||
document.getElementById('em-password').placeholder = '•••••••• (변경 시에만 입력)';
|
||||
}
|
||||
|
||||
async function deleteEmailAccount(accountId) {
|
||||
if (!confirm(`이메일 계정 "${accountId}"를 삭제하시겠습니까?`)) return;
|
||||
const username = getCurrentUsername();
|
||||
if (!username) return;
|
||||
try {
|
||||
const data = await api(`/api/users/${encodeURIComponent(username)}/email/accounts/${encodeURIComponent(accountId)}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
if (data?.success) {
|
||||
addProcessEntry('final', `Email account "${accountId}" deleted.`);
|
||||
await loadEmailAccounts();
|
||||
} else {
|
||||
alert('삭제 실패: ' + (data?.error || '알 수 없는 오류'));
|
||||
}
|
||||
} catch (err) {
|
||||
alert('삭제 실패: ' + err.message);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,141 @@
|
||||
// terminal.js — PTY 기반 터미널(xterm) — 코드 채팅 탭 내 터미널 포함.
|
||||
// extracted from app.js (v4.3.19-3 split).
|
||||
|
||||
function v2LiveCodeUpdate() {}
|
||||
function codeEditorWriteFile() {}
|
||||
|
||||
// ── Terminal infrastructure (PTY over WebSocket) ─────────────────────────
|
||||
let termWs = null;
|
||||
let termWsConnected = false;
|
||||
|
||||
function termWsConnect() {
|
||||
if (termWs && (termWs.readyState === WebSocket.OPEN || termWs.readyState === WebSocket.CONNECTING)) return;
|
||||
const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
let url = `${proto}//${location.host}/ws`;
|
||||
const token = sessionStorage.getItem('smallclaw_token') || getCookie('smallclaw_session');
|
||||
if (token) url += `?token=${encodeURIComponent(token)}`;
|
||||
try { termWs = new WebSocket(url); } catch { return; }
|
||||
termWs.onopen = () => {
|
||||
termWsConnected = true;
|
||||
for (const [shellId, inst] of xtermInstances) {
|
||||
if (!inst.ptyReady) { inst.ptyReady = true; termWsSend({ type: 'pty_spawn', shellId, cols: inst.term.cols, rows: inst.term.rows }); }
|
||||
}
|
||||
};
|
||||
termWs.onmessage = (ev) => {
|
||||
let msg; try { msg = JSON.parse(ev.data); } catch { return; }
|
||||
if (msg.type === 'pty_output') { const i = xtermInstances.get(msg.shellId); if (i) i.term.write(msg.data); }
|
||||
else if (msg.type === 'pty_exit') { const i = xtermInstances.get(msg.shellId); if (i) { i.ptyReady = false; i.term.write('\r\n\x1b[90m[exited]\x1b[0m\r\n'); } }
|
||||
else if (msg.type === 'pty_error') { const i = xtermInstances.get(msg.shellId); if (i) i.term.write('\r\n\x1b[31mPTY error: '+(msg.error||'?')+'\x1b[0m\r\n'); }
|
||||
};
|
||||
termWs.onclose = () => {
|
||||
termWsConnected = false; termWs = null;
|
||||
for (const [,i] of xtermInstances) i.ptyReady = false;
|
||||
setTimeout(termWsConnect, 3000);
|
||||
};
|
||||
termWs.onerror = () => { termWsConnected = false; };
|
||||
}
|
||||
|
||||
function termWsSend(msg) {
|
||||
if (termWs && termWs.readyState === WebSocket.OPEN) { termWs.send(JSON.stringify(msg)); return true; }
|
||||
return false;
|
||||
}
|
||||
|
||||
const xtermInstances = new Map();
|
||||
|
||||
function createXtermShell(container, shellId) {
|
||||
const id = shellId || 'sh_' + Math.random().toString(36).slice(2, 8);
|
||||
const sub = document.createElement('div');
|
||||
sub.id = 'xterm-' + id;
|
||||
sub.style.cssText = 'position:absolute;inset:0';
|
||||
container.appendChild(sub);
|
||||
const term = new Terminal({
|
||||
theme: { background:'#0C0C0C', foreground:'#CCCCCC', cursor:'#22c55e',
|
||||
selectionBackground:'rgba(34,197,94,0.3)', red:'#E74856', green:'#16C60C',
|
||||
yellow:'#C19C00', blue:'#3B78FF', cyan:'#61D6D6', white:'#CCCCCC',
|
||||
brightBlack:'#767676', brightGreen:'#69FF69', brightWhite:'#FFFFFF' },
|
||||
fontFamily: "'IBM Plex Mono','Courier New',monospace",
|
||||
fontSize: 13, lineHeight: 1.4, cursorBlink: true, scrollback: 5000,
|
||||
});
|
||||
const fitAddon = new FitAddon.FitAddon();
|
||||
const webLinksAddon = new WebLinksAddon.WebLinksAddon();
|
||||
term.loadAddon(fitAddon); term.loadAddon(webLinksAddon);
|
||||
term.open(sub); fitAddon.fit();
|
||||
const inst = { term, fitAddon, ptyReady: false };
|
||||
xtermInstances.set(id, inst);
|
||||
term.onData(data => { if (termWsConnected && inst.ptyReady) termWsSend({ type: 'pty_input', shellId: id, data }); });
|
||||
term.onResize(({ cols, rows }) => { if (termWsConnected && inst.ptyReady) termWsSend({ type: 'pty_resize', shellId: id, cols, rows }); });
|
||||
if (termWsConnected) { inst.ptyReady = true; termWsSend({ type: 'pty_spawn', shellId: id, cols: term.cols, rows: term.rows }); }
|
||||
return { id, term, fitAddon, inst };
|
||||
}
|
||||
|
||||
// Init WebSocket connection on load
|
||||
fetch('/api/status').then(r => r.json()).catch(() => ({})).finally(termWsConnect);
|
||||
|
||||
// ── Chat terminal (for chat view) ─────────────────────────────────────────
|
||||
let chatTermShells = [];
|
||||
let activeChatTermShellId = null;
|
||||
let chatTermOpen = false;
|
||||
let chatTermHeight = 280;
|
||||
|
||||
function toggleChatTerminal() {
|
||||
const panel = document.getElementById('chat-terminal-panel');
|
||||
const btn = document.getElementById('chat-term-btn');
|
||||
if (!panel) return;
|
||||
chatTermOpen = !chatTermOpen;
|
||||
if (chatTermOpen) {
|
||||
panel.style.display = 'flex';
|
||||
if (btn) btn.classList.add('active');
|
||||
if (!chatTermShells.length) { addChatTermShell(); }
|
||||
else { setTimeout(() => { const s = chatTermShells.find(s => s.id === activeChatTermShellId); if (s?.fitAddon) s.fitAddon.fit(); if (s?.term) s.term.focus(); }, 50); }
|
||||
} else {
|
||||
panel.style.display = 'none';
|
||||
if (btn) btn.classList.remove('active');
|
||||
}
|
||||
}
|
||||
function renderChatShellTabs() {
|
||||
const bar = document.getElementById('chat-shell-tabs'); if (!bar) return;
|
||||
bar.innerHTML = chatTermShells.map(s => {
|
||||
const a = s.id === activeChatTermShellId;
|
||||
return `<div class="ct-tab${a?' active':''}" onclick="switchChatTermShell('${s.id}')"><svg width="10" height="10" viewBox="0 0 16 16" fill="currentColor" style="opacity:.6"><path d="M14 3v10H2V3h12zM1 2v12h14V2H1zm5 9l3-2.5L6 6v5z"/></svg><span>${escHtml(s.name)}</span>${chatTermShells.length>1?`<span class="ct-tab-close" onclick="closeChatTermShell('${s.id}',event)">×</span>`:''}</div>`;
|
||||
}).join('');
|
||||
}
|
||||
function addChatTermShell() {
|
||||
const id = 'ct_' + Math.random().toString(36).slice(2,8);
|
||||
chatTermShells.push({ id, name:'bash', ptyReady:false, term:null, fitAddon:null });
|
||||
switchChatTermShell(id);
|
||||
}
|
||||
function switchChatTermShell(id) {
|
||||
const cur = chatTermShells.find(s => s.id === activeChatTermShellId);
|
||||
if (cur) { const sub = document.getElementById('xterm-'+cur.id); if (sub) sub.style.display='none'; }
|
||||
activeChatTermShellId = id;
|
||||
const shell = chatTermShells.find(s => s.id === id); if (!shell) return;
|
||||
if (shell.term) {
|
||||
const sub = document.getElementById('xterm-'+shell.id); if (sub) sub.style.display='';
|
||||
if (shell.fitAddon) shell.fitAddon.fit(); shell.term.focus();
|
||||
} else {
|
||||
const container = document.getElementById('chat-term-container');
|
||||
if (container) { const r = createXtermShell(container, shell.id); shell.term=r.term; shell.fitAddon=r.fitAddon; shell.ptyReady=r.inst.ptyReady; setTimeout(()=>{r.fitAddon.fit();r.term.focus();},50); }
|
||||
}
|
||||
renderChatShellTabs();
|
||||
}
|
||||
function closeChatTermShell(id, ev) {
|
||||
if (ev) ev.stopPropagation();
|
||||
const idx = chatTermShells.findIndex(s => s.id === id);
|
||||
if (idx === -1 || chatTermShells.length <= 1) return;
|
||||
termWsSend({ type:'pty_kill', shellId:id });
|
||||
const shell = chatTermShells[idx]; if (shell.term) shell.term.dispose();
|
||||
xtermInstances.delete(id); const sub = document.getElementById('xterm-'+id); if (sub) sub.remove();
|
||||
chatTermShells.splice(idx, 1);
|
||||
if (activeChatTermShellId === id) switchChatTermShell(chatTermShells[Math.min(idx,chatTermShells.length-1)].id);
|
||||
else renderChatShellTabs();
|
||||
}
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const handle = document.getElementById('chat-term-resize-handle'); if (!handle) return;
|
||||
let startY=0, startH=0;
|
||||
handle.addEventListener('mousedown', function(e) {
|
||||
startY=e.clientY; startH=chatTermHeight;
|
||||
const onMove = e2 => { const dy=startY-e2.clientY; chatTermHeight=Math.max(120,Math.min(window.innerHeight*.7,startH+dy)); const p=document.getElementById('chat-terminal-panel'); if(p) p.style.height=chatTermHeight+'px'; const s=chatTermShells.find(s=>s.id===activeChatTermShellId); if(s?.fitAddon) s.fitAddon.fit(); };
|
||||
const onUp = () => { document.removeEventListener('mousemove',onMove); document.removeEventListener('mouseup',onUp); };
|
||||
document.addEventListener('mousemove', onMove); document.addEventListener('mouseup', onUp); e.preventDefault();
|
||||
});
|
||||
});
|
||||
File renamed without changes.
File renamed without changes.
@@ -6534,7 +6534,7 @@ async function _cupUploadESP32() {
|
||||
const b64 = data.merged || data.bin;
|
||||
if (!b64) throw new Error('컴파일 결과에 바이너리가 없습니다');
|
||||
cupLog('esptool-js 로딩 중...', 'prog');
|
||||
const { ESPLoader, Transport, HardReset } = await import('/esptool-bundle.js');
|
||||
const { ESPLoader, Transport, HardReset } = await import('/js/code-editor/esptool-bundle.js');
|
||||
cupLog('보드 연결 중 (자동 리셋)...', 'prog'); _cupSetStatus('uploading', '연결 중...');
|
||||
transport = new Transport(_cupPort, true);
|
||||
const terminal = { clean:()=>{}, writeLine:m=>{ if(m.trim()) cupLog(m,'info'); }, write:m=>{ if(m.trim()) cupLog(m,'info'); } };
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Reference in new issue
Block a user