Files
javis_bot/app/src/settings.rs
javis-bot 81bd8bd573 feat(conversation): answers wait until the asker is quiet, and going on joins while the answer plays
Live 2026-11-19 (the user's own pieced requests replayed into Discord) the pauses inside
one thought, 2.3-4.7 s, were longer than writing the answer: the answer started in the
pause, and what followed became a new request, so answers were cut off mid-sentence.

- A voice answer is written at once but starts playing only after its asker has been
  quiet for call.answerWaitMs (default 3000, 0 = off, settings "말이 끝나고 답하기 전
  기다림"); while they talk it waits for their final, which joins the request.
- A request stays open (Going on) until its answer ended, not until it is first heard:
  going on within call.continueMs while it plays stops it and answers all of it.

Replayed live: the three pieced requests each get one answer, none cut off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:10:07 +09:00

1216 lines
59 KiB
Rust

//! App settings: `<data folder>/config/settings.json` (see `app/src/discord_core.spec.md`).
//!
//! Every key is optional in the file; missing keys take the defaults. A bad value stops the app with
//! a message naming the key, rather than running with a setting the user did not choose. Unknown keys
//! are ignored.
use serde_json::{Map, Value};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::Duration;
use crate::calls::{CallMode, CallSettings};
use crate::policy::{PolicyKind, PolicySettings};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChatChannelSettings {
pub id: u64,
/// What the channel is for, as the user describes it; given to the assistant (M3).
pub name: String,
pub description: String,
/// The assistant may read this channel's messages.
pub read: bool,
/// The assistant may send messages to this channel.
pub send: bool,
/// The assistant may edit the messages it wrote here (Discord allows only those).
pub edit: bool,
/// The assistant may add reactions here.
pub react: bool,
/// The assistant may delete messages here (needs Manage Messages for other people's). Off by default.
pub delete: bool,
/// The assistant may pin and unpin messages here. Off by default.
pub pin: bool,
/// Answer every message here (`answer: "everything"`), not only those calling a wake word (`"wakeWord"`,
/// the default; conversation.spec.md).
pub answer_all: bool,
/// Keep the Discord channel's name and topic in step with `name` and `description`
/// (`syncDiscord`, on by default; admin.spec.md, "Chat channel names and topics").
pub sync_discord: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiscordSettings {
/// The one server the bot works in. The slash command is registered there.
pub guild_id: Option<u64>,
/// Voice channel to join on start ("자동 입장").
pub voice_channel_id: Option<u64>,
pub command_name: String,
/// Slash command replies only the caller sees.
pub ephemeral_replies: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub struct VoiceSettings {
/// Most people transcribed at once (1-10).
pub max_speakers: usize,
/// Transcribe other bots too (music bots are ignored by default).
pub listen_to_bots: bool,
/// Keep each utterance and spoken answer as a sound file (voice_worker.spec.md, "Recordings").
pub record: bool,
/// Posted in the voice channel's chat on every join (privacy.md).
pub join_notice: String,
/// Wake words: the STT hint and the voice wake words of call detection (`conversation.spec.md`).
pub wake_words: Vec<String>,
/// Voice worker STT settings (voice_worker.spec.md); the worker validates them.
pub stt: Map<String, Value>,
/// How fast the voice speaks (MeloTTS `speed`, 0.5-2.0); the worker gets it at start.
pub tts_speed: f64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WorkerSettings {
/// Python of the voice worker venv.
pub python: String,
/// Directory holding the `voice_worker` package (the repo's `src/`).
pub cwd: PathBuf,
/// Extra worker arguments, e.g. `["--melo-python", "<MeloTTS venv python>"]`.
pub args: Vec<String>,
}
/// The LLM (admin.spec.md, "LLM"): the app starts Strata on `port`, or uses a server already
/// running at `url` (an OpenAI-compatible `/v1` address) and starts nothing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LlmSettings {
pub url: Option<String>,
pub port: u16,
/// Tokens the model keeps at once (each request's share).
pub context: u32,
}
/// The brain's built-in features (admin.spec.md, "Features and MCP servers"); each is on by default.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FeatureSettings {
pub weather: bool,
pub web_search: bool,
pub meals: bool,
/// Background collection (admin.spec.md, "Background collection").
pub collect: bool,
/// The bot browser (admin.spec.md, "Bot browser").
pub browser: bool,
/// The bot browser's window on a virtual monitor to share in Discord (admin.spec.md, "Virtual
/// monitor"); off by default.
pub browser_share: bool,
/// Reminders and scheduled tasks (admin.spec.md, "Schedules").
pub schedule: bool,
/// Each person's standing instructions (admin.spec.md, "Personal notes").
pub notes: bool,
/// Screen viewing (admin.spec.md, "Screen viewing").
pub screen: bool,
/// Operating programs through agent-desktop (admin.spec.md, "PC control").
pub pc_control: bool,
}
/// Game detection (admin.spec.md, "Game detection"): on by default; the person's own games and
/// programs that are never games, as program file names (".exe" may be left out).
#[derive(Debug, Clone, PartialEq)]
pub struct GameSettings {
pub detect: bool,
pub games: Vec<String>,
pub not_games: Vec<String>,
/// Graphics memory the normal placement leaves for programs opened later (GB, default 1).
pub other_room_gb: f64,
/// Graphics memory a game gets in the game stage (GB, default 8).
pub reserve_gb: f64,
/// How long after a game ends the normal stage comes back (seconds, default 30).
pub revert_seconds: u32,
/// Stop the LLM while a game runs (default off).
pub pause_in_game: bool,
}
impl GameSettings {
pub fn other_room_mib(&self) -> i64 {
(self.other_room_gb * 1024.0).round() as i64
}
pub fn reserve_mib(&self) -> i64 {
(self.reserve_gb * 1024.0).round() as i64
}
}
/// Background collection (admin.spec.md, "Background collection"); no targets by default.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CollectSettings {
pub keep_days: u32,
pub targets: Vec<CollectTarget>,
/// The registered chat channel new items are announced in (admin.spec.md, "News
/// notifications"); None: nothing is announced.
pub notify_channel: Option<u64>,
/// The hour (0-23, local) the daily digest goes out (default 9).
pub digest_hour: u32,
}
/// One thing to collect: `kind` is `site`, `search` or `rss`; `value` its address or words.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CollectTarget {
pub name: String,
pub kind: String,
pub value: String,
pub every_minutes: u32,
pub enabled: bool,
/// New items announced: `off` (default), `now` or `daily`.
pub notify: String,
}
/// How freely Jarvis may do one kind of action on the PC (`app/src/permissions.rs`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Level {
/// Done without asking.
Auto,
/// Done once the person agrees in their next message.
Ask,
/// Not done.
Never,
}
/// PC control permissions (admin.spec.md, "PC control permissions"): who may ask, and the level of
/// each kind of action that can be changed. Payments, passwords, deleting files and administrator
/// rights are never done and have no setting.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PcControlSettings {
/// Discord user IDs; nobody by default.
pub allowed_users: Vec<u64>,
/// Seeing the screen and listing windows (default automatic).
pub view: Level,
/// Pressing buttons and points (default ask).
pub click: Level,
/// Typing text and keys (default ask).
pub type_text: Level,
/// Starting programs (default ask).
pub run: Level,
/// Programs never seen on the screen (file names, ".exe" may be left out).
pub screen_exclude: Vec<String>,
/// Programs with an anti-cheat the person added (file names, ".exe" may be left out): while one
/// runs, nothing but reading is done (admin.spec.md, "PC control").
pub anti_cheat_games: Vec<String>,
/// The emergency stop's global hotkey (`Ctrl+Shift+F12`).
pub stop_hotkey: String,
}
/// An MCP server the brain starts (stdio). The values of `env` are in the secrets, never here.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct McpServerSettings {
pub name: String,
pub command: String,
pub args: Vec<String>,
/// Names of the environment variables it gets (their values are secrets).
pub env: Vec<String>,
pub enabled: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Settings {
pub discord: DiscordSettings,
pub voice: VoiceSettings,
pub chat_channels: Vec<ChatChannelSettings>,
pub voice_worker: WorkerSettings,
/// Call detection for voice (`conversation.spec.md`); its wake words are `voice.wakeWords`.
pub call: CallSettings,
/// Wake words for chat; `None` uses `voice.wakeWords`.
pub chat_wake_words: Option<Vec<String>>,
pub response: PolicySettings,
/// The voice worker's memory settings (voice_worker.spec.md, "Memory settings"), sent in its
/// `hello`; the worker validates them, the settings screens check them first (admin.spec.md).
pub memory: Map<String, Value>,
pub llm: LlmSettings,
pub features: FeatureSettings,
pub mcp_servers: Vec<McpServerSettings>,
pub collect: CollectSettings,
pub game: GameSettings,
/// The registered chat channel a schedule asked by voice is posted in when its person is not in
/// Jarvis's voice channel (admin.spec.md, "Schedules"); None: not delivered then.
pub schedule_channel: Option<u64>,
pub pc_control: PcControlSettings,
/// The window's close button (X) hides it to the tray instead of quitting (`app.closeButton`:
/// "tray" or "quit", default "quit"; admin.spec.md, "Window and Windows build").
pub close_to_tray: bool,
/// Where the people Jarvis answers are, by default (`brain.location`, default "대한민국"): the
/// brain's location for the time line, weather without a place and searches (admin.spec.md,
/// "LLM"); None (an empty value) leaves it to the brain's own detection.
pub location: Option<String>,
}
pub const DEFAULT_LOCATION: &str = "대한민국";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SettingsError(pub String);
impl std::fmt::Display for SettingsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for SettingsError {}
pub const DEFAULT_JOIN_NOTICE: &str =
"자비스가 이 음성 채널에 들어왔습니다. 이 채널의 대화는 자비스가 받아 적습니다.";
/// The default wake words: Jarvis is called like a secretary, by the word and its usual call forms
/// (the longest one heard is the call, `calls.rs`).
pub fn default_wake_words() -> Vec<String> {
["비서", "비서야", "비서님", "김비서", "김비서야", "김비서님"].map(String::from).to_vec()
}
impl Default for Settings {
fn default() -> Self {
Self {
discord: DiscordSettings {
guild_id: None,
voice_channel_id: None,
command_name: "자비스".into(),
ephemeral_replies: true,
},
voice: VoiceSettings {
max_speakers: 10,
listen_to_bots: false,
record: false,
join_notice: DEFAULT_JOIN_NOTICE.into(),
wake_words: default_wake_words(),
stt: Map::new(),
tts_speed: 1.5,
},
chat_channels: vec![],
voice_worker: WorkerSettings {
python: if cfg!(windows) { "python.exe".into() } else { "python3".into() },
cwd: worker_cwd_for(std::env::current_exe().ok().as_deref()),
args: vec![],
},
call: CallSettings::default(),
chat_wake_words: None,
response: PolicySettings::default(),
memory: Map::new(),
llm: LlmSettings { url: None, port: 8080, context: 32768 },
features: FeatureSettings { weather: true, web_search: true, meals: true, collect: true, browser: true, browser_share: false, schedule: true, notes: true, screen: true, pc_control: true },
mcp_servers: vec![],
collect: CollectSettings { keep_days: 30, targets: vec![], notify_channel: None, digest_hour: 9 },
game: GameSettings { detect: true, games: vec![], not_games: vec![], other_room_gb: 1.0, reserve_gb: 8.0, revert_seconds: 30, pause_in_game: false },
schedule_channel: None,
pc_control: PcControlSettings { allowed_users: vec![], view: Level::Auto, click: Level::Ask,
type_text: Level::Ask, run: Level::Ask,
screen_exclude: ["1Password", "Bitwarden", "KeePass", "KeePassXC"].map(String::from).into(),
anti_cheat_games: vec![], stop_hotkey: crate::pc::DEFAULT_STOP_HOTKEY.into() },
close_to_tray: false,
location: Some(DEFAULT_LOCATION.into()),
}
}
}
/// Where the worker's Python sources (`voice_worker`, `jarvis`) are by default: `python-src` next to
/// the app's executable (the Windows build ships them there), else the repository's `src/` next to
/// this crate (development and tests).
pub fn worker_cwd_for(exe: Option<&Path>) -> PathBuf {
if let Some(shipped) = exe.and_then(Path::parent).map(|d| d.join("python-src")) {
if shipped.join("voice_worker").is_dir() {
return shipped;
}
}
Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("src")
}
/// The worker's Python sources: the ones shipped next to the app's executable always win, so an
/// update or a second install never runs the older sources a `voiceWorker.cwd` written by another
/// install points at; without shipped sources the stored folder, else the default.
pub fn worker_cwd(stored: Option<PathBuf>, exe: Option<&Path>) -> PathBuf {
let shipped = exe.and_then(Path::parent).map(|d| d.join("python-src")).filter(|p| p.join("voice_worker").is_dir());
shipped.or(stored).unwrap_or_else(|| worker_cwd_for(exe))
}
impl Settings {
/// The voice worker's arguments: `voiceWorker.args`, plus the voice speed when it speaks
/// (`--melo-python`) and the arguments do not set one themselves.
pub fn worker_args(&self) -> Vec<String> {
let mut a = self.voice_worker.args.clone();
if a.iter().any(|x| x == "--melo-python") && !a.iter().any(|x| x == "--melo-speed") {
a.extend(["--melo-speed".to_string(), self.voice.tts_speed.to_string()]);
}
a
}
}
fn err<T>(msg: impl Into<String>) -> Result<T, SettingsError> {
Err(SettingsError(msg.into()))
}
fn section<'a>(raw: &'a Map<String, Value>, key: &str) -> Result<Option<&'a Map<String, Value>>, SettingsError> {
match raw.get(key) {
None => Ok(None),
Some(Value::Object(m)) => Ok(Some(m)),
Some(_) => err(format!("{key} must be an object")),
}
}
/// A Discord ID: a JSON string of 17-20 digits (numbers would lose precision in JSON).
fn snowflake(v: &Value) -> Option<u64> {
let s = v.as_str()?;
if !(17..=20).contains(&s.len()) || !s.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
s.parse().ok()
}
fn opt_snowflake(m: Option<&Map<String, Value>>, key: &str, path: &str, default: Option<u64>, what: &str)
-> Result<Option<u64>, SettingsError> {
match m.and_then(|m| m.get(key)) {
None => Ok(default),
Some(Value::Null) => Ok(None),
Some(v) => snowflake(v).map(Some).ok_or_else(|| SettingsError(format!("{path}.{key} must be {what} or null"))),
}
}
fn get_str(m: Option<&Map<String, Value>>, key: &str, path: &str, default: &str) -> Result<String, SettingsError> {
match m.and_then(|m| m.get(key)) {
None => Ok(default.to_owned()),
Some(Value::String(s)) => Ok(s.clone()),
Some(_) => err(format!("{path}.{key} must be a string")),
}
}
fn get_bool(m: Option<&Map<String, Value>>, key: &str, path: &str, default: bool) -> Result<bool, SettingsError> {
match m.and_then(|m| m.get(key)) {
None => Ok(default),
Some(Value::Bool(b)) => Ok(*b),
Some(_) => err(format!("{path}.{key} must be true or false")),
}
}
fn get_str_list(m: Option<&Map<String, Value>>, key: &str, path: &str, default: &[String])
-> Result<Vec<String>, SettingsError> {
match m.and_then(|m| m.get(key)) {
None => Ok(default.to_vec()),
Some(Value::Array(a)) => a
.iter()
.map(|v| v.as_str().map(str::to_owned))
.collect::<Option<Vec<_>>>()
.ok_or_else(|| SettingsError(format!("{path}.{key} must be a list of strings"))),
Some(_) => err(format!("{path}.{key} must be a list of strings")),
}
}
fn get_ms(m: Option<&Map<String, Value>>, key: &str, path: &str, default: Duration, max: u64)
-> Result<Duration, SettingsError> {
match m.and_then(|m| m.get(key)) {
None => Ok(default),
Some(v) => match v.as_u64() {
Some(n) if n <= max => Ok(Duration::from_millis(n)),
_ => err(format!("{path}.{key} must be an integer 0-{max} (milliseconds)")),
},
}
}
fn snowflake_list(m: Option<&Map<String, Value>>, key: &str, path: &str) -> Result<Vec<u64>, SettingsError> {
match m.and_then(|m| m.get(key)) {
None => Ok(vec![]),
Some(Value::Array(a)) => a
.iter()
.map(snowflake)
.collect::<Option<Vec<_>>>()
.ok_or_else(|| SettingsError(format!("{path}.{key} must be a list of Discord user IDs"))),
Some(_) => err(format!("{path}.{key} must be a list of Discord user IDs")),
}
}
fn clean_words(words: Vec<String>) -> Vec<String> {
words.into_iter().map(|w| w.trim().to_owned()).filter(|w| !w.is_empty()).collect()
}
fn parse_call(raw: &Map<String, Value>, wake_words: &[String], d: &CallSettings)
-> Result<(CallSettings, Option<Vec<String>>), SettingsError> {
let call = section(raw, "call")?;
let similarity = match call.and_then(|m| m.get("similarity")) {
None => d.similarity,
Some(v) => match v.as_f64() {
Some(x) if (0.0..=0.5).contains(&x) => x,
_ => return err("call.similarity must be a number 0-0.5"),
},
};
let mode = match get_str(call, "mode", "call", "wakeWord")?.as_str() {
"wakeWord" => CallMode::WakeWord,
"addressed" => CallMode::Addressed,
"everything" => CallMode::Everything,
_ => return err("call.mode must be wakeWord, addressed or everything"),
};
let chat_wake_words = match call.and_then(|m| m.get("chatWakeWords")) {
None | Some(Value::Null) => None,
Some(_) => Some(clean_words(get_str_list(call, "chatWakeWords", "call", &[])?)),
};
let stop_words = clean_words(get_str_list(call, "stopWords", "call", &d.stop_words)?);
Ok((
CallSettings {
wake_words: wake_words.to_vec(),
similarity,
mode,
designated: snowflake_list(call, "designated", "call")?.into_iter().collect(),
designated_only: get_bool(call, "designatedOnly", "call", d.designated_only)?,
designated_no_wake_word: get_bool(call, "designatedNoWakeWord", "call", d.designated_no_wake_word)?,
stop_words,
follow_up: get_ms(call, "followUpMs", "call", d.follow_up, 5000)?,
continue_window: get_ms(call, "continueMs", "call", d.continue_window, 15000)?,
answer_wait: get_ms(call, "answerWaitMs", "call", d.answer_wait, 10000)?,
earcon: get_bool(call, "earcon", "call", d.earcon)?,
},
chat_wake_words,
))
}
fn parse_response(raw: &Map<String, Value>, d: &PolicySettings) -> Result<PolicySettings, SettingsError> {
let r = section(raw, "response")?;
let kind = match get_str(r, "policy", "response", "latest")?.as_str() {
"first" => PolicyKind::First,
"inOrder" => PolicyKind::InOrder,
"latest" => PolicyKind::Latest,
"important" => PolicyKind::Important,
_ => return err("response.policy must be first, inOrder, latest or important"),
};
let queue_max = match r.and_then(|m| m.get("queueMax")) {
None => d.queue_max,
Some(v) => match v.as_u64() {
Some(n @ 1..=20) => n as usize,
_ => return err("response.queueMax must be an integer 1-20"),
},
};
let mut priorities = HashMap::new();
match r.and_then(|m| m.get("priorities")) {
None => {}
Some(Value::Object(p)) => {
for (k, v) in p {
let id = snowflake(&Value::String(k.clone()))
.ok_or_else(|| SettingsError("response.priorities keys must be Discord user IDs".into()))?;
let n = v.as_i64().ok_or_else(|| SettingsError("response.priorities values must be integers".into()))?;
priorities.insert(id, n);
}
}
Some(_) => return err("response.priorities must be an object of user ID to priority"),
}
Ok(PolicySettings {
kind,
queue_max,
collect: get_ms(r, "collectMs", "response", d.collect, 3000)?,
settle: get_ms(r, "settleMs", "response", d.settle, 3000)?,
priorities,
rank_timeout: d.rank_timeout,
interrupt: get_bool(r, "interrupt", "response", d.interrupt)?,
})
}
/// Discord's rule for command names: 1-32 lowercase letters, digits, `-` or `_`.
fn valid_command_name(s: &str) -> bool {
let n = s.chars().count();
(1..=32).contains(&n)
&& s.chars().all(|c| c == '-' || c == '_' || c.is_alphanumeric())
&& s.to_lowercase() == s
}
/// Validate a parsed settings document over the defaults.
pub fn parse_settings(raw: &Value) -> Result<Settings, SettingsError> {
let d = Settings::default();
let Value::Object(raw) = raw else { return err("settings must be a JSON object") };
let disc = section(raw, "discord")?;
let voice = section(raw, "voice")?;
let worker = section(raw, "voiceWorker")?;
let command_name = get_str(disc, "commandName", "discord", &d.discord.command_name)?;
if !valid_command_name(&command_name) {
return err("discord.commandName must be 1-32 lowercase letters, digits, - or _");
}
let max_speakers = match voice.and_then(|m| m.get("maxSpeakers")) {
None => d.voice.max_speakers,
Some(v) => match v.as_u64() {
Some(n @ 1..=10) => n as usize,
_ => return err("voice.maxSpeakers must be an integer 1-10"),
},
};
let wake_words = clean_words(get_str_list(voice, "wakeWords", "voice", &d.voice.wake_words)?);
let (call, chat_wake_words) = parse_call(raw, &wake_words, &d.call)?;
let response = parse_response(raw, &d.response)?;
let join_notice = get_str(voice, "joinNotice", "voice", &d.voice.join_notice)?.trim().to_owned();
if join_notice.is_empty() {
return err("voice.joinNotice must not be empty: people must be told they are transcribed");
}
if join_notice.encode_utf16().count() > 2000 {
return err("voice.joinNotice must be at most 2000 characters");
}
let tts_speed = match voice.and_then(|m| m.get("tts")) {
None => d.voice.tts_speed,
Some(Value::Object(t)) => match t.get("speed") {
None => d.voice.tts_speed,
Some(v) => match v.as_f64() {
Some(x) if (0.5..=2.0).contains(&x) => x,
_ => return err("voice.tts.speed must be a number 0.5-2.0"),
},
},
Some(_) => return err("voice.tts must be an object"),
};
let stt = match voice.and_then(|m| m.get("stt")) {
None => d.voice.stt.clone(),
Some(Value::Object(m)) => m.clone(),
Some(_) => return err("voice.stt must be an object"),
};
let chat_raw = match raw.get("chatChannels") {
None => vec![],
Some(Value::Array(a)) => a.clone(),
Some(_) => return err("chatChannels must be a list"),
};
let mut chat_channels: Vec<ChatChannelSettings> = Vec::new();
for (i, c) in chat_raw.iter().enumerate() {
let path = format!("chatChannels[{i}]");
let Value::Object(m) = c else { return err(format!("{path} must be an object")) };
let id = m.get("id").and_then(snowflake).ok_or_else(|| SettingsError(format!("{path}.id must be a Discord channel ID")))?;
if chat_channels.iter().any(|c| c.id == id) {
return err(format!("{path}.id is listed twice"));
}
chat_channels.push(ChatChannelSettings {
id,
name: get_str(Some(m), "name", &path, "")?,
description: get_str(Some(m), "description", &path, "")?,
read: get_bool(Some(m), "read", &path, true)?,
send: get_bool(Some(m), "send", &path, true)?,
edit: get_bool(Some(m), "edit", &path, true)?,
react: get_bool(Some(m), "react", &path, true)?,
delete: get_bool(Some(m), "delete", &path, false)?,
pin: get_bool(Some(m), "pin", &path, false)?,
answer_all: match get_str(Some(m), "answer", &path, "wakeWord")?.as_str() {
"wakeWord" => false,
"everything" => true,
_ => return err(format!("{path}.answer must be wakeWord or everything")),
},
sync_discord: get_bool(Some(m), "syncDiscord", &path, true)?,
});
}
let collect = parse_collect(raw, &d.collect)?;
if collect.notify_channel.is_some_and(|c| !chat_channels.iter().any(|x| x.id == c && x.send)) {
return err("collect.notifyChannel must be a registered chat channel with sending on");
}
let schedule_channel = opt_snowflake(section(raw, "schedule")?, "chatChannel", "schedule", None, "a Discord channel ID")?;
if schedule_channel.is_some_and(|c| !chat_channels.iter().any(|x| x.id == c && x.send)) {
return err("schedule.chatChannel must be a registered chat channel with sending on");
}
Ok(Settings {
discord: DiscordSettings {
guild_id: opt_snowflake(disc, "guildId", "discord", d.discord.guild_id, "a Discord server ID")?,
voice_channel_id: opt_snowflake(disc, "voiceChannelId", "discord", d.discord.voice_channel_id,
"a Discord channel ID")?,
command_name,
ephemeral_replies: get_bool(disc, "ephemeralReplies", "discord", d.discord.ephemeral_replies)?,
},
voice: VoiceSettings {
max_speakers,
listen_to_bots: get_bool(voice, "listenToBots", "voice", d.voice.listen_to_bots)?,
record: get_bool(voice, "record", "voice", d.voice.record)?,
join_notice,
wake_words,
stt,
tts_speed,
},
chat_channels,
voice_worker: WorkerSettings {
python: get_str(worker, "python", "voiceWorker", &d.voice_worker.python)?,
cwd: worker_cwd(match worker.and_then(|m| m.get("cwd")) {
None => None,
Some(Value::String(s)) => Some(PathBuf::from(s)),
Some(_) => return err("voiceWorker.cwd must be a string"),
}, std::env::current_exe().ok().as_deref()),
args: get_str_list(worker, "args", "voiceWorker", &d.voice_worker.args)?,
},
call,
chat_wake_words,
response,
memory: match raw.get("memory") {
None => Map::new(),
Some(Value::Object(m)) => m.clone(),
Some(_) => return err("memory must be an object"),
},
llm: parse_llm(raw, &d.llm)?,
features: {
let f = section(raw, "features")?;
FeatureSettings {
weather: get_bool(f, "weather", "features", d.features.weather)?,
web_search: get_bool(f, "webSearch", "features", d.features.web_search)?,
meals: get_bool(f, "meals", "features", d.features.meals)?,
collect: get_bool(f, "collect", "features", d.features.collect)?,
browser: get_bool(f, "browser", "features", d.features.browser)?,
browser_share: get_bool(f, "browserShare", "features", d.features.browser_share)?,
schedule: get_bool(f, "schedule", "features", d.features.schedule)?,
notes: get_bool(f, "notes", "features", d.features.notes)?,
screen: get_bool(f, "screen", "features", d.features.screen)?,
pc_control: get_bool(f, "pcControl", "features", d.features.pc_control)?,
}
},
mcp_servers: parse_mcp_servers(raw)?,
collect,
game: parse_game(raw, &d.game)?,
schedule_channel,
pc_control: parse_pc_control(raw, &d.pc_control)?,
close_to_tray: match get_str(section(raw, "app")?, "closeButton", "app", "quit")?.as_str() {
"tray" => true,
"quit" => false,
_ => return err("app.closeButton must be tray or quit"),
},
location: {
let l = get_str(section(raw, "brain")?, "location", "brain", DEFAULT_LOCATION)?.trim().to_owned();
if l.chars().count() > 100 {
return err("brain.location must be at most 100 characters");
}
(!l.is_empty()).then_some(l)
},
})
}
fn parse_pc_control(raw: &Map<String, Value>, d: &PcControlSettings) -> Result<PcControlSettings, SettingsError> {
let p = section(raw, "pcControl")?;
let level = |key: &str, default: Level| -> Result<Level, SettingsError> {
match p.and_then(|m| m.get(key)) {
None => Ok(default),
Some(Value::String(v)) if v == "auto" => Ok(Level::Auto),
Some(Value::String(v)) if v == "ask" => Ok(Level::Ask),
Some(Value::String(v)) if v == "never" => Ok(Level::Never),
Some(_) => err(format!("pcControl.{key} must be auto, ask or never")),
}
};
let programs = |key: &str, default: &[String]| -> Result<Vec<String>, SettingsError> {
let v: Vec<String> = get_str_list(p, key, "pcControl", default)?.into_iter()
.map(|e| e.trim().to_owned()).filter(|e| !e.is_empty()).collect();
if v.len() > 100 || v.iter().any(|e| e.chars().count() > 100 || e.contains(['\\', '/'])) {
return err(format!("pcControl.{key} must be at most 100 program names (no folders)"));
}
Ok(v)
};
let stop_hotkey = get_str(p, "stopHotkey", "pcControl", &d.stop_hotkey)?.trim().to_owned();
if crate::pc::parse_hotkey(&stop_hotkey).is_none() {
return err("pcControl.stopHotkey must be modifiers and a key, such as Ctrl+Shift+F12");
}
Ok(PcControlSettings {
allowed_users: snowflake_list(p, "allowedUsers", "pcControl")?,
view: level("view", d.view)?,
click: level("click", d.click)?,
type_text: level("type", d.type_text)?,
run: level("run", d.run)?,
screen_exclude: programs("screenExclude", &d.screen_exclude)?,
anti_cheat_games: programs("antiCheatGames", &d.anti_cheat_games)?,
stop_hotkey,
})
}
/// A collection target's name: 1-32 letters, digits, `-` or `_` in any script. It names the
/// target's folder, so a Windows device name (`con`, `nul`, `com1`, ...) is refused.
pub fn valid_collect_name(s: &str) -> bool {
let n = s.chars().count();
let lower = s.to_ascii_lowercase();
let device = ["con", "prn", "aux", "nul"].contains(&lower.as_str())
|| (lower.len() == 4 && (lower.starts_with("com") || lower.starts_with("lpt"))
&& lower.as_bytes()[3].is_ascii_digit());
(1..=32).contains(&n) && s.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_') && !device
}
fn get_uint(m: Option<&Map<String, Value>>, key: &str, path: &str, default: u32, min: u32, max: u32)
-> Result<u32, SettingsError> {
match m.and_then(|m| m.get(key)) {
None => Ok(default),
Some(v) => match v.as_u64() {
Some(n) if (min as u64..=max as u64).contains(&n) => Ok(n as u32),
_ => err(format!("{path}.{key} must be an integer {min}-{max}")),
},
}
}
fn parse_game(raw: &Map<String, Value>, d: &GameSettings) -> Result<GameSettings, SettingsError> {
let g = section(raw, "game")?;
let list = |key: &str, default: &[String]| -> Result<Vec<String>, SettingsError> {
let v: Vec<String> = get_str_list(g, key, "game", default)?.into_iter().map(|e| e.trim().to_owned())
.filter(|e| !e.is_empty()).collect();
if v.len() > 100 || v.iter().any(|e| e.chars().count() > 100 || e.contains(['\\', '/'])) {
return err(format!("game.{key} must be at most 100 program names (no folders)"));
}
Ok(v)
};
let gb = |key: &str, default: f64, max: f64| -> Result<f64, SettingsError> {
match g.and_then(|m| m.get(key)) {
None => Ok(default),
Some(v) => match v.as_f64() {
Some(n) if (0.0..=max).contains(&n) => Ok(n),
_ => err(format!("game.{key} must be a number 0-{max} (GB)")),
},
}
};
let other_room_gb = gb("otherRoomGb", d.other_room_gb, 8.0)?;
let reserve_gb = gb("reserveGb", d.reserve_gb, 32.0)?;
let revert_seconds = get_uint(g, "revertSeconds", "game", d.revert_seconds, 0, 600)?;
Ok(GameSettings { detect: get_bool(g, "detect", "game", d.detect)?, games: list("games", &d.games)?,
not_games: list("notGames", &d.not_games)?, other_room_gb, reserve_gb, revert_seconds,
pause_in_game: get_bool(g, "pauseInGame", "game", d.pause_in_game)? })
}
fn parse_collect(raw: &Map<String, Value>, d: &CollectSettings) -> Result<CollectSettings, SettingsError> {
let c = section(raw, "collect")?;
let keep_days = get_uint(c, "keepDays", "collect", d.keep_days, 1, 365)?;
let notify_channel = opt_snowflake(c, "notifyChannel", "collect", d.notify_channel, "a Discord channel ID")?;
let digest_hour = get_uint(c, "digestHour", "collect", d.digest_hour, 0, 23)?;
let list = match c.and_then(|m| m.get("targets")) {
None => return Ok(CollectSettings { keep_days, targets: vec![], notify_channel, digest_hour }),
Some(Value::Array(a)) => a,
Some(_) => return err("collect.targets must be a list"),
};
let mut targets: Vec<CollectTarget> = Vec::new();
for (i, v) in list.iter().enumerate() {
let path = format!("collect.targets[{i}]");
let Value::Object(m) = v else { return err(format!("{path} must be an object")) };
let name = get_str(Some(m), "name", &path, "")?.trim().to_owned();
if !valid_collect_name(&name) {
return err(format!("{path}.name must be 1-32 letters, digits, - or _ (not a device name like con)"));
}
// Windows folder names ignore case: `News` and `news` would share one folder and state.
if targets.iter().any(|t| t.name.to_lowercase() == name.to_lowercase()) {
return err(format!("{path}.name is listed twice (names that differ only in case count as the same)"));
}
let kind = get_str(Some(m), "kind", &path, "")?;
let value = get_str(Some(m), "value", &path, "")?.trim().to_owned();
let ok = match kind.as_str() {
"site" | "rss" => (value.starts_with("http://") || value.starts_with("https://")) && value.len() <= 2000,
"search" => (1..=200).contains(&value.chars().count()),
_ => return err(format!("{path}.kind must be site, search or rss")),
};
if !ok {
return err(format!("{path}.value must be an http(s) address (site, rss) or 1-200 characters of words (search)"));
}
targets.push(CollectTarget {
name,
kind,
value,
every_minutes: get_uint(Some(m), "everyMinutes", &path, 60, 15, 10080)?,
enabled: get_bool(Some(m), "enabled", &path, true)?,
notify: match get_str(Some(m), "notify", &path, "off")?.as_str() {
n @ ("off" | "now" | "daily") => n.to_owned(),
_ => return err(format!("{path}.notify must be off, now or daily")),
},
});
}
Ok(CollectSettings { keep_days, targets, notify_channel, digest_hour })
}
/// An MCP server name: 1-32 letters, digits, `-` or `_`, without `__` (the brain names a server's
/// tools `<server>__<tool>`).
fn valid_mcp_name(s: &str) -> bool {
(1..=32).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') && !s.contains("__")
}
/// An environment variable name: a letter or `_`, then letters, digits or `_`.
fn valid_env_name(s: &str) -> bool {
let mut b = s.bytes();
b.next().is_some_and(|c| c.is_ascii_alphabetic() || c == b'_') && b.all(|c| c.is_ascii_alphanumeric() || c == b'_')
&& s.len() <= 64
}
fn parse_mcp_servers(raw: &Map<String, Value>) -> Result<Vec<McpServerSettings>, SettingsError> {
let list = match raw.get("mcpServers") {
None => return Ok(vec![]),
Some(Value::Array(a)) => a,
Some(_) => return err("mcpServers must be a list"),
};
let mut out: Vec<McpServerSettings> = Vec::new();
for (i, v) in list.iter().enumerate() {
let path = format!("mcpServers[{i}]");
let Value::Object(m) = v else { return err(format!("{path} must be an object")) };
let name = get_str(Some(m), "name", &path, "")?.trim().to_owned();
if !valid_mcp_name(&name) {
return err(format!("{path}.name must be 1-32 letters, digits, - or _ (no __)"));
}
if out.iter().any(|s| s.name == name) {
return err(format!("{path}.name is listed twice"));
}
let command = get_str(Some(m), "command", &path, "")?.trim().to_owned();
if command.is_empty() {
return err(format!("{path}.command must not be empty"));
}
let env = clean_words(get_str_list(Some(m), "env", &path, &[])?);
if let Some(bad) = env.iter().find(|n| !valid_env_name(n)) {
return err(format!("{path}.env has a name that is not an environment variable: {bad}"));
}
if env.iter().enumerate().any(|(j, n)| env[..j].contains(n)) {
return err(format!("{path}.env lists a name twice"));
}
out.push(McpServerSettings {
name,
command,
args: get_str_list(Some(m), "args", &path, &[])?,
env,
enabled: get_bool(Some(m), "enabled", &path, true)?,
});
}
Ok(out)
}
fn parse_llm(raw: &Map<String, Value>, d: &LlmSettings) -> Result<LlmSettings, SettingsError> {
let l = section(raw, "llm")?;
let url = match l.and_then(|m| m.get("url")) {
None | Some(Value::Null) => None,
Some(Value::String(s)) if s.starts_with("http://") || s.starts_with("https://") => Some(s.trim_end_matches('/').to_owned()),
Some(_) => return err("llm.url must be an http(s) address or null"),
};
let port = match l.and_then(|m| m.get("port")) {
None => d.port,
Some(v) => match v.as_u64() {
Some(n @ 1024..=65535) => n as u16,
_ => return err("llm.port must be an integer 1024-65535"),
},
};
let context = match l.and_then(|m| m.get("context")) {
None => d.context,
Some(v) => match v.as_u64() {
Some(n @ 4096..=262144) => n as u32,
_ => return err("llm.context must be an integer 4096-262144"),
},
};
Ok(LlmSettings { url, port, context })
}
/// Read and validate the settings file. A missing file means all defaults.
pub fn load_settings(path: &Path) -> Result<Settings, SettingsError> {
let text = match std::fs::read_to_string(path) {
Ok(t) => t,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Settings::default()),
Err(e) => return err(format!("could not read {}: {e}", path.display())),
};
let raw: Value = serde_json::from_str(text.trim_start_matches('\u{feff}'))
.map_err(|e| SettingsError(format!("{} is not valid JSON: {e}", path.display())))?;
parse_settings(&raw)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn the_tts_speed_reaches_the_worker_when_it_speaks() {
let melo = json!({"voiceWorker": {"args": ["--melo-python", "/m/python", "--brain"]}});
let s = parse_settings(&melo).unwrap();
let speed = |a: &[String]| a.iter().position(|x| x == "--melo-speed").map(|i| a[i + 1].clone());
assert_eq!(speed(&s.worker_args()), Some(s.voice.tts_speed.to_string()), "the default speed");
let mut fast = melo.clone();
fast["voice"] = json!({"tts": {"speed": 1.8}});
assert_eq!(speed(&parse_settings(&fast).unwrap().worker_args()).as_deref(), Some("1.8"));
assert!(speed(&Settings::default().worker_args()).is_none(), "no TTS, no speed");
for bad in [json!(0.2), json!(3), json!("fast")] {
assert!(parse_settings(&json!({"voice": {"tts": {"speed": bad}}})).unwrap_err().0.contains("voice.tts.speed"));
}
}
#[test]
fn the_python_sources_shipped_next_to_the_app_win_over_the_repository() {
let dir = crate::datadir::temp_dir("pysrc");
let exe = dir.join("jarvis.exe");
assert!(worker_cwd_for(Some(&exe)).ends_with("src"), "nothing shipped: the repository's src/");
std::fs::create_dir_all(dir.join("python-src").join("voice_worker")).unwrap();
assert_eq!(worker_cwd_for(Some(&exe)), dir.join("python-src"));
assert_eq!(worker_cwd_for(None), Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("src"));
}
#[test]
fn a_worker_folder_stored_by_another_install_never_beats_the_sources_shipped_with_this_app() {
// The first-run setup of one install wrote its folder; this app (installed elsewhere, or
// updated) must still run its own sources, never the other install's older ones.
let dir = crate::datadir::temp_dir("pysrc-stored");
let exe = dir.join("jarvis.exe");
let other = PathBuf::from("C:/old-install/python-src");
assert_eq!(worker_cwd(Some(other.clone()), Some(&exe)), other, "nothing shipped: the stored folder");
std::fs::create_dir_all(dir.join("python-src").join("voice_worker")).unwrap();
assert_eq!(worker_cwd(Some(other), Some(&exe)), dir.join("python-src"));
assert_eq!(worker_cwd(None, Some(&exe)), dir.join("python-src"));
}
const ID: &str = "123456789012345678";
const IDN: u64 = 123456789012345678;
#[test]
fn empty_document_and_missing_file_give_the_defaults() {
assert_eq!(parse_settings(&json!({})).unwrap(), Settings::default());
let dir = std::env::temp_dir().join(format!("jarvis-settings-{}", std::process::id()));
assert_eq!(load_settings(&dir.join("nope.json")).unwrap(), Settings::default());
}
#[test]
fn by_default_only_the_latest_call_is_answered() {
assert_eq!(parse_settings(&json!({})).unwrap().response.kind, PolicyKind::Latest);
}
#[test]
fn reads_a_full_file_with_bom() {
let dir = std::env::temp_dir().join(format!("jarvis-settings-full-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("settings.json");
let doc = json!({
"discord": {"guildId": ID, "voiceChannelId": ID, "commandName": "jarvis", "ephemeralReplies": false},
"voice": {"maxSpeakers": 3, "listenToBots": true, "record": true, "joinNotice": "알림", "wakeWords": [" 자비스 ", "", "javis"],
"stt": {"end_silence_ms": 250}},
"chatChannels": [{"id": ID, "name": "일정", "description": "일정 올리는 곳", "send": false}],
"voiceWorker": {"python": "/venv/bin/python", "cwd": "/repo/src", "args": ["--melo-python", "/m/python"]},
"somethingNew": 1
});
std::fs::write(&path, format!("\u{feff}{doc}")).unwrap();
let s = load_settings(&path).unwrap();
std::fs::remove_dir_all(&dir).ok();
assert_eq!(s.discord, DiscordSettings { guild_id: Some(IDN), voice_channel_id: Some(IDN),
command_name: "jarvis".into(), ephemeral_replies: false });
assert_eq!(s.voice.max_speakers, 3);
assert!(s.voice.listen_to_bots);
assert!(s.voice.record);
assert!(!parse_settings(&json!({})).unwrap().voice.record, "off by default");
assert_eq!(s.voice.join_notice, "알림");
assert_eq!(s.voice.wake_words, vec!["자비스", "javis"]);
assert_eq!(s.voice.stt.get("end_silence_ms"), Some(&json!(250)));
assert_eq!(s.chat_channels, vec![ChatChannelSettings { id: IDN, name: "일정".into(),
description: "일정 올리는 곳".into(), read: true, send: false, edit: true, react: true, delete: false,
pin: false, answer_all: false, sync_discord: true }]);
assert_eq!(s.voice_worker.args, vec!["--melo-python", "/m/python"]);
assert_eq!(s.voice_worker.cwd, PathBuf::from("/repo/src"));
}
#[test]
fn bad_values_are_refused_with_the_key() {
let cases = [
(json!({"discord": {"guildId": "abc"}}), "discord.guildId"),
(json!({"discord": {"guildId": 123456789012345678u64}}), "discord.guildId"),
(json!({"discord": {"commandName": "Jarvis"}}), "commandName"),
(json!({"discord": {"commandName": "두 단어"}}), "commandName"),
(json!({"voice": {"maxSpeakers": 11}}), "maxSpeakers"),
(json!({"voice": {"maxSpeakers": 0}}), "maxSpeakers"),
(json!({"voice": {"joinNotice": " "}}), "joinNotice"),
(json!({"chatChannels": [{"id": ID}, {"id": ID}]}), "twice"),
(json!({"chatChannels": [{"id": "1"}]}), "chatChannels[0].id"),
(json!({"chatChannels": {}}), "chatChannels"),
(json!({"chatChannels": [{"id": ID, "answer": "sometimes"}]}), "chatChannels[0].answer"),
(json!({"voice": []}), "voice"),
(json!([]), "object"),
];
for (raw, key) in cases {
let e = parse_settings(&raw).unwrap_err();
assert!(e.0.contains(key), "{raw} -> {e}");
}
}
#[test]
fn call_and_response_sections_are_read_and_checked() {
let s = parse_settings(&json!({
"voice": {"wakeWords": ["자비스", "javis"]},
"call": {"similarity": 0.3, "mode": "addressed", "designated": [ID], "designatedOnly": true,
"designatedNoWakeWord": true, "stopWords": ["멈춰", " "], "chatWakeWords": ["봇"],
"followUpMs": 2500, "earcon": false},
"response": {"policy": "important", "queueMax": 3, "collectMs": 500, "settleMs": 0, "interrupt": false,
"priorities": {ID: 2}}
})).unwrap();
assert_eq!(s.call.wake_words, vec!["자비스", "javis"]);
assert_eq!(s.call.similarity, 0.3);
assert_eq!(s.call.mode, CallMode::Addressed);
assert!(s.call.designated.contains(&IDN));
assert!(s.call.designated_only && s.call.designated_no_wake_word);
assert_eq!(s.call.stop_words, vec!["멈춰"]);
assert_eq!(s.chat_wake_words, Some(vec!["봇".to_string()]));
assert_eq!(s.call.follow_up, Duration::from_millis(2500));
assert!(!s.call.earcon);
assert!(parse_settings(&json!({})).unwrap().call.earcon, "on by default");
assert_eq!(s.response.kind, PolicyKind::Important);
assert_eq!(s.response.queue_max, 3);
assert_eq!(s.response.collect, Duration::from_millis(500));
assert_eq!(s.response.settle, Duration::ZERO);
assert!(!s.response.interrupt);
assert!(parse_settings(&json!({})).unwrap().response.interrupt, "on by default");
assert_eq!(s.response.priorities.get(&IDN), Some(&2));
let s = parse_settings(&json!({"chatChannels": [{"id": ID, "answer": "everything"}]})).unwrap();
assert!(s.chat_channels[0].answer_all);
let cases = [
(json!({"call": {"similarity": 0.9}}), "call.similarity"),
(json!({"call": {"mode": "sometimes"}}), "call.mode"),
(json!({"call": {"designated": ["1"]}}), "call.designated"),
(json!({"call": {"followUpMs": 6000}}), "call.followUpMs"),
(json!({"call": {"earcon": "yes"}}), "call.earcon"),
(json!({"response": {"policy": "random"}}), "response.policy"),
(json!({"response": {"queueMax": 0}}), "response.queueMax"),
(json!({"response": {"interrupt": "yes"}}), "response.interrupt"),
(json!({"response": {"collectMs": 5000}}), "response.collectMs"),
(json!({"response": {"priorities": {"x": 1}}}), "response.priorities"),
];
for (raw, key) in cases {
let e = parse_settings(&raw).unwrap_err();
assert!(e.0.contains(key), "{raw} -> {e}");
}
}
#[test]
fn the_close_button_choice_is_read_and_checked() {
assert!(!parse_settings(&json!({})).unwrap().close_to_tray, "closing quits by default");
assert_eq!(parse_settings(&json!({})).unwrap().location.as_deref(), Some(DEFAULT_LOCATION));
assert_eq!(parse_settings(&json!({"brain": {"location": " 부산 "}})).unwrap().location.as_deref(), Some("부산"));
assert_eq!(parse_settings(&json!({"brain": {"location": " "}})).unwrap().location, None, "empty: the brain detects it");
for bad in [json!({"brain": {"location": 1}}), json!({"brain": {"location": "가".repeat(101)}}), json!({"brain": 1})] {
assert!(parse_settings(&bad).unwrap_err().0.contains("brain"), "{bad}");
}
assert!(parse_settings(&json!({"app": {"closeButton": "tray"}})).unwrap().close_to_tray);
assert!(!parse_settings(&json!({"app": {"closeButton": "quit"}})).unwrap().close_to_tray);
for bad in [json!({"app": {"closeButton": "hide"}}), json!({"app": {"closeButton": 1}}), json!({"app": 1})] {
assert!(parse_settings(&bad).unwrap_err().0.contains("app"), "{bad}");
}
}
#[test]
fn game_detection_settings_are_read_and_checked() {
assert_eq!(parse_settings(&json!({})).unwrap().game, GameSettings { detect: true, games: vec![], not_games: vec![], other_room_gb: 1.0, reserve_gb: 8.0, revert_seconds: 30, pause_in_game: false });
let s = parse_settings(&json!({"game": {"detect": false, "games": [" MyGame.exe ", ""], "notGames": ["obs64"], "otherRoomGb": 2.5, "reserveGb": 6, "revertSeconds": 60, "pauseInGame": true}})).unwrap();
assert_eq!(s.game, GameSettings { detect: false, games: vec!["MyGame.exe".into()], not_games: vec!["obs64".into()], other_room_gb: 2.5,
reserve_gb: 6.0, revert_seconds: 60, pause_in_game: true });
assert_eq!(s.game.reserve_mib(), 6144);
assert_eq!(s.game.other_room_mib(), 2560);
for bad in [json!({"game": {"games": ["C:\\x\\a.exe"]}}), json!({"game": {"notGames": "a"}}), json!({"game": {"detect": 1}}), json!({"game": {"otherRoomGb": 9}}), json!({"game": {"revertSeconds": 601}}), json!({"game": {"reserveGb": -1}})] {
assert!(parse_settings(&bad).unwrap_err().0.contains("game."), "{bad}");
}
}
#[test]
fn features_and_mcp_servers_are_read_and_checked() {
let s = parse_settings(&json!({}));
assert_eq!(s.unwrap().features, FeatureSettings { weather: true, web_search: true, meals: true, collect: true, browser: true, browser_share: false, schedule: true, notes: true, screen: true, pc_control: true });
let s = parse_settings(&json!({
"features": {"weather": false, "meals": false, "browserShare": true, "schedule": false, "notes": false, "screen": false, "pcControl": false},
"mcpServers": [{"name": "brave", "command": "npx", "args": ["-y", "brave"], "env": ["BRAVE_API_KEY", " "]},
{"name": "time-2", "command": "uvx", "enabled": false}]
})).unwrap();
assert_eq!(s.features, FeatureSettings { weather: false, web_search: true, meals: false, collect: true, browser: true, browser_share: true, schedule: false, notes: false, screen: false, pc_control: false });
assert_eq!(s.mcp_servers, vec![
McpServerSettings { name: "brave".into(), command: "npx".into(), args: vec!["-y".into(), "brave".into()],
env: vec!["BRAVE_API_KEY".into()], enabled: true },
McpServerSettings { name: "time-2".into(), command: "uvx".into(), args: vec![], env: vec![], enabled: false },
]);
// PC control: nobody by default, viewing automatic and the rest asked first.
let pc = parse_settings(&json!({})).unwrap().pc_control;
assert!(pc.allowed_users.is_empty());
assert_eq!((pc.view, pc.click, pc.type_text, pc.run), (Level::Auto, Level::Ask, Level::Ask, Level::Ask));
assert!(pc.screen_exclude.contains(&"KeePassXC".to_owned()), "password managers are never seen by default");
assert!(pc.anti_cheat_games.is_empty());
assert_eq!(pc.stop_hotkey, "Ctrl+Shift+F12");
let pc = parse_settings(&json!({"pcControl": {"allowedUsers": ["123456789012345678"], "view": "never",
"click": "auto", "type": "never", "run": "auto", "screenExclude": [" bank.exe ", ""],
"antiCheatGames": ["MyShooter"], "stopHotkey": "Ctrl+Shift+Nope"}})).unwrap_err();
assert!(pc.0.contains("pcControl.stopHotkey"), "{pc}");
let pc = parse_settings(&json!({"pcControl": {"allowedUsers": ["123456789012345678"], "view": "never",
"click": "auto", "type": "never", "run": "auto", "screenExclude": [" bank.exe ", ""],
"antiCheatGames": ["MyShooter"], "stopHotkey": " ctrl+alt+s "}})).unwrap().pc_control;
assert_eq!(pc.allowed_users, vec![123456789012345678]);
assert_eq!(pc.screen_exclude, vec!["bank.exe".to_owned()]);
assert_eq!(pc.anti_cheat_games, vec!["MyShooter".to_owned()]);
assert_eq!(pc.stop_hotkey, "ctrl+alt+s");
assert_eq!((pc.view, pc.click, pc.type_text, pc.run), (Level::Never, Level::Auto, Level::Never, Level::Auto));
for bad in [json!({"pcControl": {"click": "yes"}}), json!({"pcControl": {"allowedUsers": ["1"]}}),
json!({"pcControl": {"screenExclude": ["C:\\bank\\bank.exe"]}}), json!({"pcControl": {"screenExclude": "x"}}),
json!({"pcControl": {"antiCheatGames": ["D:\\games\\x.exe"]}}), json!({"pcControl": {"stopHotkey": "F12"}})] {
assert!(parse_settings(&bad).unwrap_err().0.contains("pcControl."), "{bad}");
}
// A schedule channel must be a registered one that Jarvis may send in.
let ch = json!([{"id": "123456789012345678", "send": true}, {"id": "123456789012345679", "send": false}]);
let s = parse_settings(&json!({"chatChannels": ch, "schedule": {"chatChannel": "123456789012345678"}})).unwrap();
assert_eq!(s.schedule_channel, Some(123456789012345678));
for c in ["123456789012345679", "123456789012345670"] {
let e = parse_settings(&json!({"chatChannels": ch, "schedule": {"chatChannel": c}})).unwrap_err();
assert!(e.0.contains("schedule.chatChannel"), "{e}");
}
let cases = [
(json!({"features": {"weather": "no"}}), "features.weather"),
(json!({"mcpServers": {}}), "mcpServers"),
(json!({"mcpServers": [{"name": "a__b", "command": "x"}]}), "mcpServers[0].name"),
(json!({"mcpServers": [{"name": "", "command": "x"}]}), "mcpServers[0].name"),
(json!({"mcpServers": [{"name": "a b", "command": "x"}]}), "mcpServers[0].name"),
(json!({"mcpServers": [{"name": "a", "command": "x"}, {"name": "a", "command": "y"}]}), "mcpServers[1].name"),
(json!({"mcpServers": [{"name": "a", "command": " "}]}), "mcpServers[0].command"),
(json!({"mcpServers": [{"name": "a", "command": "x", "env": ["1KEY"]}]}), "mcpServers[0].env"),
(json!({"mcpServers": [{"name": "a", "command": "x", "env": ["K", "K"]}]}), "mcpServers[0].env"),
];
for (raw, key) in cases {
let e = parse_settings(&raw).unwrap_err();
assert!(e.0.contains(key), "{raw} -> {e}");
}
}
#[test]
fn collection_targets_are_read_and_checked() {
let s = parse_settings(&json!({})).unwrap();
// News notifications are off by default, with no channel, the digest at 9.
assert_eq!(s.collect, CollectSettings { keep_days: 30, targets: vec![], notify_channel: None, digest_hour: 9 });
let s = parse_settings(&json!({"features": {"collect": false},
"chatChannels": [{"id": "123456789012345678"}],
"collect": {"keepDays": 7, "notifyChannel": "123456789012345678", "digestHour": 21, "targets": [
{"name": "뉴스_1", "kind": "rss", "value": " https://feed.example/rss ", "notify": "daily"},
{"name": "rust", "kind": "search", "value": "rust release", "everyMinutes": 1440, "enabled": false}]}})).unwrap();
assert!(!s.features.collect);
assert_eq!(s.collect, CollectSettings { keep_days: 7, notify_channel: Some(123456789012345678), digest_hour: 21,
targets: vec![
CollectTarget { name: "뉴스_1".into(), kind: "rss".into(), value: "https://feed.example/rss".into(),
every_minutes: 60, enabled: true, notify: "daily".into() },
CollectTarget { name: "rust".into(), kind: "search".into(), value: "rust release".into(),
every_minutes: 1440, enabled: false, notify: "off".into() },
]});
// The channel must be a registered one Jarvis may send in.
for raw in [json!({"collect": {"notifyChannel": "123456789012345678"}}),
json!({"chatChannels": [{"id": "123456789012345678", "send": false}],
"collect": {"notifyChannel": "123456789012345678"}})] {
assert!(parse_settings(&raw).unwrap_err().0.contains("collect.notifyChannel"), "{raw}");
}
let t = |extra: Value| {
let mut m = json!({"name": "a", "kind": "site", "value": "https://a.example"});
m.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
json!({"collect": {"targets": [m]}})
};
let cases = [
(json!({"collect": {"keepDays": 0}}), "collect.keepDays"),
(json!({"collect": {"keepDays": 366}}), "collect.keepDays"),
(json!({"collect": {"targets": {}}}), "collect.targets"),
(t(json!({"name": ""})), "collect.targets[0].name"),
(t(json!({"name": "a/b"})), "collect.targets[0].name"),
(t(json!({"name": "../x"})), "collect.targets[0].name"),
(t(json!({"name": "CON"})), "collect.targets[0].name"),
(t(json!({"name": "com1"})), "collect.targets[0].name"),
(t(json!({"kind": "video"})), "collect.targets[0].kind"),
(t(json!({"value": "ftp://a.example"})), "collect.targets[0].value"),
(t(json!({"kind": "search", "value": " "})), "collect.targets[0].value"),
(t(json!({"everyMinutes": 14})), "collect.targets[0].everyMinutes"),
(t(json!({"everyMinutes": 10081})), "collect.targets[0].everyMinutes"),
(t(json!({"notify": "hourly"})), "collect.targets[0].notify"),
(json!({"collect": {"digestHour": 24}}), "collect.digestHour"),
(json!({"collect": {"targets": [{"name": "a", "kind": "rss", "value": "https://a"},
{"name": "a", "kind": "rss", "value": "https://b"}]}}), "collect.targets[1].name"),
(json!({"collect": {"targets": [{"name": "News", "kind": "rss", "value": "https://a"},
{"name": "news", "kind": "rss", "value": "https://b"}]}}), "collect.targets[1].name"),
];
for (raw, key) in cases {
let e = parse_settings(&raw).unwrap_err();
assert!(e.0.contains(key), "{raw} -> {e}");
}
assert!(valid_collect_name("console") && valid_collect_name("com") && valid_collect_name("날씨-서울"));
}
#[test]
fn null_ids_clear_them() {
let s = parse_settings(&json!({"discord": {"guildId": null, "voiceChannelId": null}})).unwrap();
assert_eq!((s.discord.guild_id, s.discord.voice_channel_id), (None, None));
}
#[test]
fn invalid_json_names_the_file() {
let dir = std::env::temp_dir().join(format!("jarvis-settings-bad-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("settings.json");
std::fs::write(&path, "{ nope").unwrap();
let e = load_settings(&path).unwrap_err();
std::fs::remove_dir_all(&dir).ok();
assert!(e.0.contains("not valid JSON"));
}
}