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:
@@ -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
222
app/src/admin_api.rs
Normal 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());
|
||||
}
|
||||
}
|
||||
105
app/src/bin/jarvis-admin-dev.rs
Normal file
105
app/src/bin/jarvis-admin-dev.rs
Normal 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
106
app/src/discord_setup.rs
Normal 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));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user