Files
javis_bot/app/ui/app.js
javis-bot a4436698c8 feat(app): M5 step 4a, install the runtime and voice models into the data folder
- download: resumed downloads checked against a pinned SHA-256.
- install: uv 0.11.20, the worker/brain venv (Python 3.12, the new
  src/voice_worker/requirements-brain.txt), the MeloTTS venv (Python 3.11,
  PyTorch cu128), Whisper large-v3-turbo, the Korean MeloTTS voice and
  Strata, the M0 kit's recipe; markers per step and version, cancel, retry,
  everything (caches, temp, HF and NLTK data) inside the data folder, the uv
  cache cleaned and the worker settings pointed at the venvs when done.
- The services give the worker the same environment once installed.
- The wizard's model step shows and drives the install.

Installed from an empty folder on Linux and started the services on it:
worker connected, STT and TTS ready, nothing written outside the folder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 17:11:23 +09:00

548 lines
30 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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 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);
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 = [["read", "읽기", true], ["send", "보내기", true], ["edit", "수정", true], ["react", "반응", true],
["delete", "삭제", false], ["pin", "고정", false]];
const body = h("tbody");
const addRow = (c = {}) => {
const tr = h("tr", {},
h("td", {}, h("input", { type: "text", value: c.id ?? "", placeholder: "채널 ID", "data-k": "id" })),
h("td", {}, h("input", { type: "text", value: c.name ?? "", placeholder: "이름", "data-k": "name" })),
h("td", {}, h("input", { type: "text", value: c.description ?? "", placeholder: "무엇에 쓰는 채널인지", "data-k": "description" })),
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" }, "모든 글"))),
h("td", {}, h("button", { class: "btn", onclick: () => tr.remove() }, "삭제")));
body.append(tr);
};
(value || []).forEach(addRow);
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 };
}
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);
toast(r.restartNeeded ? "저장했습니다. 다시 시작하면 적용됩니다." : "저장했습니다.");
} 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" });
return h("div", { class: "card" }, h("h2", {}, "봇 토큰"),
h("div", { class: "row" }, h("span", {}, st.set ? st.masked : "저장된 토큰 없음"), 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 = "";
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", "정지")]
: act("service_start", "시작", true))),
d.error ? h("div", { class: "card", style: "border-color:var(--bad);margin-bottom:12px" }, d.error) : null);
}
function dashboardBody(d) {
const med = d.latency?.median ?? {};
const s = (ms) => (ms == null ? "–" : (ms / 1000).toFixed(2) + "초");
const w = d.worker;
return h("div", {},
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("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: "모델" };
const extra = name === "bot" ? await tokenCard() : null;
const view = await settingsScreen(name, titles[name], extra);
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", {}, "시작하면 봇이 디스코드에 연결되고, 처음 시작할 때 서버에 슬래시 명령을 등록합니다."),
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");
}
start().catch(fail);