diff --git a/app/src/admin.spec.md b/app/src/admin.spec.md index e068a48..8f393fe 100644 --- a/app/src/admin.spec.md +++ b/app/src/admin.spec.md @@ -135,7 +135,8 @@ back as Korean messages for the screen. The Tauri shell passes the screens' `inv | Command | Does | |---|---| -| `app_status` | version, data folder, whether a token is stored; `firstRun` while either is missing | +| `app_status` | version, data folder, whether a token is stored, `wizardStep`; `firstRun` until the wizard's last step was reached (a stored token alone does not finish it) | +| `wizard_step` `{step}` / `wizard_finish` | remember the wizard step reached / mark it done (needs a stored token); both in `config/setup.json` | | `folder_check` `{path}` / `folder_choose` `{path}` | free space against the recommendation / create the folder and remember it | | `pc_check` | OS, CPU threads, RAM, NVIDIA GPUs, the driver version and whether it is 580 or newer, free disk | | `token_check` `{token}` | the bot's tag and IDs, whether the Message Content intent is on, the invite link (REST only, nothing stored) | @@ -147,8 +148,8 @@ back as Korean messages for the screen. The Tauri shell passes the screens' `inv The invite link asks for: view channels, send messages, read history, add reactions, manage messages, manage channels, connect, speak, voice activity, and the slash command scope; never -administrator. The log hub writes to the data folder's `logs/` from the first start after a -folder is chosen (before that, memory only). +administrator. The log hub writes to the data folder's `logs/` as soon as a folder is chosen +(`folder_choose` points it there; before that, memory only). ## Screens (`app/ui/`) @@ -157,11 +158,15 @@ Plain HTML, CSS and an ES module, no build step, dark theme after `DESIGN.md`. A - **First-run wizard** (while `firstRun`): data folder (free space, warning under 200 GB), PC check, the model to download (the download itself is step 4 of M5), Discord bot (token check with the Message Content state and the invite link, then save), server and auto-join voice channel - pickers, wake words, then start. It resumes at the bot step when a folder is already chosen. + pickers, wake words, then start. Each step reached is saved, so a reload or a restart resumes at + that step; only the last step's start finishes it. A stored token lets the bot step go on + without entering it again. - **Dashboard**: the snapshot every second; the header with start, restart and stop is rebuilt - only when the state changes, so a click is never lost to the refresh. + only when the state changes, so a click is never lost to the refresh. Every screen change starts + a new generation: an answer that arrives after the user moved to another screen is dropped. - **Settings screens** (봇, 채널·호출, 채팅 채널, 대화 기억, 모델): built from `settings_fields`; only - changed fields are sent; the server and voice channel are pickers; the chat channels are a table + changed fields are sent; the server and voice channel are pickers (choosing another server clears + the voice channel and lists only that server's channels); the chat channels are a table with their switches; the bot screen also changes the token. - **Logs**: tab, level and text filters, pause, live follow (lines after the last seen), "최근 오류 복사" (to the clipboard; over 2,000 characters it suggests the zip), and the zip export by days. @@ -180,7 +185,8 @@ categories, query filters and follow, files per day and retention, error report cap, redaction of stored secrets and token-shaped text; the controller's state rules with a fake service starter; the dashboard from made-up events (captions replaced and cleared, latency stages and medians, an answer matched to its asker's final, missed requests without text); the admin -commands (first run: folder then token, the token never returned whole, settings and logs through +commands (first run: folder then token, the token never returned whole, the wizard resumed at its +step until finished, log files and the zip from the folder choice on, settings and logs through their modules, the dashboard before anything runs), the invite link's permissions and the Message Content flags. The screens are checked in a browser against the development server with the real services (wizard, dashboard start, restart and stop, settings save, chat channels, logs, export). Windows-only paths (DPAPI, `%APPDATA%`) are diff --git a/app/src/admin_api.rs b/app/src/admin_api.rs index 844ff76..322c69c 100644 --- a/app/src/admin_api.rs +++ b/app/src/admin_api.rs @@ -60,6 +60,19 @@ impl AdminApi { .ok_or_else(|| "봇 토큰을 먼저 저장해 주세요".into()) } + /// The wizard's progress, `config/setup.json`: `{step, done}`. + fn setup(&self, dir: &DataDir) -> Value { + std::fs::read_to_string(dir.config().join("setup.json")).ok() + .and_then(|t| serde_json::from_str::(&t).ok()) + .filter(Value::is_object) + .unwrap_or_else(|| json!({"step": 1, "done": false})) + } + + fn save_setup(&self, dir: &DataDir, v: &Value) -> Result<(), String> { + crate::datadir::write_atomic(&dir.config().join("setup.json"), v.to_string().as_bytes()) + .map_err(|e| format!("설정 진행 상황을 저장하지 못했습니다: {e}")) + } + fn controller(&self) -> Result, String> { let dir = self.dir()?; let mut c = self.controller.lock().unwrap(); @@ -72,8 +85,31 @@ impl AdminApi { "app_status" => { let dir = self.dir.lock().unwrap().clone(); let token = dir.as_ref().and_then(|d| Secrets::new(&d.secrets_file()).get(DISCORD_TOKEN).ok().flatten()); + // The wizard is done only when its last step was reached, not when a token exists. + let setup = dir.as_ref().map(|d| self.setup(d)); + let done = setup.as_ref().is_some_and(|s| s["done"] == json!(true)); Ok(json!({"version": APP_VERSION, "dataDir": dir.as_ref().map(|d| d.path().to_string_lossy()), - "tokenSet": token.is_some(), "firstRun": dir.is_none() || token.is_none()})) + "tokenSet": token.is_some(), "firstRun": !done, + "wizardStep": setup.as_ref().and_then(|s| s["step"].as_u64()).unwrap_or(0)})) + } + "wizard_step" => { + let dir = self.dir()?; + let step = arg(&args, "step")?.as_u64().ok_or("step은 숫자여야 합니다")?; + let mut s = self.setup(&dir); + s["step"] = json!(step); + self.save_setup(&dir, &s)?; + Ok(s) + } + "wizard_finish" => { + let dir = self.dir()?; + if self.secrets()?.get(DISCORD_TOKEN).map_err(|e| e.to_string())?.is_none() { + return Err("봇 토큰을 먼저 저장해 주세요".into()); + } + let mut s = self.setup(&dir); + s["done"] = json!(true); + self.save_setup(&dir, &s)?; + crate::info_log!("admin", "first-run setup finished"); + Ok(s) } "folder_check" => { let path = PathBuf::from(arg_str(&args, "path")?); @@ -87,6 +123,8 @@ impl AdminApi { "folder_choose" => { let path = PathBuf::from(arg_str(&args, "path")?); let dir = DataDir::choose(&path, &self.location_file).map_err(|e| e.to_string())?; + // Log files go to the chosen folder from now on, not only after a restart. + self.hub.set_dir(&dir.logs()); *self.dir.lock().unwrap() = Some(dir); *self.controller.lock().unwrap() = None; crate::info_log!("admin", "data folder chosen"); @@ -182,13 +220,27 @@ mod tests { let data = base.join("data"); let check = a.call("folder_check", json!({"path": data.to_string_lossy()})).await.unwrap(); assert!(check["freeBytes"].as_u64().unwrap() > 0 && check["exists"] == json!(false)); + a.hub.push(Level::Info, "app", "before the folder"); a.call("folder_choose", json!({"path": data.to_string_lossy()})).await.unwrap(); assert!(data.join("config").is_dir()); + // From the choice on, lines go to the folder's log files and the zip export works. + a.hub.push(Level::Info, "app", "after the folder"); + let today = chrono::Local::now().date_naive().to_string(); + let logs = std::fs::read_to_string(data.join("logs").join(format!("app-{today}.log"))).unwrap(); + assert!(logs.contains("after the folder")); + let zip = a.call("logs_export", json!({"from": today, "to": today})).await.unwrap(); + assert!(std::path::Path::new(zip["path"].as_str().unwrap()).exists()); assert_eq!(a.call("app_status", json!({})).await.unwrap()["firstRun"], json!(true), "no token yet"); + assert!(a.call("wizard_finish", json!({})).await.is_err(), "not without a token"); let saved = a.call("token_save", json!({"token": "abc.def.ghijkl"})).await.unwrap(); assert_eq!(saved["masked"], json!("••••ijkl")); + a.call("wizard_step", json!({"step": 4})).await.unwrap(); + // A stored token does not finish the wizard: it resumes at the step it reached. let s = a.call("app_status", json!({})).await.unwrap(); - assert_eq!((s["firstRun"].clone(), s["tokenSet"].clone()), (json!(false), json!(true))); + assert_eq!((s["firstRun"].clone(), s["tokenSet"].clone(), s["wizardStep"].clone()), + (json!(true), json!(true), json!(4))); + a.call("wizard_finish", json!({})).await.unwrap(); + assert_eq!(a.call("app_status", json!({})).await.unwrap()["firstRun"], json!(false)); // The token never comes back whole. assert_eq!(a.call("token_status", json!({})).await.unwrap(), json!({"set": true, "masked": "••••ijkl"})); } diff --git a/app/src/logs.rs b/app/src/logs.rs index e1e0567..f4e6ac7 100644 --- a/app/src/logs.rs +++ b/app/src/logs.rs @@ -58,6 +58,8 @@ pub fn tab_of(category: &str) -> &'static str { #[derive(Default)] struct State { + /// Where the daily files go; None: memory only (no data folder yet). + dir: Option, lines: VecDeque, next_seq: u64, files: HashMap<(String, NaiveDate), std::fs::File>, @@ -66,18 +68,28 @@ struct State { } pub struct LogHub { - dir: Option, state: Mutex, } impl LogHub { /// A hub writing daily files to `dir` (None: memory only). pub fn new(dir: Option<&Path>) -> Arc { - let hub = Arc::new(Self { dir: dir.map(Path::to_path_buf), state: Mutex::default() }); + let hub = Arc::new(Self { state: Mutex::new(State { dir: dir.map(Path::to_path_buf), ..State::default() }) }); hub.cleanup(Local::now().date_naive()); hub } + /// Start writing daily files to `dir` (the data folder was just chosen); lines kept in memory + /// stay there, the next ones also go to the files. + pub fn set_dir(&self, dir: &Path) { + { + let mut s = self.state.lock().unwrap(); + s.dir = Some(dir.to_path_buf()); + s.files.clear(); + } + self.cleanup(Local::now().date_naive()); + } + /// The stored secrets' values, masked in every copy and export. pub fn set_secrets(&self, values: Vec) { self.state.lock().unwrap().secrets = values; @@ -107,7 +119,7 @@ impl LogHub { let mut s = self.state.lock().unwrap(); let line = LogLine { seq: s.next_seq, at_ms: at.timestamp_millis(), level, tab: tab.into(), text: text.into() }; s.next_seq += 1; - if let Some(dir) = &self.dir { + if let Some(dir) = s.dir.clone() { let day = at.date_naive(); let key = (tab.to_owned(), day); if !s.files.contains_key(&key) { @@ -135,8 +147,12 @@ impl LogHub { /// Remove log files older than the retention. fn cleanup(&self, today: NaiveDate) { - self.state.lock().unwrap().last_cleanup = Some(today); - let Some(dir) = &self.dir else { return }; + let dir = { + let mut s = self.state.lock().unwrap(); + s.last_cleanup = Some(today); + s.dir.clone() + }; + let Some(dir) = dir else { return }; let Ok(entries) = std::fs::read_dir(dir) else { return }; for e in entries.flatten() { let name = e.file_name().to_string_lossy().into_owned(); @@ -183,10 +199,13 @@ impl LogHub { /// The log files of days `from..=to` in a zip at `out`, masked, at most `ZIP_MAX_BYTES`: when /// larger, the oldest lines are left out and NOTE.txt says how many. Returns the lines left out. pub fn export_zip(&self, from: NaiveDate, to: NaiveDate, out: &Path) -> std::io::Result { - let secrets = self.state.lock().unwrap().secrets.clone(); - let Some(dir) = &self.dir else { return Err(std::io::Error::other("no log folder")) }; + let (secrets, dir) = { + let s = self.state.lock().unwrap(); + (s.secrets.clone(), s.dir.clone()) + }; + let Some(dir) = dir else { return Err(std::io::Error::other("no log folder")) }; let mut files: Vec<(NaiveDate, String, Vec)> = vec![]; - for e in std::fs::read_dir(dir)?.flatten() { + for e in std::fs::read_dir(&dir)?.flatten() { let name = e.file_name().to_string_lossy().into_owned(); let Some(day) = file_day(&name) else { continue }; if day < from || day > to { diff --git a/app/ui/app.js b/app/ui/app.js index 8c239af..5a78157 100644 --- a/app/ui/app.js +++ b/app/ui/app.js @@ -193,15 +193,21 @@ async function fillPickers(root, view) { ...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)); }; - const loadVoice = async () => { + // `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; - if (!g.value) return opts(v, [], null, "자동으로 들어가지 않음"); - try { opts(v, (await api("discord_channels", { guildId: g.value })).voice, view["discord.voiceChannelId"], "자동으로 들어가지 않음"); } - catch (e) { /* the ID stays as it was */ } + 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); - loadVoice(); + g.addEventListener("change", () => loadVoice(null)); + loadVoice(view["discord.voiceChannelId"]); } async function tokenCard() { @@ -333,10 +339,14 @@ function logsScreen() { 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) { @@ -350,6 +360,7 @@ async function refresh() { } 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); @@ -359,7 +370,8 @@ async function show(name) { 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; - screen.replaceChildren(await settingsScreen(name, titles[name], extra)); + const view = await settingsScreen(name, titles[name], extra); + if (my === gen) screen.replaceChildren(view); } catch (e) { fail(e); } } @@ -368,17 +380,24 @@ async function show(name) { const WIZ = ["데이터 폴더", "PC 점검", "모델", "디스코드 봇", "서버·채널", "호출어", "완료"]; async function wizard(status) { const root = $("#wizard"); - let step = status.dataDir ? 3 : 0; + // 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 { card.append(...(await STEPS[step](card)).filter((x) => x != null)); } catch (e) { fail(e); } + try { + const kids = await STEPS[n](card); + if (my === wgen) card.append(...kids.filter((x) => x != null)); + } catch (e) { fail(e); } } const STEPS = [ async () => { @@ -416,7 +435,9 @@ async function wizard(status) { 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 { @@ -430,7 +451,7 @@ async function wizard(status) { } catch (e) { fail(e); } } }, "연결 확인")), out, nav(true, async () => { - if (!s.check) return toast("먼저 연결을 확인해 주세요", true); + if (!s.check) return stored.set ? go(4) : toast("먼저 연결을 확인해 주세요", true); try { await api("token_save", { token: s.token }); go(4); } catch (e) { fail(e); } })]; }, @@ -470,6 +491,7 @@ async function wizard(status) { 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); }