feat(app): M5 step 3, the management app's screens and their commands

- admin_api: the one entry point of the screens (app status, data folder,
  PC check, Discord token check and pickers, settings, service control and
  the dashboard, logs query, error report and zip export).
- discord_setup: token, Message Content and invite link checks over REST.
- app/ui: first-run wizard, dashboard, five settings screens and the log
  screen in plain HTML/CSS/JS (dark theme after DESIGN.md, Korean text).
- jarvis-admin-dev: a loopback, token-guarded development server so the
  screens run in a browser against the real commands.

Checked in a browser with the real test bot and voice worker: wizard
steps, start/restart/stop, settings save, chat channels, logs and export.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-12 14:15:58 +09:00
parent e8ddde5be6
commit 20300c017e
11 changed files with 1654 additions and 2 deletions

View File

@@ -127,6 +127,49 @@ reaches the screen.
The dashboard's state is built from the core's events alone (`Dashboard::on_event` with the time),
so it is tested with made-up events.
## Admin commands (`app/src/admin_api.rs`)
`AdminApi::call(command, args)` is the one entry point of the screens, JSON in and out; errors come
back as Korean messages for the screen. The Tauri shell passes the screens' `invoke("admin",
{command, args})` to it; the development server (below) does the same over loopback HTTP.
| Command | Does |
|---|---|
| `app_status` | version, data folder, whether a token is stored; `firstRun` while either is missing |
| `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) |
| `token_save` `{token}` / `token_status` | store it (masked from then on in logs) / `set` and the masked form, never the token |
| `discord_guilds` / `discord_channels` `{guildId}` | the bot's servers / a server's voice and text channels, for the pickers |
| `settings_fields` / `settings_view` / `settings_apply` `{changes}` | the settings editor above; `restartNeeded` when the services run |
| `service_start` / `service_stop` / `service_restart` / `dashboard` | the controller and its snapshot |
| `logs_query` `{tab, level, find, after, limit}` / `logs_error_report` / `logs_export` `{from, to}` | the log hub; the zip goes to `logs/` and its path comes back |
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).
## Screens (`app/ui/`)
Plain HTML, CSS and an ES module, no build step, dark theme after `DESIGN.md`. All text is Korean.
- **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.
- **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.
- **Settings screens** (봇, 채널·호출, 채팅 채널, 대화 기억, 모델): built from `settings_fields`; only
changed fields are sent; the server and voice channel are pickers; 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.
`jarvis-admin-dev [--port N] [--ui DIR] [--location FILE]` (development only) serves `app/ui` and
the commands on 127.0.0.1; every command needs the random token it prints (`#token=` in the page
URL), so other local programs cannot drive it.
## Tests
`cargo test`: data folder layout, location file and the environment override, a refused relative
@@ -136,5 +179,9 @@ without touching the file; secrets round trip, file permissions on Unix, masking
categories, query filters and follow, files per day and retention, error report bounds, zip size
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). Windows-only paths (DPAPI, `%APPDATA%`) are
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
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
checked on the Windows VM in the Windows build step.

222
app/src/admin_api.rs Normal file
View File

@@ -0,0 +1,222 @@
//! The commands the management app's screens call (`app/src/admin.spec.md`, "Admin commands").
//!
//! One entry point, `AdminApi::call(command, args)`, with JSON in and out: the Tauri shell passes
//! the screen's `invoke` straight to it, and the development server does the same over loopback
//! HTTP, so both run the same code.
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use serde_json::{json, Map, Value};
use crate::control::{Controller, ServicesHost};
use crate::datadir::{free_bytes, DataDir, RECOMMENDED_FREE_BYTES};
use crate::logs::{Level, LogHub};
use crate::secrets::{masked, Secrets, DISCORD_TOKEN};
pub const APP_VERSION: &str = env!("CARGO_PKG_VERSION");
pub struct AdminApi {
location_file: PathBuf,
dir: Mutex<Option<DataDir>>,
controller: Mutex<Option<Arc<Controller>>>,
hub: Arc<LogHub>,
}
fn arg<'a>(args: &'a Value, key: &str) -> Result<&'a Value, String> {
args.get(key).ok_or_else(|| format!("{key}이(가) 필요합니다"))
}
fn arg_str<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> {
arg(args, key)?.as_str().ok_or_else(|| format!("{key}은(는) 글자여야 합니다"))
}
fn level_of(s: &str) -> Level {
match s {
"error" => Level::Error,
"warn" => Level::Warn,
"info" => Level::Info,
_ => Level::Debug,
}
}
impl AdminApi {
/// `location_file`: where the data folder is remembered; `hub`: the app's log hub.
pub fn new(location_file: &Path, hub: Arc<LogHub>) -> Self {
let dir = DataDir::locate(location_file);
Self { location_file: location_file.to_path_buf(), dir: Mutex::new(dir), controller: Mutex::new(None), hub }
}
fn dir(&self) -> Result<DataDir, String> {
self.dir.lock().unwrap().clone().ok_or_else(|| "데이터 폴더를 먼저 골라 주세요".into())
}
fn secrets(&self) -> Result<Secrets, String> {
Ok(Secrets::new(&self.dir()?.secrets_file()))
}
fn token(&self) -> Result<String, String> {
self.secrets()?.get(DISCORD_TOKEN).map_err(|e| e.to_string())?
.ok_or_else(|| "봇 토큰을 먼저 저장해 주세요".into())
}
fn controller(&self) -> Result<Arc<Controller>, String> {
let dir = self.dir()?;
let mut c = self.controller.lock().unwrap();
Ok(c.get_or_insert_with(|| Controller::new(ServicesHost { data_dir: dir.path().to_path_buf() })).clone())
}
pub async fn call(&self, command: &str, args: Value) -> Result<Value, String> {
crate::debug_log!("admin", "command {command}");
match command {
"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());
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()}))
}
"folder_check" => {
let path = PathBuf::from(arg_str(&args, "path")?);
if !path.is_absolute() {
return Err("전체 경로를 적어 주세요 (예: D:\\JarvisBot)".into());
}
let free = free_bytes(&path).map_err(|e| e.to_string())?;
Ok(json!({"freeBytes": free, "recommendedBytes": RECOMMENDED_FREE_BYTES,
"enough": free >= RECOMMENDED_FREE_BYTES, "exists": path.exists()}))
}
"folder_choose" => {
let path = PathBuf::from(arg_str(&args, "path")?);
let dir = DataDir::choose(&path, &self.location_file).map_err(|e| e.to_string())?;
*self.dir.lock().unwrap() = Some(dir);
*self.controller.lock().unwrap() = None;
crate::info_log!("admin", "data folder chosen");
Ok(json!({"dataDir": path.to_string_lossy()}))
}
"pc_check" => {
let usage = crate::system::usage().await;
let driver = crate::system::driver_version().await;
let disk = self.dir.lock().unwrap().as_ref().and_then(|d| free_bytes(d.path()).ok());
Ok(json!({"os": std::env::consts::OS, "cpuThreads": std::thread::available_parallelism().map(|n| n.get()).ok(),
"ramTotalMb": usage.ram_total_mb, "gpus": usage.gpus, "driver": driver,
"driverOk": driver.as_deref().is_some_and(crate::system::driver_ok),
"minDriver": crate::system::MIN_DRIVER_MAJOR, "diskFreeBytes": disk}))
}
"token_check" => Ok(json!(crate::discord_setup::check_token(arg_str(&args, "token")?).await?)),
"token_save" => {
let token = arg_str(&args, "token")?.trim().to_owned();
if token.is_empty() {
return Err("봇 토큰이 비어 있습니다".into());
}
self.secrets()?.set(DISCORD_TOKEN, &token).map_err(|e| e.to_string())?;
self.hub.set_secrets(self.secrets()?.values());
crate::info_log!("admin", "bot token saved");
Ok(json!({"masked": masked(&token)}))
}
"token_status" => {
let t = self.secrets()?.get(DISCORD_TOKEN).map_err(|e| e.to_string())?;
Ok(json!({"set": t.is_some(), "masked": t.as_deref().map(masked)}))
}
"discord_guilds" => Ok(json!(crate::discord_setup::guilds(&self.token()?).await?)),
"discord_channels" => {
let guild: u64 = arg_str(&args, "guildId")?.parse().map_err(|_| "서버 ID가 올바르지 않습니다")?;
Ok(json!(crate::discord_setup::channels(&self.token()?, guild).await?))
}
"settings_fields" => Ok(json!(crate::settings_edit::fields())),
"settings_view" => crate::settings_edit::view(&self.dir()?.settings_file())
.map(Value::Object).map_err(|e| e.0),
"settings_apply" => {
let changes: Map<String, Value> = arg(&args, "changes")?.as_object().cloned()
.ok_or("changes는 객체여야 합니다")?;
crate::settings_edit::apply(&self.dir()?.settings_file(), &changes).map_err(|e| e.0)?;
Ok(json!({"saved": changes.len(), "restartNeeded": self.controller()?.state() == crate::control::State::Running}))
}
"service_start" => self.controller()?.start().await.map(|_| json!({"ok": true})),
"service_stop" => self.controller()?.stop().await.map(|_| json!({"ok": true})),
"service_restart" => self.controller()?.restart().await.map(|_| json!({"ok": true})),
"dashboard" => Ok(self.controller()?.snapshot().await),
"logs_query" => {
let tab = args.get("tab").and_then(Value::as_str).filter(|t| !t.is_empty() && *t != "all");
let level = level_of(args.get("level").and_then(Value::as_str).unwrap_or("debug"));
let find = args.get("find").and_then(Value::as_str).filter(|f| !f.is_empty());
let after = args.get("after").and_then(Value::as_u64);
let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(500).min(5000) as usize;
Ok(json!(self.hub.query(tab, level, find, after, limit)))
}
"logs_error_report" => {
let report = self.hub.recent_error_report(APP_VERSION);
let too_long = report.as_ref().is_some_and(|r| r.chars().count() > crate::logs::DISCORD_MESSAGE_CHARS);
Ok(json!({"report": report, "tooLongForDiscord": too_long}))
}
"logs_export" => {
let day = |k: &str| -> Result<chrono::NaiveDate, String> {
chrono::NaiveDate::parse_from_str(arg_str(&args, k)?, "%Y-%m-%d").map_err(|_| format!("{k}는 YYYY-MM-DD 날짜여야 합니다"))
};
let (from, to) = (day("from")?, day("to")?);
let out = self.dir()?.logs().join(format!("jarvis-logs-{from}-{to}.zip"));
let dropped = self.hub.export_zip(from, to, &out).map_err(|e| e.to_string())?;
Ok(json!({"path": out.to_string_lossy(), "droppedLines": dropped}))
}
_ => Err(format!("알 수 없는 명령: {command}")),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::datadir::temp_dir;
fn api(tag: &str) -> (AdminApi, PathBuf) {
let base = temp_dir(tag);
let loc = base.join("cfg").join("location.json");
(AdminApi { location_file: loc, dir: Mutex::new(None), controller: Mutex::new(None), hub: LogHub::new(None) },
base)
}
#[tokio::test]
async fn the_first_run_chooses_a_folder_then_stores_the_token() {
let (a, base) = api("api1");
assert_eq!(a.call("app_status", json!({})).await.unwrap()["firstRun"], json!(true));
assert!(a.call("settings_view", json!({})).await.unwrap_err().contains("데이터 폴더"));
assert!(a.call("folder_check", json!({"path": "relative"})).await.is_err());
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.call("folder_choose", json!({"path": data.to_string_lossy()})).await.unwrap();
assert!(data.join("config").is_dir());
assert_eq!(a.call("app_status", json!({})).await.unwrap()["firstRun"], json!(true), "no token yet");
let saved = a.call("token_save", json!({"token": "abc.def.ghijkl"})).await.unwrap();
assert_eq!(saved["masked"], json!("••••ijkl"));
let s = a.call("app_status", json!({})).await.unwrap();
assert_eq!((s["firstRun"].clone(), s["tokenSet"].clone()), (json!(false), json!(true)));
// The token never comes back whole.
assert_eq!(a.call("token_status", json!({})).await.unwrap(), json!({"set": true, "masked": "••••ijkl"}));
}
#[tokio::test]
async fn settings_go_through_the_editor_and_logs_through_the_hub() {
let (a, base) = api("api2");
a.call("folder_choose", json!({"path": base.join("d").to_string_lossy()})).await.unwrap();
let fields = a.call("settings_fields", json!({})).await.unwrap();
assert_eq!(fields.as_array().unwrap().len(), crate::settings_edit::fields().len());
a.call("settings_apply", json!({"changes": {"call.mode": "everything"}})).await.unwrap();
assert_eq!(a.call("settings_view", json!({})).await.unwrap()["call.mode"], json!("everything"));
assert!(a.call("settings_apply", json!({"changes": {"call.mode": "x"}})).await.unwrap_err().contains("call.mode"));
a.hub.push(Level::Error, "discord", "login failed");
a.hub.push(Level::Debug, "chat", "ok");
let lines = a.call("logs_query", json!({"tab": "discord", "level": "error"})).await.unwrap();
assert_eq!(lines.as_array().unwrap().len(), 1);
let r = a.call("logs_error_report", json!({})).await.unwrap();
assert!(r["report"].as_str().unwrap().contains("login failed"));
assert!(a.call("nope", json!({})).await.is_err());
}
#[tokio::test]
async fn the_dashboard_answers_before_anything_runs() {
let (a, base) = api("api3");
a.call("folder_choose", json!({"path": base.join("d").to_string_lossy()})).await.unwrap();
let d = a.call("dashboard", json!({})).await.unwrap();
assert_eq!(d["state"], json!("stopped"));
assert!(a.call("service_stop", json!({})).await.is_err());
}
}

View File

@@ -0,0 +1,105 @@
//! Development server for the management app's screens (`app/src/admin.spec.md`, "Screens"):
//! serves `app/ui` and passes `POST /api/<command>` to the same `AdminApi` the Tauri shell uses,
//! so the screens can be opened and tested in a browser. Loopback only, and every API call needs
//! the random token printed at start (in the page URL's `#token=`).
//!
//! jarvis-admin-dev [--port N] [--ui DIR] [--location FILE]
use std::path::{Path, PathBuf};
use std::sync::Arc;
use jarvis_app::admin_api::AdminApi;
use serde_json::{json, Value};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
fn arg(name: &str) -> Option<String> {
let args: Vec<String> = std::env::args().collect();
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1).cloned())
}
fn content_type(path: &Path) -> &'static str {
match path.extension().and_then(|e| e.to_str()) {
Some("html") => "text/html; charset=utf-8",
Some("js") => "text/javascript; charset=utf-8",
Some("css") => "text/css; charset=utf-8",
Some("svg") => "image/svg+xml",
Some("png") => "image/png",
_ => "application/octet-stream",
}
}
async fn respond(s: &mut TcpStream, status: &str, ctype: &str, body: &[u8]) {
let head = format!("HTTP/1.1 {status}\r\nContent-Type: {ctype}\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n", body.len());
let _ = s.write_all(head.as_bytes()).await;
let _ = s.write_all(body).await;
}
async fn handle(mut s: TcpStream, api: Arc<AdminApi>, ui: Arc<PathBuf>, token: Arc<String>) {
let mut buf = Vec::new();
let mut chunk = [0u8; 8192];
let head_end = loop {
let Ok(n) = s.read(&mut chunk).await else { return };
if n == 0 { return; }
buf.extend_from_slice(&chunk[..n]);
if let Some(i) = buf.windows(4).position(|w| w == b"\r\n\r\n") { break i + 4; }
if buf.len() > 64 * 1024 { return; }
};
let head = String::from_utf8_lossy(&buf[..head_end]).to_string();
let mut lines = head.lines();
let mut first = lines.next().unwrap_or("").split_whitespace();
let (method, path) = (first.next().unwrap_or(""), first.next().unwrap_or("/").to_owned());
let header = |name: &str| head.lines().find_map(|l| l.split_once(':')
.filter(|(k, _)| k.trim().eq_ignore_ascii_case(name)).map(|(_, v)| v.trim().to_owned()));
let len: usize = header("content-length").and_then(|v| v.parse().ok()).unwrap_or(0).min(4 * 1024 * 1024);
while buf.len() < head_end + len {
let Ok(n) = s.read(&mut chunk).await else { return };
if n == 0 { break; }
buf.extend_from_slice(&chunk[..n]);
}
if method == "POST" && path.starts_with("/api/") {
if header("x-admin-token").as_deref() != Some(token.as_str()) {
return respond(&mut s, "403 Forbidden", "text/plain", b"bad token").await;
}
let args: Value = serde_json::from_slice(&buf[head_end..(head_end + len).min(buf.len())]).unwrap_or(json!({}));
let out = match api.call(&path[5..], args).await {
Ok(v) => json!({"ok": true, "value": v}),
Err(e) => json!({"ok": false, "error": e}),
};
return respond(&mut s, "200 OK", "application/json", out.to_string().as_bytes()).await;
}
if method != "GET" {
return respond(&mut s, "405 Method Not Allowed", "text/plain", b"").await;
}
let rel = path.split(['?', '#']).next().unwrap_or("/").trim_start_matches('/');
let rel = if rel.is_empty() { "index.html" } else { rel };
if rel.split('/').any(|p| p == ".." || p.is_empty()) {
return respond(&mut s, "404 Not Found", "text/plain", b"").await;
}
let file = ui.join(rel);
match tokio::fs::read(&file).await {
Ok(b) => respond(&mut s, "200 OK", content_type(&file), &b).await,
Err(_) => respond(&mut s, "404 Not Found", "text/plain", b"").await,
}
}
#[tokio::main]
async fn main() {
let ui = arg("--ui").map(PathBuf::from).unwrap_or_else(|| Path::new(env!("CARGO_MANIFEST_DIR")).join("ui"));
let location = arg("--location").map(PathBuf::from).or_else(jarvis_app::datadir::default_location_file)
.expect("no location file path: pass --location");
let port: u16 = arg("--port").and_then(|p| p.parse().ok()).unwrap_or(0);
// Log files go to the data folder once there is one (from the next start after the wizard).
let logs = jarvis_app::datadir::DataDir::locate(&location).map(|d| d.logs());
let hub = jarvis_app::logs::LogHub::new(logs.as_deref());
jarvis_app::logs::install(hub.clone());
let api = Arc::new(AdminApi::new(&location, hub));
let token: String = (0..16).map(|_| format!("{:02x}", rand::random::<u8>())).collect();
let listener = TcpListener::bind(("127.0.0.1", port)).await.expect("bind");
println!("http://127.0.0.1:{}/#token={token}", listener.local_addr().unwrap().port());
let (ui, token) = (Arc::new(ui), Arc::new(token));
loop {
let Ok((s, _)) = listener.accept().await else { continue };
tokio::spawn(handle(s, api.clone(), ui.clone(), token.clone()));
}
}

106
app/src/discord_setup.rs Normal file
View File

@@ -0,0 +1,106 @@
//! The setup wizard's Discord steps (`app/src/admin.spec.md`, "Admin commands"): check a bot
//! token, the Message Content intent and the invite link, and list servers and channels for the
//! pickers. REST only: nothing here connects to the gateway or joins anything.
use serde::Serialize;
use serenity::all::{ApplicationFlags, ChannelType, GuildId, Http, Permissions};
/// What the bot needs: read and post in chat channels (reply, react, delete, pin), keep channel
/// names and topics in step (desktop-app.md), and talk in voice.
pub fn needed_permissions() -> Permissions {
Permissions::VIEW_CHANNEL | Permissions::SEND_MESSAGES | Permissions::READ_MESSAGE_HISTORY
| Permissions::ADD_REACTIONS | Permissions::MANAGE_MESSAGES | Permissions::MANAGE_CHANNELS
| Permissions::CONNECT | Permissions::SPEAK | Permissions::USE_VAD
}
/// The link that adds the bot to a server with those permissions and its slash command.
pub fn invite_url(application_id: u64) -> String {
format!("https://discord.com/oauth2/authorize?client_id={application_id}&scope=bot%20applications.commands&permissions={}",
needed_permissions().bits())
}
/// The Message Content intent is on (either the full or the limited flag of unverified bots).
pub fn message_content_on(flags: Option<ApplicationFlags>) -> bool {
flags.is_some_and(|f| f.intersects(ApplicationFlags::GATEWAY_MESSAGE_CONTENT
| ApplicationFlags::GATEWAY_MESSAGE_CONTENT_LIMITED))
}
#[derive(Debug, Clone, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct TokenCheck {
pub bot_tag: String,
pub bot_id: String,
pub application_id: String,
pub message_content: bool,
pub invite_url: String,
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct Named {
pub id: String,
pub name: String,
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct Channels {
pub voice: Vec<Named>,
pub text: Vec<Named>,
}
fn err(e: serenity::Error) -> String {
match e {
serenity::Error::Http(h) if h.status_code().is_some_and(|s| s.as_u16() == 401) =>
"디스코드가 이 봇 토큰을 받아들이지 않았습니다".into(),
e => format!("디스코드에 연결하지 못했습니다: {e}"),
}
}
/// Check a token without storing it.
pub async fn check_token(token: &str) -> Result<TokenCheck, String> {
let http = Http::new(token.trim());
let me = http.get_current_user().await.map_err(err)?;
let app = http.get_current_application_info().await.map_err(err)?;
Ok(TokenCheck { bot_tag: me.tag(), bot_id: me.id.to_string(), application_id: app.id.to_string(),
message_content: message_content_on(app.flags), invite_url: invite_url(app.id.get()) })
}
/// The servers the bot is in.
pub async fn guilds(token: &str) -> Result<Vec<Named>, String> {
let list = Http::new(token).get_guilds(None, Some(200)).await.map_err(err)?;
Ok(list.into_iter().map(|g| Named { id: g.id.to_string(), name: g.name }).collect())
}
/// A server's voice and text channels, in their server order.
pub async fn channels(token: &str, guild_id: u64) -> Result<Channels, String> {
let mut list = Http::new(token).get_channels(GuildId::new(guild_id)).await.map_err(err)?;
list.sort_by_key(|c| c.position);
let pick = |kinds: &[ChannelType]| list.iter().filter(|c| kinds.contains(&c.kind))
.map(|c| Named { id: c.id.to_string(), name: c.name.clone() }).collect();
Ok(Channels { voice: pick(&[ChannelType::Voice, ChannelType::Stage]), text: pick(&[ChannelType::Text]) })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_invite_asks_for_the_bot_its_command_and_its_permissions() {
let url = invite_url(123456789012345678);
assert!(url.contains("client_id=123456789012345678"));
assert!(url.contains("scope=bot%20applications.commands"));
let bits: u64 = url.rsplit("permissions=").next().unwrap().parse().unwrap();
let p = Permissions::from_bits_truncate(bits);
for need in [Permissions::CONNECT, Permissions::SPEAK, Permissions::SEND_MESSAGES, Permissions::MANAGE_CHANNELS] {
assert!(p.contains(need), "{need:?}");
}
assert!(!p.contains(Permissions::ADMINISTRATOR));
}
#[test]
fn message_content_counts_when_full_or_limited() {
assert!(message_content_on(Some(ApplicationFlags::GATEWAY_MESSAGE_CONTENT)));
assert!(message_content_on(Some(ApplicationFlags::GATEWAY_MESSAGE_CONTENT_LIMITED)));
assert!(!message_content_on(Some(ApplicationFlags::GATEWAY_GUILD_MEMBERS)));
assert!(!message_content_on(None));
}
}

View File

@@ -1,6 +1,7 @@
//! Jarvis v2 app core (see `app/src/discord_core.spec.md`).
pub mod log;
pub mod admin_api;
pub mod calls;
pub mod chat;
pub mod control;
@@ -8,6 +9,7 @@ pub mod conversation;
pub mod dashboard;
pub mod datadir;
pub mod discord;
pub mod discord_setup;
pub mod earcon;
pub mod frames;
pub mod logs;

View File

@@ -46,6 +46,26 @@ pub async fn gpus() -> Vec<Gpu> {
}
}
/// The NVIDIA driver version (`581.57`), None without nvidia-smi.
pub async fn driver_version() -> Option<String> {
let mut cmd = tokio::process::Command::new("nvidia-smi");
cmd.args(["--query-gpu=driver_version", "--format=csv,noheader"])
.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()).kill_on_drop(true);
#[cfg(windows)]
cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
match tokio::time::timeout(Duration::from_secs(2), cmd.output()).await {
Ok(Ok(o)) if o.status.success() => String::from_utf8_lossy(&o.stdout).lines().next().map(|l| l.trim().to_owned()),
_ => None,
}
}
/// CUDA 13 needs driver 580 or newer (desktop-app.md, "PC 점검").
pub const MIN_DRIVER_MAJOR: u32 = 580;
pub fn driver_ok(version: &str) -> bool {
version.split('.').next().and_then(|m| m.parse::<u32>().ok()).is_some_and(|m| m >= MIN_DRIVER_MAJOR)
}
pub async fn usage() -> Usage {
let (used, total) = memory_mb();
Usage { ram_used_mb: used, ram_total_mb: total, gpus: gpus().await }
@@ -87,6 +107,12 @@ mod tests {
vram_used_mb: 5120, vram_total_mb: 8151 }]);
}
#[test]
fn drivers_from_580_run_cuda_13() {
assert!(driver_ok("581.57") && driver_ok("595.91.07") && driver_ok("580.0"));
assert!(!driver_ok("572.16") && !driver_ok("") && !driver_ok("abc"));
}
#[tokio::test]
async fn usage_reads_this_machines_memory() {
let u = usage().await;

493
app/ui/app.js Normal file
View File

@@ -0,0 +1,493 @@
// 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));
};
const loadVoice = async () => {
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 */ }
};
try { opts(g, await api("discord_guilds"), view["discord.guildId"], "선택 안 함"); } catch (e) { return; }
g.addEventListener("change", loadVoice);
loadVoice();
}
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;
async function refresh() {
if (current !== "dashboard") return;
try {
const d = await api("dashboard");
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) {
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;
screen.replaceChildren(await settingsScreen(name, titles[name], extra));
} catch (e) { fail(e); }
}
// ---- first-run wizard ---------------------------------------------------------------------------
const WIZ = ["데이터 폴더", "PC 점검", "모델", "디스코드 봇", "서버·채널", "호출어", "완료"];
async function wizard(status) {
const root = $("#wizard");
let step = status.dataDir ? 3 : 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 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); }
}
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 () => [h("h2", {}, "받을 모델"),
h("p", {}, "대화 모델 Qwen3.6-35B-A3B(약 23GB)와 받아 적기(Whisper)·음성(MeloTTS) 모델을 받습니다. 고를 것은 없고, 설치가 끝나면 이 PC에 맞는 설정을 스스로 정합니다."),
h("p", { class: "muted small" }, "자동 설치는 다음 업데이트에서 이 단계에 들어옵니다."), nav(true, () => go(3))],
async () => {
const input = h("input", { type: "password", placeholder: "디스코드 봇 토큰", autocomplete: "off" });
const out = h("div");
return [h("h2", {}, "디스코드 봇 연결"),
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 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 () => {
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);

28
app/ui/index.html Normal file
View File

@@ -0,0 +1,28 @@
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Jarvis 관리</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="wizard" class="wizard" hidden></div>
<div id="main" class="layout" hidden>
<nav class="side">
<div class="brand">Jarvis</div>
<button data-screen="dashboard" class="nav">대시보드</button>
<button data-screen="bot" class="nav">봇</button>
<button data-screen="channels" class="nav">채널·호출</button>
<button data-screen="chat" class="nav">채팅 채널</button>
<button data-screen="memory" class="nav">대화 기억</button>
<button data-screen="model" class="nav">모델</button>
<button data-screen="logs" class="nav">로그</button>
<div class="side-foot" id="version"></div>
</nav>
<main id="screen" class="screen"></main>
</div>
<div id="toast" class="toast" hidden></div>
<script type="module" src="app.js"></script>
</body>
</html>

75
app/ui/style.css Normal file
View File

@@ -0,0 +1,75 @@
/* Dark admin theme after DESIGN.md (near-black canvas, charcoal panels, hairline borders, one accent). */
:root {
--canvas: #08090a; --s1: #0f1011; --s2: #141516; --s3: #1b1c1e;
--line: #23252a; --line2: #34343a;
--ink: #f7f8f8; --ink2: #d0d6e0; --ink3: #8a8f98; --ink4: #62666d;
--accent: #5e6ad2; --accent2: #828fff; --ok: #27a644; --warn: #d7a03a; --bad: #e5484d;
font-family: "Pretendard", "Malgun Gothic", "Segoe UI", system-ui, sans-serif;
color: var(--ink); background: var(--canvas); font-size: 14px;
}
* { box-sizing: border-box; }
[hidden] { display: none !important; }
body { margin: 0; min-height: 100vh; }
button, input, select, textarea { font: inherit; color: inherit; }
.layout { display: grid; grid-template-columns: 200px 1fr; min-height: 100vh; }
.side { background: var(--s1); border-right: 1px solid var(--line); padding: 16px 10px; display: flex; flex-direction: column; gap: 2px; }
.brand { font-weight: 600; font-size: 18px; letter-spacing: -0.3px; padding: 6px 10px 16px; }
.nav { text-align: left; background: none; border: 0; padding: 8px 10px; border-radius: 6px; color: var(--ink2); cursor: pointer; }
.nav:hover { background: var(--s2); }
.nav.on { background: var(--s3); color: var(--ink); }
.side-foot { margin-top: auto; color: var(--ink4); font-size: 12px; padding: 8px 10px; }
.screen { padding: 28px 32px; max-width: 1100px; }
h1 { font-size: 24px; font-weight: 600; letter-spacing: -0.4px; margin: 0 0 18px; }
h2 { font-size: 15px; font-weight: 600; margin: 0 0 10px; color: var(--ink2); }
.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 12px; margin-bottom: 12px; }
.card { background: var(--s1); border: 1px solid var(--line); border-radius: 10px; padding: 14px 16px; }
.muted { color: var(--ink3); }
.small { font-size: 12px; }
.row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
.btn { background: var(--s3); border: 1px solid var(--line2); border-radius: 7px; padding: 7px 14px; cursor: pointer; }
.btn:hover { border-color: var(--ink4); }
.btn.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
.btn.primary:hover { background: var(--accent2); }
.btn:disabled { opacity: .45; cursor: default; }
.badge { display: inline-block; border-radius: 999px; padding: 2px 10px; font-size: 12px; border: 1px solid var(--line2); }
.badge.ok { color: var(--ok); border-color: #1f5f30; }
.badge.warn { color: var(--warn); border-color: #6b5222; }
.badge.bad { color: var(--bad); border-color: #6e2a2c; }
.kv { display: grid; grid-template-columns: max-content 1fr; gap: 6px 14px; }
.kv .k { color: var(--ink3); }
.field { display: grid; grid-template-columns: 260px 1fr; gap: 14px; padding: 12px 0; border-bottom: 1px solid var(--line); align-items: start; }
.field label { color: var(--ink2); padding-top: 6px; }
.field .hint { color: var(--ink4); font-size: 12px; margin-top: 4px; }
input[type=text], input[type=number], input[type=password], input[type=date], select, textarea {
background: var(--s2); border: 1px solid var(--line2); border-radius: 7px; padding: 7px 10px; width: 100%; max-width: 520px; outline: none; }
input:focus, select:focus, textarea:focus { border-color: var(--accent); }
textarea { min-height: 70px; resize: vertical; }
.switch { appearance: none; width: 38px; height: 22px; border-radius: 999px; background: var(--line2); position: relative; cursor: pointer; margin-top: 4px; }
.switch:checked { background: var(--accent); }
.switch::after { content: ""; position: absolute; top: 3px; left: 3px; width: 16px; height: 16px; border-radius: 50%; background: #fff; transition: left .12s; }
.switch:checked::after { left: 19px; }
table { width: 100%; border-collapse: collapse; }
th, td { text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--line); vertical-align: top; }
th { color: var(--ink3); font-weight: 500; font-size: 12px; }
.captions { max-height: 260px; overflow: auto; display: flex; flex-direction: column; gap: 4px; }
.cap { color: var(--ink2); }
.cap.partial { color: var(--ink4); font-style: italic; }
.cap b { color: var(--ink); font-weight: 500; margin-right: 6px; }
.logs { background: var(--s1); border: 1px solid var(--line); border-radius: 10px; height: 60vh; overflow: auto; font-family: ui-monospace, Consolas, monospace; font-size: 12px; padding: 8px 10px; }
.log { white-space: pre-wrap; word-break: break-all; padding: 1px 0; }
.log.error { color: var(--bad); } .log.warn { color: var(--warn); } .log.debug { color: var(--ink4); }
.savebar { position: sticky; bottom: 0; background: var(--canvas); padding: 14px 0; display: flex; gap: 10px; align-items: center; }
.toast { position: fixed; right: 20px; bottom: 20px; background: var(--s3); border: 1px solid var(--line2); border-radius: 8px; padding: 10px 14px; max-width: 420px; }
.toast.bad { border-color: var(--bad); }
.wizard { max-width: 720px; margin: 48px auto; padding: 0 20px; }
.steps { display: flex; gap: 6px; margin-bottom: 22px; flex-wrap: wrap; }
.step { font-size: 12px; color: var(--ink4); border: 1px solid var(--line); border-radius: 999px; padding: 3px 10px; }
.step.on { color: var(--ink); border-color: var(--accent); }
.step.done { color: var(--ok); border-color: #1f5f30; }
.wizard .card { padding: 22px 24px; }
.wizard p { color: var(--ink2); line-height: 1.6; }
.nav-row { display: flex; justify-content: space-between; margin-top: 20px; }
a { color: var(--accent2); }
.row > select, .row > input[type=date] { width: auto; }
input[type=date] { color-scheme: dark; }
th, .btn { white-space: nowrap; }