Files
javis_bot/app/src/settings_edit.rs
javis-bot ff78c0ac41 feat(app): the LLM always takes one request at a time, and only the latest call is answered by default
A chat channel answering every message no longer starts Strata with
--parallel 2: on the 16 GB card that read prompts about three times
slower (2026-11-16, answers took 10-20 s). Chat and voice answers now
take turns at Strata. response.policy defaults to latest.

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

388 lines
21 KiB
Rust

//! 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,
Features,
Collect,
Game,
Schedule,
PcControl,
App,
}
#[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,
/// The MCP servers (their own rules are checked by `parse_settings`; values are secrets).
McpServers,
/// The background collection targets (their own rules are checked by `parse_settings`).
CollectTargets,
}
#[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 }
}
/// The levels of a PC control action (`settings::Level`).
const LEVELS: &[&str] = &["auto", "ask", "never"];
/// 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!("latest"), "동시 대화 응답 정책"),
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("response.interrupt", Channels, Bool, json!(true),
"말하는 중에 새 요청이 오면 하던 말 멈추기(가장 최근 것, 중요한 것 먼저)"),
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), "참고 분량 상한(토큰)"),
f("voice.record", Memory, Bool, json!(false),
"목소리 녹음 저장(사람 말과 자비스 말, 분석용, 7일 보관, 다음 시작부터)"),
// 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"), "받아 적을 언어(비우면 자동)"),
// MeloTTS's Korean model has one voice (speaker "KR"), so only the speed is a choice.
f("voice.tts.speed", Model, Number { min: 0.5, max: 2.0 }, json!(1.5), "말하기 속도(1.0 보통, 기본 1.5, 저장하면 바로 적용)"),
// The LLM (admin.spec.md, "LLM"); `llm.url` (a server the app does not start) is file-only.
f("llm.context", Model, Int { min: 4096, max: 262144 }, json!(32768), "대화 모델이 한 번에 기억하는 양(토큰)"),
f("brain.location", Model, Text { max: 100, non_empty: false }, json!(crate::settings::DEFAULT_LOCATION),
"기본 위치(날씨, 검색, 추천의 기준, 비우면 자동 감지)"),
f("llm.port", Model, Int { min: 1024, max: 65535 }, json!(8080), "대화 모델 포트"),
// The brain's features (admin.spec.md, "Features and MCP servers").
f("features.weather", Features, Bool, json!(true), "날씨"),
f("features.webSearch", Features, Bool, json!(true), "웹 검색"),
f("features.meals", Features, Bool, json!(true), "식단 기록"),
f("features.collect", Features, Bool, json!(true), "백그라운드 수집"),
f("features.browser", Features, Bool, json!(true), "브라우저 제어(봇용 크롬)"),
f("features.browserShare", Features, Bool, json!(false), "봇용 크롬창 화면공유 선택 표시(가상 모니터, Windows)"),
f("features.schedule", Features, Bool, json!(true), "예약 알림과 정기 작업"),
f("features.notes", Features, Bool, json!(true), "사람별 지침"),
f("features.screen", Features, Bool, json!(true), "화면 보기(Windows, PC 제어에 등록한 사람만)"),
f("mcpServers", Features, McpServers, json!([]), "MCP 서버"),
// Background collection (admin.spec.md, "Background collection"): no targets by default.
f("collect.targets", Collect, CollectTargets, json!([]), "수집 대상"),
f("collect.keepDays", Collect, Int { min: 1, max: 365 }, json!(30), "보관 기간(일)"),
f("collect.notifyChannel", Collect, Id, Value::Null, "새 글을 알릴 채팅 채널(등록한 채널, 비우면 알리지 않음)"),
f("collect.digestHour", Collect, Int { min: 0, max: 23 }, json!(9), "하루 요약을 보낼 시각(시)"),
// Schedules (admin.spec.md, "Schedules").
f("schedule.chatChannel", Schedule, Id, Value::Null,
"음성으로 맡긴 알림을 그 사람이 음성 채널에 없을 때 보낼 채팅 채널(등록한 채널)"),
// PC control permissions (admin.spec.md, "PC control permissions").
f("pcControl.allowedUsers", PcControl, IdList, json!([]), "PC 제어를 시킬 수 있는 사람(디스코드 사용자 ID)"),
f("pcControl.view", PcControl, Choice { values: LEVELS }, json!("auto"), "화면 보기, 창 목록"),
f("pcControl.click", PcControl, Choice { values: LEVELS }, json!("ask"), "누르기(버튼, 메뉴, 화면의 한 점)"),
f("pcControl.type", PcControl, Choice { values: LEVELS }, json!("ask"), "글자·키 입력"),
f("pcControl.run", PcControl, Choice { values: LEVELS }, json!("ask"), "프로그램 실행"),
f("pcControl.screenExclude", PcControl, TextList { max_items: 100, nullable: false },
json!(["1Password", "Bitwarden", "KeePass", "KeePassXC"]), "화면 보기에서 뺄 프로그램(파일 이름, 은행·비밀번호 관리자 등)"),
// Game detection (admin.spec.md, "Game detection").
f("game.detect", Game, Bool, json!(true), "게임 감지"),
f("game.games", Game, TextList { max_items: 100, nullable: false }, json!([]), "게임으로 볼 프로그램(파일 이름, 예: MyGame.exe)"),
f("game.otherRoomGb", Game, Number { min: 0.0, max: 8.0 }, json!(1.0), "평소 다른 프로그램용으로 남길 VRAM(GB)"),
f("game.reserveGb", Game, Number { min: 0.0, max: 32.0 }, json!(8.0), "게임 중 게임용으로 비울 VRAM(GB)"),
f("game.revertSeconds", Game, Int { min: 0, max: 600 }, json!(30), "게임이 끝난 뒤 평소 배치로 돌아가기까지(초)"),
f("game.pauseInGame", Game, Bool, json!(false), "게임 중 일시정지(대답하지 않음)"),
f("game.notGames", Game, TextList { max_items: 100, nullable: false }, json!([]), "게임이 아닌 프로그램(파일 이름)"),
// The window (admin.spec.md, "Window and Windows build"): read when the close button is pressed.
f("app.closeButton", App, Choice { values: &["quit", "tray"] }, json!("quit"), "창 닫기(X) 버튼을 누르면"),
]
}
#[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 | Kind::McpServers | Kind::CollectTargets => 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"),
(json!({"collect.targets": [{"name": "nul", "kind": "rss", "value": "https://a"}]}), "collect.targets[0].name"),
] {
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");
}
}