729 lines
41 KiB
JavaScript
729 lines
41 KiB
JavaScript
// The management app's screens (app/src/admin.spec.md, "Screens"). Plain ES module, no build step:
|
||
// the Tauri shell and the development server load the same files. Every action goes through
|
||
// api(command, args), which the shell answers with AdminApi::call.
|
||
|
||
const $ = (sel, el = document) => el.querySelector(sel);
|
||
const h = (tag, attrs = {}, ...kids) => {
|
||
const el = document.createElement(tag);
|
||
for (const [k, v] of Object.entries(attrs)) {
|
||
if (k === "class") el.className = v;
|
||
else if (k.startsWith("on")) el.addEventListener(k.slice(2), v);
|
||
else if (v === true) el.setAttribute(k, "");
|
||
else if (v !== false && v != null) el.setAttribute(k, v);
|
||
}
|
||
for (const kid of kids.flat()) if (kid != null) el.append(kid instanceof Node ? kid : String(kid));
|
||
return el;
|
||
};
|
||
|
||
const token = new URLSearchParams(location.hash.slice(1)).get("token");
|
||
async function api(command, args = {}) {
|
||
if (window.__TAURI__) return window.__TAURI__.core.invoke("admin", { command, args });
|
||
const r = await fetch(`/api/${command}`, { method: "POST", headers: { "x-admin-token": token || "" },
|
||
body: JSON.stringify(args) });
|
||
const out = await r.json();
|
||
if (!out.ok) throw new Error(out.error);
|
||
return out.value;
|
||
}
|
||
|
||
function toast(msg, bad = false) {
|
||
const t = $("#toast");
|
||
t.textContent = msg;
|
||
t.className = bad ? "toast bad" : "toast";
|
||
t.hidden = false;
|
||
clearTimeout(toast.timer);
|
||
toast.timer = setTimeout(() => (t.hidden = true), bad ? 6000 : 2500);
|
||
}
|
||
const fail = (e) => toast(e.message || String(e), true);
|
||
const gb = (b) => (b / 1e9).toFixed(0) + " GB";
|
||
|
||
const CHOICE = {
|
||
"call.mode": { wakeWord: "호출어로 부를 때만", addressed: "자비스에게 하는 말로 보이면", everything: "모든 말" },
|
||
"response.policy": { first: "처음 대화만", inOrder: "순서대로", latest: "가장 최근 것", important: "중요한 것 먼저" },
|
||
};
|
||
const REASON = { busy: "다른 답을 하는 중", queue_full: "대기열이 가득 참", replaced: "더 새 요청이 대신함",
|
||
interrupted: "끼어들어 멈춤", lower_score: "다른 요청이 더 중요함", stopped: "정지 명령" };
|
||
const BROWSER = { off: "꺼짐", ready: "준비", failed: "실패", exited: "꺼짐(스스로 끝남)" };
|
||
const STATE = { stopped: ["꺼짐", ""], starting: ["켜는 중", "warn"], running: ["실행 중", "ok"],
|
||
stopping: ["끄는 중", "warn"], failed: ["실패", "bad"] };
|
||
|
||
// ---- settings screens, built from the field list ------------------------------------------------
|
||
|
||
let FIELDS = null;
|
||
async function fields() {
|
||
return FIELDS ??= await api("settings_fields");
|
||
}
|
||
|
||
/** An input for one field; read() gives the value to save, or throws with a message. */
|
||
function editor(f, value) {
|
||
const id = "f-" + f.path.replace(/\W/g, "-");
|
||
let el, read;
|
||
const lines = (v) => (v || []).join("\n");
|
||
const fromLines = (s) => s.split("\n").map((x) => x.trim()).filter(Boolean);
|
||
switch (f.type) {
|
||
case "bool":
|
||
el = h("input", { type: "checkbox", class: "switch", id });
|
||
el.checked = !!value;
|
||
read = () => el.checked;
|
||
break;
|
||
case "int": case "number":
|
||
el = h("input", { type: "number", id, min: f.min, max: f.max, step: f.type === "int" ? 1 : "any", value });
|
||
read = () => {
|
||
const n = Number(el.value);
|
||
if (el.value === "" || Number.isNaN(n) || n < f.min || n > f.max) throw new Error(`${f.label}: ${f.min}~${f.max}`);
|
||
return n;
|
||
};
|
||
break;
|
||
case "nullableNumber":
|
||
el = h("input", { type: "number", id, step: "any", value: value ?? "" });
|
||
read = () => (el.value === "" ? null : Number(el.value));
|
||
break;
|
||
case "text":
|
||
el = f.max > 100 ? h("textarea", { id }, value ?? "") : h("input", { type: "text", id, value: value ?? "" });
|
||
read = () => el.value.trim();
|
||
break;
|
||
case "languageCode":
|
||
el = h("input", { type: "text", id, value: value ?? "", placeholder: "자동" });
|
||
read = () => (el.value.trim() === "" ? null : el.value.trim());
|
||
break;
|
||
case "textList":
|
||
el = h("textarea", { id, placeholder: f.nullable ? "비우면 음성 호출어와 같음" : "한 줄에 하나" }, lines(value));
|
||
read = () => {
|
||
const v = fromLines(el.value);
|
||
return f.nullable && v.length === 0 ? null : v;
|
||
};
|
||
break;
|
||
case "choice":
|
||
el = h("select", { id }, f.values.map((v) => h("option", { value: v, selected: v === value }, CHOICE[f.path]?.[v] ?? v)));
|
||
read = () => el.value;
|
||
break;
|
||
case "id":
|
||
if (f.path === "discord.guildId" || f.path === "discord.voiceChannelId") {
|
||
// A picker of the bot's servers and the chosen server's voice channels (the ID stays if the
|
||
// list cannot be read).
|
||
el = h("select", { id, "data-picker": f.path }, h("option", { value: value ?? "" }, value ?? "선택 안 함"));
|
||
read = () => el.value || null;
|
||
break;
|
||
}
|
||
el = h("input", { type: "text", id, value: value ?? "", placeholder: "디스코드 ID" });
|
||
read = () => (el.value.trim() === "" ? null : el.value.trim());
|
||
break;
|
||
case "idList":
|
||
el = h("textarea", { id, placeholder: "디스코드 사용자 ID, 한 줄에 하나" }, lines(value));
|
||
read = () => fromLines(el.value);
|
||
break;
|
||
case "idNumberMap":
|
||
el = h("textarea", { id, placeholder: "사용자ID=우선순위" },
|
||
Object.entries(value || {}).map(([k, v]) => `${k}=${v}`).join("\n"));
|
||
read = () => Object.fromEntries(fromLines(el.value).map((l) => {
|
||
const [k, v] = l.split("=").map((x) => x.trim());
|
||
if (!k || v === undefined || Number.isNaN(Number(v))) throw new Error(`${f.label}: "사용자ID=숫자" 형식`);
|
||
return [k, Number(v)];
|
||
}));
|
||
break;
|
||
case "chatChannels":
|
||
return chatChannelsEditor(f, value);
|
||
case "mcpServers":
|
||
return mcpServersEditor(f, value);
|
||
case "collectTargets":
|
||
return collectTargetsEditor(f, value);
|
||
default:
|
||
el = h("span", { class: "muted" }, JSON.stringify(value));
|
||
read = () => value;
|
||
}
|
||
return { el: h("div", {}, el, f.hint ? h("div", { class: "hint" }, f.hint) : null), read };
|
||
}
|
||
|
||
function chatChannelsEditor(f, value) {
|
||
const flags = [["syncDiscord", "디스코드 반영", true], ["read", "읽기", true], ["send", "보내기", true], ["edit", "수정", true],
|
||
["react", "반응", true], ["delete", "삭제", false], ["pin", "고정", false]];
|
||
const body = h("tbody");
|
||
const SYNC = { applied: "반영됨", pending: "잠시 뒤 반영", failed: "반영 못 함" };
|
||
const statusCells = new Map();
|
||
const addRow = (c = {}) => {
|
||
const id = h("input", { type: "text", value: c.id ?? "", placeholder: "채널 ID", "data-k": "id" });
|
||
const name = h("input", { type: "text", value: c.name ?? "", placeholder: "이름", "data-k": "name" });
|
||
const desc = h("input", { type: "text", value: c.description ?? "", placeholder: "무엇에 쓰는 채널인지", "data-k": "description" });
|
||
// A newly registered channel starts with its Discord name and topic.
|
||
id.addEventListener("change", async () => {
|
||
const asked = id.value.trim();
|
||
if (!asked || (name.value && desc.value)) return;
|
||
try {
|
||
const info = await api("discord_channel_info", { id: asked });
|
||
if (id.value.trim() !== asked) return; // the ID changed meanwhile: this answer is for another channel
|
||
if (!name.value) name.value = info.name;
|
||
if (!desc.value) desc.value = info.topic;
|
||
} catch (e) { fail(e); }
|
||
});
|
||
const status = h("td", { class: "small muted" });
|
||
if (c.id) statusCells.set(c.id, status);
|
||
const tr = h("tr", {}, h("td", {}, id), h("td", {}, name), h("td", {}, desc),
|
||
flags.map(([k, , d]) => {
|
||
const box = h("input", { type: "checkbox", "data-k": k });
|
||
box.checked = c[k] ?? d;
|
||
return h("td", {}, box);
|
||
}),
|
||
h("td", {}, h("select", { "data-k": "answer" },
|
||
h("option", { value: "wakeWord", selected: (c.answer ?? "wakeWord") === "wakeWord" }, "호출어"),
|
||
h("option", { value: "everything", selected: c.answer === "everything" }, "모든 글"))),
|
||
status,
|
||
h("td", {}, h("button", { class: "btn", onclick: () => tr.remove() }, "삭제")));
|
||
body.append(tr);
|
||
};
|
||
(value || []).forEach(addRow);
|
||
api("channel_sync_status").then((st) => {
|
||
for (const [cid, s] of Object.entries(st)) {
|
||
const cell = statusCells.get(cid);
|
||
if (cell) { cell.textContent = SYNC[s.state] ?? s.state; cell.title = s.reason ?? ""; }
|
||
}
|
||
}).catch(() => {});
|
||
const table = h("table", {}, h("thead", {}, h("tr", {}, ["ID", "이름", "설명", ...flags.map((x) => x[1]), "대답", "디스코드", ""]
|
||
.map((t) => h("th", {}, t)))), body);
|
||
const read = () => [...body.rows].map((tr) => {
|
||
const c = {};
|
||
for (const el of tr.querySelectorAll("[data-k]")) c[el.dataset.k] = el.type === "checkbox" ? el.checked : el.value.trim();
|
||
return c;
|
||
});
|
||
return { el: h("div", {}, table, h("button", { class: "btn", onclick: () => addRow() }, "채널 추가")), read, wide: true };
|
||
}
|
||
|
||
// One card per MCP server. Environment values (API keys) are secrets: they are typed here and stored
|
||
// encrypted by the app on their own (mcp_env_set), and only "stored" or not ever comes back.
|
||
function mcpServersEditor(f, value) {
|
||
const list = h("div");
|
||
const saved = new Set((value || []).map((s) => s.name));
|
||
let status = {};
|
||
const addServer = (s = {}) => {
|
||
const name = h("input", { type: "text", value: s.name ?? "", placeholder: "이름 (영문, 숫자, - _)", "data-k": "name" });
|
||
const command = h("input", { type: "text", value: s.command ?? "", placeholder: "명령 (예: npx, uvx)", "data-k": "command" });
|
||
const args = h("textarea", { placeholder: "인자, 한 줄에 하나", "data-k": "args" }, (s.args || []).join("\n"));
|
||
const env = h("textarea", { placeholder: "환경 변수 이름, 한 줄에 하나 (예: BRAVE_API_KEY)", "data-k": "env" }, (s.env || []).join("\n"));
|
||
const enabled = h("input", { type: "checkbox", class: "switch", "data-k": "enabled" });
|
||
enabled.checked = s.enabled ?? true;
|
||
const values = h("div", { class: "small" });
|
||
const fillValues = () => {
|
||
values.replaceChildren();
|
||
if (!saved.has(s.name)) {
|
||
if ((s.env || []).length || env.value.trim()) values.append(h("div", { class: "muted" }, "환경 변수 값은 서버를 저장한 뒤 넣을 수 있습니다."));
|
||
return;
|
||
}
|
||
for (const v of s.env || []) {
|
||
const box = h("input", { type: "password", placeholder: status[s.name]?.[v] ? "저장됨 (바꾸려면 입력)" : "값 없음", autocomplete: "off" });
|
||
const put = async (val) => {
|
||
try {
|
||
const r = await api("mcp_env_set", { server: s.name, name: v, value: val });
|
||
status[s.name] = { ...(status[s.name] || {}), [v]: r.set };
|
||
box.value = "";
|
||
fillValues();
|
||
toast(r.restartNeeded ? "저장했습니다. 다시 시작하면 적용됩니다." : "저장했습니다.");
|
||
} catch (e) { fail(e); }
|
||
};
|
||
values.append(h("div", { class: "field" }, h("label", {}, v), box,
|
||
h("button", { class: "btn", onclick: () => box.value.trim() ? put(box.value) : toast("값을 입력해 주세요", true) }, "값 저장"),
|
||
status[s.name]?.[v] ? h("button", { class: "btn", onclick: () => put("") }, "값 지우기") : null));
|
||
}
|
||
};
|
||
const card = h("div", { class: "card mcp" },
|
||
h("div", { class: "field" }, h("label", {}, "이름"), name),
|
||
h("div", { class: "field" }, h("label", {}, "명령"), command),
|
||
h("div", { class: "field" }, h("label", {}, "인자"), args),
|
||
h("div", { class: "field" }, h("label", {}, "환경 변수"), env),
|
||
h("div", { class: "field" }, h("label", {}, "켜기"), enabled),
|
||
values,
|
||
h("button", { class: "btn", onclick: () => card.remove() }, "서버 삭제"));
|
||
card.fillValues = fillValues;
|
||
list.append(card);
|
||
fillValues();
|
||
};
|
||
(value || []).forEach(addServer);
|
||
api("mcp_env_status").then((st) => { status = st; for (const c of list.children) c.fillValues(); }).catch(() => {});
|
||
const lines = (t) => t.split("\n").map((x) => x.trim()).filter(Boolean);
|
||
const read = () => [...list.children].map((card) => {
|
||
const k = (key) => card.querySelector(`[data-k="${key}"]`);
|
||
return { name: k("name").value.trim(), command: k("command").value.trim(), args: lines(k("args").value),
|
||
env: lines(k("env").value), enabled: k("enabled").checked };
|
||
});
|
||
return { el: h("div", {}, h("div", { class: "hint" }, "MCP 서버는 이 PC에서 프로그램으로 실행됩니다. 믿을 수 있는 서버만 추가해 주세요."),
|
||
list, h("button", { class: "btn", onclick: () => addServer() }, "서버 추가")), read, wide: true };
|
||
}
|
||
|
||
// The background collection targets: one row each (admin.spec.md, "Background collection").
|
||
const KIND = { site: "사이트", search: "검색어", rss: "RSS" };
|
||
function collectTargetsEditor(f, value) {
|
||
const body = h("tbody");
|
||
const addRow = (t = {}) => {
|
||
const kind = h("select", { "data-k": "kind" },
|
||
Object.entries(KIND).map(([k, label]) => h("option", { value: k, selected: (t.kind ?? "site") === k }, label)));
|
||
const val = h("input", { type: "text", value: t.value ?? "", "data-k": "value" });
|
||
const hint = () => (val.placeholder = kind.value === "search" ? "검색어" : "https:// 주소");
|
||
kind.addEventListener("change", hint);
|
||
hint();
|
||
const on = h("input", { type: "checkbox", "data-k": "enabled" });
|
||
on.checked = t.enabled ?? true;
|
||
const tr = h("tr", {},
|
||
h("td", {}, h("input", { type: "text", value: t.name ?? "", placeholder: "이름 (글자, 숫자, - _)", "data-k": "name" })),
|
||
h("td", {}, kind), h("td", {}, val),
|
||
h("td", {}, h("input", { type: "number", min: 15, max: 10080, value: t.everyMinutes ?? 60, "data-k": "everyMinutes" })),
|
||
h("td", {}, on),
|
||
h("td", {}, h("button", { class: "btn", onclick: () => tr.remove() }, "삭제")));
|
||
body.append(tr);
|
||
};
|
||
(value || []).forEach(addRow);
|
||
const read = () => [...body.rows].map((tr) => {
|
||
const k = (key) => tr.querySelector(`[data-k="${key}"]`);
|
||
const every = Number(k("everyMinutes").value);
|
||
if (!Number.isInteger(every)) throw new Error(`${f.label}: 주기는 분 단위 정수`);
|
||
return { name: k("name").value.trim(), kind: k("kind").value, value: k("value").value.trim(),
|
||
everyMinutes: every, enabled: k("enabled").checked };
|
||
});
|
||
const table = h("table", {}, h("thead", {}, h("tr", {}, ["이름", "종류", "주소 또는 검색어", "주기(분)", "켜기", ""]
|
||
.map((x) => h("th", {}, x)))), body);
|
||
return { el: h("div", {}, h("div", { class: "hint" }, "기본 수집 대상은 없습니다. 모은 내용은 데이터 폴더의 collect 폴더에만 저장됩니다."),
|
||
table, h("button", { class: "btn", onclick: () => addRow() }, "대상 추가")), read, wide: true };
|
||
}
|
||
|
||
/** The newest collected items, filtered by target; web content, so shown only as plain text. */
|
||
async function collectResults() {
|
||
const pick = h("select", {}, h("option", { value: "" }, "모든 대상"));
|
||
const list = h("div");
|
||
const load = async () => {
|
||
try {
|
||
const r = await api("collect_results", { target: pick.value || null, limit: 100 });
|
||
const items = r.items;
|
||
for (const name of r.targets)
|
||
if (![...pick.options].some((o) => o.value === name)) pick.append(h("option", { value: name }, name));
|
||
list.replaceChildren(items.length ? h("table", {}, h("tbody", {}, items.map((i) => h("tr", {},
|
||
h("td", { class: "small muted" }, (i.at || "").replace("T", " ").slice(0, 16)),
|
||
h("td", { class: "small" }, i.target),
|
||
h("td", {}, h("div", {}, i.title || i.url || ""),
|
||
i.url ? h("div", { class: "small muted" }, i.url) : null,
|
||
i.text ? h("div", { class: "small" }, i.text.length > 200 ? i.text.slice(0, 200) + "…" : i.text) : null)))))
|
||
: h("div", { class: "muted" }, "아직 모은 내용이 없습니다."));
|
||
} catch (e) { fail(e); }
|
||
};
|
||
pick.addEventListener("change", load);
|
||
load();
|
||
return h("div", { class: "card" }, h("h2", {}, "수집 결과"),
|
||
h("div", { class: "field" }, h("label", {}, "대상"), pick, h("button", { class: "btn", onclick: load }, "새로 고침")), list);
|
||
}
|
||
|
||
async function settingsScreen(screen, title, extra) {
|
||
const [all, view] = await Promise.all([fields(), api("settings_view")]);
|
||
const list = all.filter((f) => f.screen === screen);
|
||
const editors = list.map((f) => ({ f, ...editor(f, view[f.path]) }));
|
||
const save = async () => {
|
||
try {
|
||
const changes = {};
|
||
for (const { f, read } of editors) {
|
||
const v = read();
|
||
if (JSON.stringify(v) !== JSON.stringify(view[f.path])) changes[f.path] = v;
|
||
}
|
||
if (!Object.keys(changes).length) return toast("바뀐 것이 없습니다");
|
||
const r = await api("settings_apply", { changes });
|
||
Object.assign(view, changes);
|
||
const sync = r.sync || [];
|
||
if (sync.length) {
|
||
const n = (k) => sync.filter((x) => x.state === k).length;
|
||
const failed = sync.filter((x) => x.state === "failed").map((x) => x.reason);
|
||
toast(`저장했습니다. 디스코드 반영: ${n("applied")}개 반영${n("pending") ? `, ${n("pending")}개 잠시 뒤 반영` : ""}`
|
||
+ (failed.length ? `, ${failed.length}개 못 함(${failed[0]})` : ""), failed.length > 0);
|
||
show(current); // Discord's form of the names, and the status column
|
||
return;
|
||
}
|
||
toast(r.restartNeeded ? "저장했습니다. 다시 시작하면 적용됩니다." : "저장했습니다.");
|
||
if (changes.mcpServers) show(current); // the saved servers' value inputs
|
||
} catch (e) { fail(e); }
|
||
};
|
||
const view_ = h("div", {}, h("h1", {}, title), extra,
|
||
editors.map(({ f, el, wide }) => wide ? h("div", { class: "card" }, h("h2", {}, f.label), el)
|
||
: h("div", { class: "field" }, h("label", { for: "f-" + f.path.replace(/\W/g, "-") }, f.label), el)),
|
||
h("div", { class: "savebar" }, h("button", { class: "btn primary", onclick: save }, "저장")));
|
||
fillPickers(view_, view);
|
||
return view_;
|
||
}
|
||
|
||
async function fillPickers(root, view) {
|
||
const g = root.querySelector('[data-picker="discord.guildId"]');
|
||
const v = root.querySelector('[data-picker="discord.voiceChannelId"]');
|
||
if (!g) return;
|
||
const opts = (sel, list, current, none) => {
|
||
sel.replaceChildren(h("option", { value: "" }, none),
|
||
...list.map((x) => h("option", { value: x.id, selected: x.id === current }, x.name)));
|
||
if (current && !list.some((x) => x.id === current)) sel.append(h("option", { value: current, selected: true }, current));
|
||
};
|
||
// `current`: the saved voice channel, kept only while its own server is shown. Another server
|
||
// starts with none chosen, so a channel of the previous server is never saved with it.
|
||
const loadVoice = async (current) => {
|
||
if (!v) return;
|
||
opts(v, [], current, "자동으로 들어가지 않음");
|
||
if (!g.value) return;
|
||
const guild = g.value;
|
||
try {
|
||
const voice = (await api("discord_channels", { guildId: guild })).voice;
|
||
if (g.value === guild) opts(v, voice, current, "자동으로 들어가지 않음");
|
||
} catch (e) { /* the saved ID stays as it was */ }
|
||
};
|
||
try { opts(g, await api("discord_guilds"), view["discord.guildId"], "선택 안 함"); } catch (e) { return; }
|
||
g.addEventListener("change", () => loadVoice(null));
|
||
loadVoice(view["discord.voiceChannelId"]);
|
||
}
|
||
|
||
async function tokenCard() {
|
||
const st = await api("token_status");
|
||
const input = h("input", { type: "password", placeholder: "새 봇 토큰", autocomplete: "off" });
|
||
const out = h("div", { class: "small muted" });
|
||
const label = h("span", {}, st.set ? st.masked : "저장된 토큰 없음");
|
||
return h("div", { class: "card" }, h("h2", {}, "봇 토큰"),
|
||
h("div", { class: "row" }, label, input,
|
||
h("button", { class: "btn", onclick: async () => {
|
||
try {
|
||
const c = await api("token_check", { token: input.value });
|
||
await api("token_save", { token: input.value });
|
||
input.value = "";
|
||
label.textContent = (await api("token_status")).masked;
|
||
out.textContent = `${c.botTag} 저장함. Message Content 권한: ${c.messageContent ? "켜짐" : "꺼짐"}`;
|
||
} catch (e) { fail(e); }
|
||
} }, "확인 후 저장")), out);
|
||
}
|
||
|
||
// ---- dashboard ----------------------------------------------------------------------------------
|
||
|
||
/** The header with the start/stop buttons; rebuilt only when the state changes, so a click is not
|
||
* lost to the once-a-second refresh of the cards. */
|
||
function dashboardHeader(d) {
|
||
const [label, cls] = STATE[d.state] ?? [d.state, ""];
|
||
const act = (cmd, text, primary) => h("button", { class: "btn" + (primary ? " primary" : ""), onclick: async (e) => {
|
||
e.target.disabled = true;
|
||
try { await api(cmd); } catch (err) { fail(err); }
|
||
refresh();
|
||
} }, text);
|
||
return h("div", {},
|
||
h("div", { class: "row", style: "justify-content:space-between;margin-bottom:16px" },
|
||
h("h1", { style: "margin:0" }, "대시보드"),
|
||
h("div", { class: "row" }, h("span", { class: "badge " + cls }, label),
|
||
d.state === "running" ? [act("service_restart", "다시 시작"), act("service_stop", "정지")]
|
||
: d.state === "starting" ? act("service_stop", "정지")
|
||
: act("service_start", "시작", true))),
|
||
d.error ? h("div", { class: "card", style: "border-color:var(--bad);margin-bottom:12px" }, d.error) : null);
|
||
}
|
||
|
||
const LLM = { off: "꺼짐", starting: "준비 중", ready: "준비", failed: "실패" };
|
||
|
||
function dashboardBody(d) {
|
||
const med = d.latency?.median ?? {};
|
||
const s = (ms) => (ms == null ? "–" : (ms / 1000).toFixed(2) + "초");
|
||
const w = d.worker;
|
||
const llm = d.llm;
|
||
const pct = llm?.percent != null ? ` ${llm.percent}%` : "";
|
||
return h("div", {},
|
||
llm?.state === "starting" ? h("div", { class: "card", style: "margin-bottom:12px" },
|
||
h("h2", {}, "대화 모델 준비 중" + pct),
|
||
h("div", { class: "small muted" }, llm.managed
|
||
? "처음 시작할 때는 대화 모델(약 23GB)을 받느라 오래 걸릴 수 있습니다. 그동안 정지할 수 있습니다."
|
||
: "설정한 대화 모델 서버의 응답을 기다리고 있습니다."),
|
||
llm.note ? h("div", { class: "small", style: "margin-top:6px;word-break:break-all" }, llm.note) : null) : null,
|
||
h("div", { class: "grid" },
|
||
h("div", { class: "card" }, h("h2", {}, "연결"), h("div", { class: "kv" },
|
||
h("span", { class: "k" }, "디스코드"), h("span", {}, d.discord ?? "연결 안 됨"),
|
||
h("span", { class: "k" }, "음성 워커"), h("span", {}, w ? (w.connected ? "연결됨" : "연결 안 됨") : "–"),
|
||
h("span", { class: "k" }, "STT / TTS"), h("span", {}, w ? `${w.sttReady ? "준비" : "–"} / ${w.ttsReady ? "준비" : "–"}` : "–"),
|
||
h("span", { class: "k" }, "워커 재시작"), h("span", {}, w?.restarts ?? "–"),
|
||
h("span", { class: "k" }, "대화 모델"), h("span", {}, llm ? (LLM[llm.state] ?? llm.state) : "–"),
|
||
h("span", { class: "k" }, "봇용 크롬"), h("span", { title: d.browser?.note ?? "" },
|
||
(BROWSER[d.browser?.state] ?? "–") + (d.browser?.note ? ` (${d.browser.note})` : "")))),
|
||
h("div", { class: "card" }, h("h2", {}, "음성 채널"),
|
||
h("div", {}, d.voiceChannel ? `채널 ${d.voiceChannel}` : "들어가 있지 않음"),
|
||
h("div", { class: "small muted", style: "margin-top:6px" },
|
||
(d.voiceMembers || []).map((m) => m.name).join(", ") || "참가자 없음")),
|
||
h("div", { class: "card" }, h("h2", {}, "응답 시간 (중앙값)"), h("div", { class: "kv" },
|
||
h("span", { class: "k" }, "말 끝 → 받아 적기"), h("span", {}, s(med.finalMs)),
|
||
h("span", { class: "k" }, "두뇌"), h("span", {}, s(med.brainMs)),
|
||
h("span", { class: "k" }, "목소리"), h("span", {}, s(med.voiceMs)),
|
||
h("span", { class: "k" }, "전체"), h("span", {}, s(med.totalMs)))),
|
||
h("div", { class: "card" }, h("h2", {}, "시스템"), h("div", { class: "kv" },
|
||
h("span", { class: "k" }, "RAM"), h("span", {}, d.system?.ramTotalMb ? `${(d.system.ramUsedMb / 1024).toFixed(1)} / ${(d.system.ramTotalMb / 1024).toFixed(1)} GB` : "–"),
|
||
(d.system?.gpus || []).flatMap((g) => [h("span", { class: "k" }, g.name.replace("NVIDIA GeForce ", "")),
|
||
h("span", {}, `${g.usePercent}% · VRAM ${(g.vramUsedMb / 1024).toFixed(1)} / ${(g.vramTotalMb / 1024).toFixed(1)} GB`)]),
|
||
h("span", { class: "k" }, "성능 단계"), h("span", { class: "muted" }, d.performance ?? "평소")))),
|
||
h("div", { class: "grid" },
|
||
h("div", { class: "card" }, h("h2", {}, "실시간 자막"), h("div", { class: "captions" },
|
||
(d.captions || []).length ? d.captions.map((c) => h("div", { class: "cap" + (c.final ? "" : " partial") }, h("b", {}, c.name), c.text))
|
||
: h("div", { class: "muted" }, "아직 없음"))),
|
||
h("div", { class: "card" }, h("h2", {}, "놓친 요청"), (d.missed || []).length
|
||
? h("table", {}, h("tbody", {}, d.missed.map((m) => h("tr", {}, h("td", {}, m.speaker),
|
||
h("td", {}, REASON[m.reason] ?? m.reason), h("td", { class: "muted" }, `${m.secondsAgo}초 전`)))))
|
||
: h("div", { class: "muted" }, "없음"))));
|
||
}
|
||
|
||
// ---- logs ---------------------------------------------------------------------------------------
|
||
|
||
const TABS = { all: "전체", app: "앱", discord: "디스코드", chat: "채팅", conversation: "대화", worker: "워커",
|
||
stt: "STT", llm: "LLM", tts: "TTS", browser: "브라우저", capture: "화면 캡처", game: "게임 감지" };
|
||
function logsScreen() {
|
||
const tab = h("select", {}, Object.entries(TABS).map(([v, t]) => h("option", { value: v }, t)));
|
||
const level = h("select", {}, [["debug", "디버그 이상"], ["info", "정보 이상"], ["warn", "경고 이상"], ["error", "오류만"]]
|
||
.map(([v, t]) => h("option", { value: v }, t)));
|
||
const find = h("input", { type: "text", placeholder: "찾기", style: "max-width:220px" });
|
||
const pause = h("input", { type: "checkbox", class: "switch" });
|
||
const box = h("div", { class: "logs" });
|
||
let last = null;
|
||
const reload = () => { box.textContent = ""; last = null; poll(); };
|
||
async function poll() {
|
||
if (pause.checked) return;
|
||
try {
|
||
const lines = await api("logs_query", { tab: tab.value, level: level.value, find: find.value, after: last, limit: 500 });
|
||
const stick = box.scrollTop + box.clientHeight >= box.scrollHeight - 20;
|
||
for (const l of lines) {
|
||
const d = new Date(l.at_ms), p2 = (n) => String(n).padStart(2, "0");
|
||
const t = `${p2(d.getHours())}:${p2(d.getMinutes())}:${p2(d.getSeconds())}`;
|
||
box.append(h("div", { class: "log " + l.level }, `${t} ${l.level.toUpperCase().padEnd(5)} [${l.tab}] ${l.text}`));
|
||
last = l.seq;
|
||
}
|
||
while (box.childElementCount > 5000) box.firstChild.remove();
|
||
if (stick) box.scrollTop = box.scrollHeight;
|
||
} catch (e) { /* the next tick tries again */ }
|
||
}
|
||
for (const el of [tab, level]) el.addEventListener("change", reload);
|
||
find.addEventListener("input", () => { clearTimeout(find.t); find.t = setTimeout(reload, 300); });
|
||
const today = new Date().toISOString().slice(0, 10);
|
||
const from = h("input", { type: "date", value: today }), to = h("input", { type: "date", value: today });
|
||
const view = h("div", {}, h("h1", {}, "로그"),
|
||
h("div", { class: "row", style: "margin-bottom:10px" }, tab, level, find, h("label", { class: "row small muted" }, pause, "일시정지"),
|
||
h("button", { class: "btn", onclick: async () => {
|
||
try {
|
||
const r = await api("logs_error_report");
|
||
if (!r.report) return toast("기록된 오류가 없습니다");
|
||
await navigator.clipboard.writeText(r.report);
|
||
toast(r.tooLongForDiscord ? "복사했습니다. 디스코드 메시지 한도(2,000자)를 넘으니 파일로 내보내세요." : "최근 오류를 복사했습니다.");
|
||
} catch (e) { fail(e); }
|
||
} }, "최근 오류 복사")),
|
||
box,
|
||
h("div", { class: "row", style: "margin-top:10px" }, h("span", { class: "muted" }, "내보내기"), from, "~", to,
|
||
h("button", { class: "btn", onclick: async () => {
|
||
try {
|
||
const r = await api("logs_export", { from: from.value, to: to.value });
|
||
toast(`${r.path}에 저장했습니다${r.droppedLines ? ` (10MB를 넘어 오래된 ${r.droppedLines}줄은 뺐습니다)` : ""}`);
|
||
} catch (e) { fail(e); }
|
||
} }, "zip으로 저장")));
|
||
reload();
|
||
return { view, tick: poll };
|
||
}
|
||
|
||
// ---- navigation ---------------------------------------------------------------------------------
|
||
|
||
let current = null, ticker = null;
|
||
let headerKey = null;
|
||
// Each show() starts a new generation: an answer that arrives after the user moved on is dropped.
|
||
let gen = 0;
|
||
async function refresh() {
|
||
if (current !== "dashboard") return;
|
||
const my = gen;
|
||
try {
|
||
const d = await api("dashboard");
|
||
if (my !== gen || current !== "dashboard") return;
|
||
const screen = $("#screen");
|
||
let head = $("#dash-head"), body = $("#dash-body");
|
||
if (!head || !body) {
|
||
head = h("div", { id: "dash-head" }); body = h("div", { id: "dash-body" });
|
||
screen.replaceChildren(head, body);
|
||
headerKey = null;
|
||
}
|
||
const key = d.state + "|" + (d.error ?? "");
|
||
if (key !== headerKey) { head.replaceChildren(dashboardHeader(d)); headerKey = key; }
|
||
body.replaceChildren(dashboardBody(d));
|
||
} catch (e) { fail(e); }
|
||
}
|
||
async function show(name) {
|
||
const my = ++gen;
|
||
current = name;
|
||
clearInterval(ticker);
|
||
for (const b of document.querySelectorAll(".nav")) b.classList.toggle("on", b.dataset.screen === name);
|
||
const screen = $("#screen");
|
||
try {
|
||
if (name === "dashboard") { screen.replaceChildren(); await refresh(); ticker = setInterval(refresh, 1000); return; }
|
||
if (name === "logs") { const l = logsScreen(); screen.replaceChildren(l.view); ticker = setInterval(l.tick, 1000); return; }
|
||
const titles = { bot: "봇", channels: "채널·호출", chat: "채팅 채널", memory: "대화 기억", model: "모델", features: "기능",
|
||
collect: "백그라운드 수집" };
|
||
const extra = name === "bot" ? await tokenCard() : null;
|
||
const view = await settingsScreen(name, titles[name], extra);
|
||
if (name === "collect") view.append(await collectResults());
|
||
if (my === gen) screen.replaceChildren(view);
|
||
} catch (e) { fail(e); }
|
||
}
|
||
|
||
// ---- first-run wizard ---------------------------------------------------------------------------
|
||
|
||
const WIZ = ["데이터 폴더", "PC 점검", "모델", "디스코드 봇", "서버·채널", "호출어", "완료"];
|
||
async function wizard(status) {
|
||
const root = $("#wizard");
|
||
// Resume where it was left: the step saved in the data folder (setup.json), not just "token stored".
|
||
let step = status.dataDir ? Math.max(1, Math.min(status.wizardStep || 1, WIZ.length - 1)) : 0;
|
||
let wgen = 0;
|
||
const s = {};
|
||
const nav = (back, next, nextLabel = "다음") => h("div", { class: "nav-row" },
|
||
back ? h("button", { class: "btn", onclick: () => go(step - 1) }, "이전") : h("span"),
|
||
next ? h("button", { class: "btn primary", onclick: next }, nextLabel) : h("span"));
|
||
async function go(n) {
|
||
step = n;
|
||
const my = ++wgen;
|
||
if (n >= 1) api("wizard_step", { step: n }).catch(() => {});
|
||
const card = h("div", { class: "card" });
|
||
root.replaceChildren(h("h1", {}, "Jarvis 처음 설정"),
|
||
h("div", { class: "steps" }, WIZ.map((t, i) => h("span", { class: "step" + (i === step ? " on" : i < step ? " done" : "") }, t))), card);
|
||
try {
|
||
const kids = await STEPS[n](card);
|
||
if (my === wgen) card.append(...kids.filter((x) => x != null));
|
||
} catch (e) { fail(e); }
|
||
}
|
||
const STEPS = [
|
||
async () => {
|
||
const path = h("input", { type: "text", placeholder: "예: D:\\JarvisBot", value: s.path ?? "" });
|
||
const info = h("p", { class: "small" });
|
||
return [h("h2", {}, "데이터를 둘 폴더"),
|
||
h("p", {}, "모델, 대화 기록, 로그가 모두 이 폴더 안에 저장됩니다. 남은 용량은 200GB 이상을 권장합니다."),
|
||
h("div", { class: "row" }, path, h("button", { class: "btn", onclick: async () => {
|
||
try {
|
||
const c = await api("folder_check", { path: path.value });
|
||
info.textContent = `남은 용량 ${gb(c.freeBytes)}` + (c.enough ? "" : ` · 권장 ${gb(c.recommendedBytes)}보다 적습니다`);
|
||
info.style.color = c.enough ? "" : "var(--warn)";
|
||
} catch (e) { fail(e); }
|
||
} }, "용량 확인")), info,
|
||
nav(false, async () => {
|
||
try { await api("folder_choose", { path: path.value }); s.path = path.value; go(1); } catch (e) { fail(e); }
|
||
}, "이 폴더 사용")];
|
||
},
|
||
async () => {
|
||
const p = await api("pc_check");
|
||
const g = p.gpus[0];
|
||
return [h("h2", {}, "PC 점검"), h("div", { class: "kv" },
|
||
h("span", { class: "k" }, "GPU"), h("span", {}, g ? `${g.name} (VRAM ${(g.vramTotalMb / 1024).toFixed(0)} GB)` : "NVIDIA GPU를 찾지 못했습니다"),
|
||
h("span", { class: "k" }, "드라이버"), h("span", {}, p.driver ? `${p.driver} ` : "–",
|
||
p.driver ? h("span", { class: "badge " + (p.driverOk ? "ok" : "bad") }, p.driverOk ? "정상" : `${p.minDriver} 이상 필요`) : null),
|
||
h("span", { class: "k" }, "RAM"), h("span", {}, p.ramTotalMb ? `${(p.ramTotalMb / 1024).toFixed(0)} GB` : "–"),
|
||
h("span", { class: "k" }, "CPU"), h("span", {}, `${p.cpuThreads ?? "–"} 스레드`),
|
||
h("span", { class: "k" }, "디스크 남은 용량"), h("span", {}, p.diskFreeBytes != null ? gb(p.diskFreeBytes) : "–")),
|
||
p.driver && !p.driverOk ? h("p", {}, "NVIDIA 드라이버를 최신으로 올려 주세요: ", h("a", { href: "https://www.nvidia.com/drivers", target: "_blank" }, "nvidia.com/drivers")) : null,
|
||
nav(true, () => go(2))];
|
||
},
|
||
async () => {
|
||
// The install runs in the app; this step shows it and polls while it is on screen.
|
||
const list = h("table");
|
||
const btn = h("button", { class: "btn" });
|
||
const next = nav(true, () => go(3));
|
||
const nextBtn = next.lastChild;
|
||
const SIZE = (b) => (b >= 1e9 ? (b / 1e9).toFixed(1) + " GB" : (b / 1e6).toFixed(0) + " MB");
|
||
const STEP = { pending: ["대기", ""], running: ["설치 중", "warn"], done: ["완료", "ok"], failed: ["실패", "bad"] };
|
||
const my = wgen;
|
||
async function poll() {
|
||
if (my !== wgen) return;
|
||
let st;
|
||
try { st = await api("install_status"); } catch (e) { return fail(e); }
|
||
if (my !== wgen) return;
|
||
list.replaceChildren(h("tbody", {}, st.steps.map((x) => {
|
||
const [label, cls] = STEP[x.state] ?? [x.state, ""];
|
||
const bytes = x.bytes && x.state === "running" ? ` ${SIZE(x.bytes[0])}${x.bytes[1] ? " / " + SIZE(x.bytes[1]) : ""}` : "";
|
||
return h("tr", {}, h("td", {}, x.label, h("div", { class: "small muted" }, x.sizeHint)),
|
||
h("td", {}, h("span", { class: "badge " + cls }, label + bytes)),
|
||
h("td", { class: "small muted", style: "max-width:320px;word-break:break-all" }, x.state === "done" ? "" : (x.note ?? "")));
|
||
})));
|
||
btn.textContent = st.running ? "취소" : st.done ? "설치됨" : st.steps.some((x) => x.state === "failed") ? "다시 시도" : "설치 시작";
|
||
btn.disabled = st.done && !st.running;
|
||
btn.onclick = async () => {
|
||
try { await api(st.running ? "install_cancel" : "install_start"); } catch (e) { fail(e); }
|
||
poll();
|
||
};
|
||
nextBtn.disabled = !st.done;
|
||
if (st.running) setTimeout(poll, 1000);
|
||
}
|
||
poll();
|
||
return [h("h2", {}, "런타임과 모델 설치"),
|
||
h("p", {}, "음성 워커와 두뇌를 돌릴 Python 환경, 받아 적기(Whisper)·음성(MeloTTS) 모델, LLM 엔진(Strata), 봇용 크롬을 데이터 폴더 안에 받습니다. 끊겨도 다음에 이어서 받습니다. 대화 모델 Qwen3.6-35B-A3B(약 23GB)는 Strata를 처음 켤 때 받습니다."),
|
||
list, h("div", { class: "row", style: "margin-top:12px" }, btn), next];
|
||
},
|
||
async () => {
|
||
const input = h("input", { type: "password", placeholder: "디스코드 봇 토큰", autocomplete: "off" });
|
||
const out = h("div");
|
||
const stored = await api("token_status");
|
||
return [h("h2", {}, "디스코드 봇 연결"),
|
||
stored.set ? h("p", { class: "small" }, `저장된 토큰 ${stored.masked}가 있습니다. 바꾸려면 새 토큰을 확인하세요.`) : null,
|
||
h("p", {}, "Discord Developer Portal의 Bot 탭에서 토큰을 복사해 붙여 넣으세요. 토큰은 이 PC의 Windows 계정으로 암호화해 저장합니다."),
|
||
h("div", { class: "row" }, input, h("button", { class: "btn", onclick: async () => {
|
||
try {
|
||
const c = await api("token_check", { token: input.value });
|
||
s.token = input.value; s.check = c;
|
||
out.replaceChildren(h("div", { class: "kv", style: "margin-top:12px" },
|
||
h("span", { class: "k" }, "봇"), h("span", {}, c.botTag),
|
||
h("span", { class: "k" }, "Message Content"), h("span", {}, h("span", { class: "badge " + (c.messageContent ? "ok" : "bad") },
|
||
c.messageContent ? "켜짐" : "꺼짐: Developer Portal > Bot > Message Content Intent를 켜 주세요")),
|
||
h("span", { class: "k" }, "초대 링크"), h("a", { href: c.inviteUrl, target: "_blank" }, "서버에 봇 초대하기")));
|
||
} catch (e) { fail(e); }
|
||
} }, "연결 확인")), out,
|
||
nav(true, async () => {
|
||
if (!s.check) return stored.set ? go(4) : toast("먼저 연결을 확인해 주세요", true);
|
||
try { await api("token_save", { token: s.token }); go(4); } catch (e) { fail(e); }
|
||
})];
|
||
},
|
||
async () => {
|
||
const guilds = await api("discord_guilds");
|
||
const g = h("select", {}, h("option", { value: "" }, "서버 선택"), guilds.map((x) => h("option", { value: x.id }, x.name)));
|
||
const v = h("select", {}, h("option", { value: "" }, "자동으로 들어가지 않음"));
|
||
g.addEventListener("change", async () => {
|
||
v.replaceChildren(h("option", { value: "" }, "자동으로 들어가지 않음"));
|
||
if (!g.value) return;
|
||
try {
|
||
const ch = await api("discord_channels", { guildId: g.value });
|
||
v.append(...ch.voice.map((x) => h("option", { value: x.id }, x.name)));
|
||
} catch (e) { fail(e); }
|
||
});
|
||
return [h("h2", {}, "서버와 음성 채널"),
|
||
guilds.length ? null : h("p", {}, "봇이 들어가 있는 서버가 없습니다. 이전 단계의 초대 링크로 먼저 초대해 주세요."),
|
||
h("div", { class: "field" }, h("label", {}, "서버"), g),
|
||
h("div", { class: "field" }, h("label", {}, "자동으로 들어갈 음성 채널"), v),
|
||
h("p", { class: "small muted" }, "AI 채팅 채널은 나중에 \"채팅 채널\" 화면에서 등록할 수 있습니다."),
|
||
nav(true, async () => {
|
||
if (!g.value) return toast("서버를 골라 주세요", true);
|
||
try { await api("settings_apply", { changes: { "discord.guildId": g.value, "discord.voiceChannelId": v.value || null } }); go(5); }
|
||
catch (e) { fail(e); }
|
||
})];
|
||
},
|
||
async () => {
|
||
const view = await api("settings_view");
|
||
const words = h("textarea", {}, (view["voice.wakeWords"] || []).join("\n"));
|
||
return [h("h2", {}, "호출어"), h("p", {}, "이 말로 부르면 대답합니다. 한 줄에 하나씩 적어 주세요."), words,
|
||
nav(true, async () => {
|
||
const list = words.value.split("\n").map((x) => x.trim()).filter(Boolean);
|
||
if (!list.length) return toast("호출어를 하나 이상 적어 주세요", true);
|
||
try { await api("settings_apply", { changes: { "voice.wakeWords": list } }); go(6); } catch (e) { fail(e); }
|
||
})];
|
||
},
|
||
async () => [h("h2", {}, "준비됐습니다"),
|
||
h("p", {}, "시작하면 대화 모델을 켜고 봇이 디스코드에 연결되며, 처음 시작할 때 서버에 슬래시 명령을 등록합니다. 처음에는 대화 모델(약 23GB)을 받아서 오래 걸립니다. 진행 상황은 대시보드에 나옵니다."),
|
||
nav(true, async () => {
|
||
try { await api("wizard_finish"); } catch (e) { return fail(e); }
|
||
root.hidden = true;
|
||
await start();
|
||
try { await api("service_start"); } catch (e) { fail(e); }
|
||
refresh();
|
||
}, "시작")],
|
||
];
|
||
root.hidden = false;
|
||
$("#main").hidden = true;
|
||
go(step);
|
||
}
|
||
|
||
async function start() {
|
||
const status = await api("app_status");
|
||
$("#version").textContent = "v" + status.version;
|
||
if (status.firstRun && !start.done) { start.done = true; return wizard(status); }
|
||
$("#wizard").hidden = true;
|
||
$("#main").hidden = false;
|
||
for (const b of document.querySelectorAll(".nav")) b.onclick = () => show(b.dataset.screen);
|
||
show("dashboard");
|
||
}
|
||
// The window tells what closing does: stopping what runs first, or that it could not.
|
||
if (window.__TAURI__?.event) {
|
||
window.__TAURI__.event.listen("closing", () => toast("실행 중인 것을 정리하고 종료합니다…"));
|
||
window.__TAURI__.event.listen("close-failed", (e) =>
|
||
toast(`정리를 끝내지 못해 창을 닫지 않았습니다: ${e.payload}. 한 번 더 닫으면 그대로 종료합니다.`, true));
|
||
}
|
||
start().catch(fail);
|