feat(app): M5 step 1, the admin backend under the management app
- datadir: the data folder layout, the location file (JARVIS_DATA_DIR wins), free space for the wizard. - settings_edit: the fields the five settings screens edit; apply writes only non-defaults, keeps unknown keys and writes nothing unless the app's own check passes. A memory section reaches the worker's hello. - secrets: config/secrets.dat, DPAPI for the Windows user; the services take the bot token from it before JARVIS_DISCORD_TOKEN. - logs: the log hub behind the log screen (tabs, daily files kept 14 days, the recent error report, a zip under 10 MB, secrets and token-shaped text masked); the log macros and the worker's output feed it. Spec: app/src/admin.spec.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
325
app/src/settings_edit.rs
Normal file
325
app/src/settings_edit.rs
Normal file
@@ -0,0 +1,325 @@
|
||||
//! Editing `config/settings.json` for the settings screens (`app/src/admin.spec.md`).
|
||||
//!
|
||||
//! The screens are built from `fields()`. `apply` changes only the keys it is given, writes only
|
||||
//! values that differ from the default, keeps keys the app does not know, and writes nothing unless
|
||||
//! the whole result passes the app's own check (`parse_settings`).
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
use crate::datadir::write_atomic;
|
||||
use crate::settings::{parse_settings, DEFAULT_JOIN_NOTICE};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Screen {
|
||||
Bot,
|
||||
Channels,
|
||||
Chat,
|
||||
Memory,
|
||||
Model,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
|
||||
#[serde(tag = "type", rename_all = "camelCase")]
|
||||
pub enum Kind {
|
||||
Bool,
|
||||
Int { min: i64, max: i64 },
|
||||
Number { min: f64, max: f64 },
|
||||
/// `nullable`: null is allowed (it means "not set").
|
||||
NullableNumber { min_exclusive: f64 },
|
||||
Text { max: usize, non_empty: bool },
|
||||
/// `nullable`: null means "use another setting" (chat wake words: the voice ones).
|
||||
TextList { max_items: usize, nullable: bool },
|
||||
Choice { values: &'static [&'static str] },
|
||||
/// A language code (2-8 letters), or null for "detect it".
|
||||
LanguageCode,
|
||||
/// A Discord ID as a JSON string, or null.
|
||||
Id,
|
||||
IdList,
|
||||
/// Discord user ID -> integer (response priorities).
|
||||
IdNumberMap,
|
||||
/// The registered chat channels (their own rules are checked by `parse_settings`).
|
||||
ChatChannels,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
|
||||
pub struct Field {
|
||||
pub path: &'static str,
|
||||
pub screen: Screen,
|
||||
#[serde(flatten)]
|
||||
pub kind: Kind,
|
||||
pub default: Value,
|
||||
pub label: &'static str,
|
||||
}
|
||||
|
||||
fn f(path: &'static str, screen: Screen, kind: Kind, default: Value, label: &'static str) -> Field {
|
||||
Field { path, screen, kind, default, label }
|
||||
}
|
||||
|
||||
/// Every key the screens edit, in screen order.
|
||||
pub fn fields() -> Vec<Field> {
|
||||
use Kind::*;
|
||||
use Screen::*;
|
||||
vec![
|
||||
f("discord.commandName", Bot, Text { max: 32, non_empty: true }, json!("자비스"), "슬래시 명령 이름"),
|
||||
f("discord.ephemeralReplies", Bot, Bool, json!(true), "명령 응답은 부른 사람만 보기"),
|
||||
f("discord.guildId", Channels, Id, Value::Null, "서버"),
|
||||
f("discord.voiceChannelId", Channels, Id, Value::Null, "자동으로 들어갈 음성 채널"),
|
||||
f("voice.maxSpeakers", Channels, Int { min: 1, max: 10 }, json!(10), "동시에 받아 적을 최대 인원"),
|
||||
f("voice.listenToBots", Channels, Bool, json!(false), "다른 봇의 말도 받아 적기"),
|
||||
f("voice.wakeWords", Channels, TextList { max_items: 20, nullable: false }, json!(["자비스"]), "호출어"),
|
||||
f("call.mode", Channels, Choice { values: &["wakeWord", "addressed", "everything"] }, json!("wakeWord"),
|
||||
"호출 방식"),
|
||||
f("call.similarity", Channels, Number { min: 0.0, max: 0.5 }, json!(0.2), "비슷한 발음 허용 정도"),
|
||||
f("call.designated", Channels, IdList, json!([]), "지정한 사람"),
|
||||
f("call.designatedOnly", Channels, Bool, json!(false), "지정한 사람에게만 응답"),
|
||||
f("call.designatedNoWakeWord", Channels, Bool, json!(false), "지정한 사람은 호출어 없이 대답"),
|
||||
f("call.stopWords", Channels, TextList { max_items: 20, nullable: false },
|
||||
json!(["멈춰", "그만", "정지", "stop"]), "정지 명령"),
|
||||
f("call.followUpMs", Channels, Int { min: 0, max: 5000 }, json!(1500), "호출어 뒤 이어 말하기 대기(ms)"),
|
||||
f("call.earcon", Channels, Bool, json!(true), "부르면 효과음"),
|
||||
f("response.policy", Channels, Choice { values: &["first", "inOrder", "latest", "important"] },
|
||||
json!("first"), "동시 대화 응답 정책"),
|
||||
f("response.queueMax", Channels, Int { min: 1, max: 20 }, json!(5), "기다리는 요청 최대 개수"),
|
||||
f("response.collectMs", Channels, Int { min: 0, max: 3000 }, json!(700), "중요도 비교 대기(ms)"),
|
||||
f("response.settleMs", Channels, Int { min: 0, max: 3000 }, json!(800), "먼저 끝난 말 전사 대기(ms)"),
|
||||
f("response.priorities", Channels, IdNumberMap, json!({}), "사람별 우선순위"),
|
||||
f("voice.joinNotice", Channels, Text { max: 2000, non_empty: true }, json!(DEFAULT_JOIN_NOTICE),
|
||||
"입장 시 전사 고지 문구"),
|
||||
f("chatChannels", Chat, ChatChannels, json!([]), "채팅 채널"),
|
||||
f("call.chatWakeWords", Chat, TextList { max_items: 20, nullable: true }, Value::Null,
|
||||
"채팅 호출어(비우면 음성과 같음)"),
|
||||
// The worker's memory settings and their defaults (voice_worker.spec.md, "Memory settings").
|
||||
f("memory.chat", Memory, Bool, json!(true), "등록한 채팅 채널 참고"),
|
||||
f("memory.others", Memory, Bool, json!(true), "같은 음성 채널의 다른 사람 말 참고"),
|
||||
f("memory.off", Memory, Bool, json!(false), "지난 대화 참고 끄기"),
|
||||
f("memory.since_days", Memory, NullableNumber { min_exclusive: 0.0 }, Value::Null,
|
||||
"참고할 기간(일, 비우면 전체)"),
|
||||
f("memory.recent_minutes", Memory, Number { min: 0.0, max: 1440.0 }, json!(30), "최근 대화 원문 범위(분)"),
|
||||
f("memory.recent_records", Memory, Int { min: 0, max: 200 }, json!(20), "최근 대화 원문 개수"),
|
||||
f("memory.matches", Memory, Int { min: 0, max: 20 }, json!(5), "과거 기록 가져올 개수"),
|
||||
f("memory.budget_tokens", Memory, Number { min: 0.0, max: 100000.0 }, json!(4000), "참고 분량 상한(토큰)"),
|
||||
// The worker's STT settings and their defaults (voice_worker.spec.md, "STT").
|
||||
f("voice.stt.end_silence_ms", Model, Int { min: 100, max: 2000 }, json!(300), "말 끝 판정 시간(ms)"),
|
||||
f("voice.stt.partials", Model, Bool, json!(true), "중간 전사"),
|
||||
f("voice.stt.partial_interval_ms", Model, Int { min: 100, max: 5000 }, json!(400), "중간 전사 간격(ms)"),
|
||||
f("voice.stt.final_beam", Model, Int { min: 1, max: 5 }, json!(2), "최종 전사 정확도(빔)"),
|
||||
f("voice.stt.language", Model, LanguageCode, json!("ko"), "받아 적을 언어(비우면 자동)"),
|
||||
]
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct EditError(pub String);
|
||||
|
||||
impl std::fmt::Display for EditError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(&self.0)
|
||||
}
|
||||
}
|
||||
impl std::error::Error for EditError {}
|
||||
|
||||
fn load_raw(file: &Path) -> Result<Map<String, Value>, EditError> {
|
||||
let text = match std::fs::read_to_string(file) {
|
||||
Ok(t) => t,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Map::new()),
|
||||
Err(e) => return Err(EditError(format!("could not read {}: {e}", file.display()))),
|
||||
};
|
||||
match serde_json::from_str(text.trim_start_matches('\u{feff}')) {
|
||||
Ok(Value::Object(m)) => Ok(m),
|
||||
Ok(_) => Err(EditError(format!("{} is not a JSON object", file.display()))),
|
||||
Err(e) => Err(EditError(format!("{} is not valid JSON: {e}", file.display()))),
|
||||
}
|
||||
}
|
||||
|
||||
fn get_path<'a>(raw: &'a Map<String, Value>, path: &str) -> Option<&'a Value> {
|
||||
let mut parts = path.split('.');
|
||||
let mut cur = raw.get(parts.next()?)?;
|
||||
for p in parts {
|
||||
cur = cur.as_object()?.get(p)?;
|
||||
}
|
||||
Some(cur)
|
||||
}
|
||||
|
||||
fn set_path(raw: &mut Map<String, Value>, path: &str, value: Value) -> Result<(), EditError> {
|
||||
let parts: Vec<&str> = path.split('.').collect();
|
||||
let mut cur = raw;
|
||||
for p in &parts[..parts.len() - 1] {
|
||||
let entry = cur.entry(p.to_string()).or_insert_with(|| Value::Object(Map::new()));
|
||||
cur = entry.as_object_mut().ok_or_else(|| EditError(format!("{p} in the file is not an object")))?;
|
||||
}
|
||||
cur.insert(parts[parts.len() - 1].into(), value);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove `path`, then every parent object it leaves empty.
|
||||
fn remove_path(raw: &mut Map<String, Value>, path: &str) {
|
||||
fn go(m: &mut Map<String, Value>, parts: &[&str]) {
|
||||
if parts.len() == 1 {
|
||||
m.remove(parts[0]);
|
||||
return;
|
||||
}
|
||||
if let Some(Value::Object(child)) = m.get_mut(parts[0]) {
|
||||
go(child, &parts[1..]);
|
||||
if child.is_empty() {
|
||||
m.remove(parts[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
go(raw, &path.split('.').collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
fn is_id(v: &Value) -> bool {
|
||||
v.as_str().is_some_and(|s| (17..=20).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_digit()))
|
||||
}
|
||||
|
||||
fn check(field: &Field, v: &Value) -> Result<(), String> {
|
||||
let ok = match &field.kind {
|
||||
Kind::Bool => v.is_boolean(),
|
||||
Kind::Int { min, max } => v.as_i64().is_some_and(|n| (*min..=*max).contains(&n)) && !v.is_f64(),
|
||||
Kind::Number { min, max } => v.as_f64().is_some_and(|n| (*min..=*max).contains(&n)),
|
||||
Kind::NullableNumber { min_exclusive } => v.is_null() || v.as_f64().is_some_and(|n| n > *min_exclusive),
|
||||
Kind::Text { max, non_empty } => v.as_str().is_some_and(|s| {
|
||||
let n = s.trim().chars().count();
|
||||
n <= *max && (!non_empty || n > 0)
|
||||
}),
|
||||
Kind::TextList { max_items, nullable } => (*nullable && v.is_null())
|
||||
|| v.as_array().is_some_and(|a| a.len() <= *max_items && a.iter().all(|w| w.as_str().is_some_and(|s| {
|
||||
let n = s.trim().chars().count();
|
||||
(1..=64).contains(&n)
|
||||
}))),
|
||||
Kind::Choice { values } => v.as_str().is_some_and(|s| values.contains(&s)),
|
||||
Kind::LanguageCode => v.is_null()
|
||||
|| v.as_str().is_some_and(|s| (2..=8).contains(&s.len()) && s.chars().all(|c| c.is_ascii_alphabetic() || c == '-')),
|
||||
Kind::Id => v.is_null() || is_id(v),
|
||||
Kind::IdList => v.as_array().is_some_and(|a| a.iter().all(is_id)),
|
||||
Kind::IdNumberMap => v.as_object().is_some_and(|m| m.iter()
|
||||
.all(|(k, n)| is_id(&Value::String(k.clone())) && n.as_i64().is_some())),
|
||||
Kind::ChatChannels => v.is_array(),
|
||||
};
|
||||
if ok { Ok(()) } else { Err(format!("{} has a value it cannot take", field.path)) }
|
||||
}
|
||||
|
||||
/// Every field's value now: the file's, else the default.
|
||||
pub fn view(settings_file: &Path) -> Result<Map<String, Value>, EditError> {
|
||||
let raw = load_raw(settings_file)?;
|
||||
Ok(fields().into_iter()
|
||||
.map(|f| (f.path.to_owned(), get_path(&raw, f.path).cloned().unwrap_or(f.default)))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Apply `{path: value}` to the file; all or nothing.
|
||||
pub fn apply(settings_file: &Path, changes: &Map<String, Value>) -> Result<(), EditError> {
|
||||
let mut raw = load_raw(settings_file)?;
|
||||
let all = fields();
|
||||
for (path, value) in changes {
|
||||
let field = all.iter().find(|f| f.path == path)
|
||||
.ok_or_else(|| EditError(format!("{path} is not a setting the screens edit")))?;
|
||||
check(field, value).map_err(EditError)?;
|
||||
if *value == field.default {
|
||||
remove_path(&mut raw, path);
|
||||
} else {
|
||||
set_path(&mut raw, path, value.clone())?;
|
||||
}
|
||||
}
|
||||
let doc = Value::Object(raw);
|
||||
parse_settings(&doc).map_err(|e| EditError(e.0))?;
|
||||
let mut text = serde_json::to_string_pretty(&doc).expect("JSON serialises");
|
||||
text.push('\n');
|
||||
write_atomic(settings_file, text.as_bytes())
|
||||
.map_err(|e| EditError(format!("could not write {}: {e}", settings_file.display())))?;
|
||||
crate::debug_log!("admin", "settings changed: {}", changes.keys().cloned().collect::<Vec<_>>().join(", "));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::datadir::temp_dir;
|
||||
use crate::settings::Settings;
|
||||
|
||||
fn file(tag: &str) -> std::path::PathBuf {
|
||||
temp_dir(tag).join("settings.json")
|
||||
}
|
||||
fn changes(v: Value) -> Map<String, Value> {
|
||||
v.as_object().unwrap().clone()
|
||||
}
|
||||
fn read(p: &Path) -> Value {
|
||||
serde_json::from_str(&std::fs::read_to_string(p).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_default_is_the_apps_own_default() {
|
||||
// Writing a field's default out explicitly must give the same settings as leaving it out.
|
||||
for f in fields() {
|
||||
let mut raw = Map::new();
|
||||
set_path(&mut raw, f.path, f.default.clone()).unwrap();
|
||||
let parsed = parse_settings(&Value::Object(raw)).unwrap_or_else(|e| panic!("{}: {e}", f.path));
|
||||
let mut d = Settings::default();
|
||||
// memory and stt pass to the worker as given; their defaults are the worker's.
|
||||
d.memory = parsed.memory.clone();
|
||||
d.voice.stt = parsed.voice.stt.clone();
|
||||
assert_eq!(parsed, d, "{}", f.path);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn view_shows_the_file_over_the_defaults() {
|
||||
let p = file("sev");
|
||||
std::fs::write(&p, r#"{"call": {"mode": "addressed"}, "unknown": 1}"#).unwrap();
|
||||
let v = view(&p).unwrap();
|
||||
assert_eq!(v["call.mode"], json!("addressed"));
|
||||
assert_eq!(v["voice.maxSpeakers"], json!(10));
|
||||
assert_eq!(v.len(), fields().len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_writes_only_non_defaults_and_keeps_unknown_keys() {
|
||||
let p = file("sea");
|
||||
std::fs::write(&p, r#"{"voiceWorker": {"python": "/venv/python"}, "mine": {"x": 1}}"#).unwrap();
|
||||
apply(&p, &changes(json!({"call.mode": "everything", "voice.maxSpeakers": 10,
|
||||
"memory.recent_records": 5, "voice.stt.end_silence_ms": 400}))).unwrap();
|
||||
assert_eq!(read(&p), json!({"voiceWorker": {"python": "/venv/python"}, "mine": {"x": 1},
|
||||
"call": {"mode": "everything"}, "memory": {"recent_records": 5}, "voice": {"stt": {"end_silence_ms": 400}}}));
|
||||
// Back to the default: the key goes, and so do sections it leaves empty.
|
||||
apply(&p, &changes(json!({"call.mode": "wakeWord", "voice.stt.end_silence_ms": 300}))).unwrap();
|
||||
assert_eq!(read(&p), json!({"voiceWorker": {"python": "/venv/python"}, "mine": {"x": 1},
|
||||
"memory": {"recent_records": 5}}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_value_changes_nothing() {
|
||||
let p = file("seb");
|
||||
std::fs::write(&p, r#"{"call": {"mode": "addressed"}}"#).unwrap();
|
||||
let before = std::fs::read(&p).unwrap();
|
||||
for (c, key) in [
|
||||
(json!({"voice.maxSpeakers": 11}), "voice.maxSpeakers"),
|
||||
(json!({"voice.maxSpeakers": 2.5}), "voice.maxSpeakers"),
|
||||
(json!({"call.mode": "sometimes"}), "call.mode"),
|
||||
(json!({"discord.guildId": 123}), "discord.guildId"),
|
||||
(json!({"voice.joinNotice": " "}), "voice.joinNotice"),
|
||||
(json!({"memory.since_days": 0}), "memory.since_days"),
|
||||
(json!({"voice.stt.language": ""}), "voice.stt.language"),
|
||||
(json!({"nope": 1}), "nope"),
|
||||
// Passes the field check, refused by the app's own check: a bad command name.
|
||||
(json!({"discord.commandName": "Big Name"}), "discord.commandName"),
|
||||
// A chat channel without a valid ID.
|
||||
(json!({"chatChannels": [{"id": "1"}]}), "chatChannels[0].id"),
|
||||
] {
|
||||
let e = apply(&p, &changes(c.clone()).into_iter().chain([("call.earcon".into(), json!(false))]).collect())
|
||||
.unwrap_err();
|
||||
assert!(e.0.contains(key), "{c} -> {e}");
|
||||
assert_eq!(std::fs::read(&p).unwrap(), before, "{c}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_does_not_parse_is_reported_not_overwritten() {
|
||||
let p = file("sep");
|
||||
std::fs::write(&p, "{ not json").unwrap();
|
||||
assert!(view(&p).is_err());
|
||||
assert!(apply(&p, &changes(json!({"call.earcon": false}))).is_err());
|
||||
assert_eq!(std::fs::read_to_string(&p).unwrap(), "{ not json");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user