From de0764a440a977d7274372c3b039f7796e5db85e Mon Sep 17 00:00:00 2001 From: LHaghfoss Date: Wed, 25 Nov 2026 23:24:36 +0100 Subject: [PATCH 1/2] fix(engine): report config.toml parse errors instead of using defaults --- apps/desktop/src/state/configIssues.test.ts | 26 ++++ apps/desktop/src/state/configIssues.ts | 27 +++++ apps/desktop/src/state/settingsScope.ts | 2 + apps/desktop/src/ui/ConfigIssueNotice.tsx | 19 +++ apps/desktop/src/ui/Settings.tsx | 2 + docs/configuration.md | 8 ++ rustcode/engine/src/acp/settings.rs | 32 +++++ rustcode/engine/src/config.rs | 44 +++---- rustcode/engine/src/config/load_issues.rs | 126 ++++++++++++++++++++ rustcode/engine/src/doctor.rs | 53 +++++++- 10 files changed, 308 insertions(+), 31 deletions(-) create mode 100644 apps/desktop/src/state/configIssues.test.ts create mode 100644 apps/desktop/src/state/configIssues.ts create mode 100644 apps/desktop/src/ui/ConfigIssueNotice.tsx create mode 100644 rustcode/engine/src/config/load_issues.rs diff --git a/apps/desktop/src/state/configIssues.test.ts b/apps/desktop/src/state/configIssues.test.ts new file mode 100644 index 000000000..74d628b44 --- /dev/null +++ b/apps/desktop/src/state/configIssues.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, test } from "bun:test"; +import { parseConfigIssues, rememberConfigIssues, useConfigIssues } from "./configIssues"; + +describe("config issues", () => { + test("reads the engine's unreadable config files", () => { + const issues = parseConfigIssues({ + values: {}, + configIssues: [ + { path: "/u/config.toml", scope: "user", message: "Failed to parse /u/config.toml: line 2" }, + { path: "/p/.rustcode/config.toml", scope: "project", message: "bad" }, + { path: 3, message: "skipped" }, + ], + }); + expect(issues).toEqual([ + { path: "/u/config.toml", scope: "user", message: "Failed to parse /u/config.toml: line 2" }, + { path: "/p/.rustcode/config.toml", scope: "project", message: "bad" }, + ]); + }); + + test("an older engine without the field reports none, and clears an earlier answer", () => { + rememberConfigIssues({ configIssues: [{ path: "/u/config.toml", scope: "user", message: "x" }] }); + expect(useConfigIssues.getState().issues).toHaveLength(1); + rememberConfigIssues({ values: {} }); + expect(useConfigIssues.getState().issues).toEqual([]); + }); +}); diff --git a/apps/desktop/src/state/configIssues.ts b/apps/desktop/src/state/configIssues.ts new file mode 100644 index 000000000..ffaa78097 --- /dev/null +++ b/apps/desktop/src/state/configIssues.ts @@ -0,0 +1,27 @@ +import { create } from "zustand"; +import { arr, type Json, obj } from "../acp/jsonrpc"; + +/** A config file the engine could not read (`configIssues` on `_rustcode/settings/get`). */ +export interface ConfigIssue { + path: string; + scope: "user" | "project"; + message: string; +} + +/** The unreadable config files of this computer's engine; empty when every file loaded. */ +export const useConfigIssues = create<{ issues: ConfigIssue[] }>(() => ({ issues: [] })); + +/** The issues in a settings answer; an engine that predates the field reports none. */ +export function parseConfigIssues(answer: Json | undefined): ConfigIssue[] { + return arr(obj(answer)?.configIssues).flatMap((raw) => { + const issue = obj(raw); + const path = issue?.path; + const message = issue?.message; + if (typeof path !== "string" || typeof message !== "string") return []; + return [{ path, message, scope: issue?.scope === "project" ? "project" : "user" }]; + }); +} + +export function rememberConfigIssues(answer: Json | undefined): void { + useConfigIssues.setState({ issues: parseConfigIssues(answer) }); +} diff --git a/apps/desktop/src/state/settingsScope.ts b/apps/desktop/src/state/settingsScope.ts index f4496ebc9..06043af2f 100644 --- a/apps/desktop/src/state/settingsScope.ts +++ b/apps/desktop/src/state/settingsScope.ts @@ -18,6 +18,7 @@ import { arr, type Json, type JsonObject, obj } from "../acp/jsonrpc"; import type { Harness, HarnessSnapshot } from "../acp/types"; import { Method, parseHarnessSnapshot } from "../acp/types"; import { readStorage, writeStorage } from "../lib/storage"; +import { rememberConfigIssues } from "./configIssues"; import { useMachines } from "./machines"; import { readProjectBook, updateProjectEntry } from "./projectBook"; import { matchProject, type Project, projectsOn } from "./projects"; @@ -302,6 +303,7 @@ async function readServerSettings(host: string): Promise { try { await seedLocalSettings(host); const answer = await machineRequest(host, "_rustcode/settings/get", {}, 10_000); + rememberConfigIssues(answer); const values = obj(obj(answer)?.values); if (values && revision === settingsRevision.get(host)) remember(host, values); else if (revision === settingsRevision.get(host)) remember(host, localValues()); diff --git a/apps/desktop/src/ui/ConfigIssueNotice.tsx b/apps/desktop/src/ui/ConfigIssueNotice.tsx new file mode 100644 index 000000000..348aac312 --- /dev/null +++ b/apps/desktop/src/ui/ConfigIssueNotice.tsx @@ -0,0 +1,19 @@ +import { useConfigIssues } from "../state/configIssues"; +import { Callout } from "./primitives"; + +/** Settings' notice for config files the engine could not read and is running without. */ +export function ConfigIssueNotice() { + const issues = useConfigIssues((state) => state.issues); + if (!issues.length) return null; + return ( +
+ {issues.map((issue) => ( + + {issue.scope === "user" + ? `config.toml could not be read: ${issue.message}. RustCode is using its defaults and will not save settings until the file is fixed.` + : `A project config could not be read and is skipped: ${issue.message}.`} + + ))} +
+ ); +} diff --git a/apps/desktop/src/ui/Settings.tsx b/apps/desktop/src/ui/Settings.tsx index e8685770f..7d061ffdc 100644 --- a/apps/desktop/src/ui/Settings.tsx +++ b/apps/desktop/src/ui/Settings.tsx @@ -62,6 +62,7 @@ import { useApp, } from "../state/store"; import { AddHarnessForm } from "./AddHarness"; +import { ConfigIssueNotice } from "./ConfigIssueNotice"; import { ArrowLeft, Blocks, @@ -1072,6 +1073,7 @@ export function SettingsPage() { + }> {section === "general" && } {section === "chat" && } diff --git a/docs/configuration.md b/docs/configuration.md index e96bd4b74..bd6112a3d 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -11,6 +11,14 @@ the next normal save, Rustcode writes the merged configuration to fields use compiled defaults. Malformed or newer unsupported TOML is preserved and reported instead of being overwritten. +A `config.toml` that cannot be read leaves the engine on built-in defaults +until it is fixed, and settings are not saved meanwhile (a save names the file +and the parse error). It is reported, with the parser's line and column, in +three places: `rustcode doctor` fails `config-load`; Settings shows a notice at +the top of every page (the `configIssues` list of `_rustcode/settings/get`); +and the engine's stderr. A project's `.rustcode/config.toml` that cannot be +read is skipped, and reported the same way as `project-config`. + ## User-data migrations When a newer RustCode first starts (terminal, `--acp` for the macOS app, or a diff --git a/rustcode/engine/src/acp/settings.rs b/rustcode/engine/src/acp/settings.rs index 636e5dad1..717ca7f2e 100644 --- a/rustcode/engine/src/acp/settings.rs +++ b/rustcode/engine/src/acp/settings.rs @@ -605,6 +605,38 @@ mod tests { assert_eq!(values["auto-compact-threshold"], json!(150_000)); } + #[test] + fn a_full_read_lists_unreadable_config_files_and_a_keyed_read_skips_them() { + let workspace = tempfile::tempdir().unwrap(); + let project = workspace.path().join(".rustcode"); + std::fs::create_dir_all(&project).unwrap(); + std::fs::write(project.join("config.toml"), "sandbox_mode = [\n").unwrap(); + let answer = read(GetSettingsRequest { + project: Some(workspace.path().display().to_string()), + ..Default::default() + }) + .unwrap(); + let issues = answer["configIssues"].as_array().unwrap(); + let issue = issues + .iter() + .find(|issue| issue["scope"] == "project") + .expect("the broken project file"); + assert!(issue["path"].as_str().unwrap().ends_with("config.toml")); + assert!( + issue["message"] + .as_str() + .unwrap() + .contains("Failed to parse") + ); + + let keyed = read(GetSettingsRequest { + keys: Some(vec!["orchestration".to_owned()]), + ..Default::default() + }) + .unwrap(); + assert!(keyed.get("configIssues").is_none()); + } + #[test] fn set_merges_reads_back_and_keeps_the_rest_of_the_file() { let answer = write(SetSettingsRequest { diff --git a/rustcode/engine/src/config.rs b/rustcode/engine/src/config.rs index acd54bfd1..564611974 100644 --- a/rustcode/engine/src/config.rs +++ b/rustcode/engine/src/config.rs @@ -2294,30 +2294,10 @@ pub fn load_config_from(dir: &Path) -> (String, String, AppConfig) { let toml_path = dir.join(CONFIG_TOML_FILE); if toml_path.exists() { - match fs::read_to_string(&toml_path) - .ok() - .and_then(|content| toml::from_str::(&content).ok()) - { - Some(file) => { - if let Some(version) = file.version - && version > CONFIG_FORMAT_VERSION - { - eprintln!( - "[rustcode] WARNING: {} uses unsupported config format version {} (this version supports up to {}). Using built-in defaults.", - toml_path.display(), - version, - CONFIG_FORMAT_VERSION - ); - is_valid = false; - } else { - apply_toml_config(&mut config, file); - } - } - None => { - eprintln!( - "[rustcode] WARNING: Failed to parse {}. Using built-in defaults.", - toml_path.display() - ); + match read_toml_config(&toml_path) { + Ok(file) => apply_toml_config(&mut config, file), + Err(error) => { + eprintln!("[rustcode] WARNING: {error}. Using built-in defaults."); is_valid = false; } } @@ -2426,7 +2406,9 @@ fn save_entire_config_for_workspace_result( workspace: Option<&Path>, ) -> Result<(), String> { if !config.is_valid { - return Err("configuration is invalid".to_owned()); + return Err(load_issues::invalid_config_error( + get_config_dir().as_deref(), + )); } let dir = get_config_dir().ok_or_else(|| "could not determine the config directory".to_owned())?; @@ -2466,7 +2448,9 @@ pub fn save_theme(theme: &str) -> Result<(), String> { get_config_dir().ok_or_else(|| "could not determine the config directory".to_owned())?; let (_, _, mut config) = load_config_from(&dir); if !config.is_valid { - return Err("configuration is invalid".to_owned()); + return Err(load_issues::invalid_config_error( + get_config_dir().as_deref(), + )); } config.theme = theme.to_owned(); save_config_to_result(&dir, &config) @@ -2479,7 +2463,9 @@ pub fn save_discord_rpc_enabled( workspace: Option<&Path>, ) -> Result<(), String> { if !config.is_valid { - return Err("configuration is invalid".to_owned()); + return Err(load_issues::invalid_config_error( + get_config_dir().as_deref(), + )); } if let Some(workspace) = workspace { for path in project_config_paths(workspace).into_iter().rev() { @@ -2509,7 +2495,7 @@ pub fn save_discord_rpc_enabled( fn save_config_to_result(dir: &Path, config: &AppConfig) -> Result<(), String> { if !config.is_valid { - return Err("configuration is invalid".to_owned()); + return Err(load_issues::invalid_config_error(Some(dir))); } fs::create_dir_all(dir).map_err(|error| { format!( @@ -3025,7 +3011,9 @@ fn write_config_file(path: &Path, contents: &str) -> std::io::Result<()> { } mod credentials; +mod load_issues; pub use credentials::{AuthMethod, CredentialRef}; +pub use load_issues::{ConfigLoadIssue, config_load_issues}; mod mcp_servers; pub use mcp_servers::{ diff --git a/rustcode/engine/src/config/load_issues.rs b/rustcode/engine/src/config/load_issues.rs new file mode 100644 index 000000000..d5e821f61 --- /dev/null +++ b/rustcode/engine/src/config/load_issues.rs @@ -0,0 +1,126 @@ +//! Config files that could not be read, with the parser's own message, so +//! `rustcode doctor`, Settings and a refused save can say what is wrong +//! instead of the engine quietly running on built-in defaults. + +use serde::Serialize; +use std::path::{Path, PathBuf}; + +/// One config file the engine skipped because it could not be read. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct ConfigLoadIssue { + pub path: PathBuf, + /// `user` for `config.toml` in the config directory, `project` for a + /// repository's `.rustcode/config.toml`. + pub scope: &'static str, + /// The read or parse error, naming the file and, for TOML, the line and column. + pub message: String, +} + +/// Every config file that failed to load: the user config, then the project +/// files that apply to `workspace`, in precedence order. +pub fn config_load_issues(workspace: Option<&Path>) -> Vec { + let mut issues: Vec = super::get_config_dir() + .and_then(|dir| user_config_issue(&dir)) + .into_iter() + .collect(); + if let Some(workspace) = workspace { + for path in super::project_config_paths(workspace) { + if let Err(message) = super::read_toml_config(&path) { + issues.push(ConfigLoadIssue { + path, + scope: "project", + message, + }); + } + } + } + issues +} + +/// The user config in `dir`, when it exists and cannot be read. +pub fn user_config_issue(dir: &Path) -> Option { + let path = dir.join(super::CONFIG_TOML_FILE); + if !path.exists() { + return None; + } + super::read_toml_config(&path) + .err() + .map(|message| ConfigLoadIssue { + path, + scope: "user", + message, + }) +} + +/// Why a save was refused while the loaded configuration is invalid. +pub(super) fn invalid_config_error(dir: Option<&Path>) -> String { + match dir.and_then(user_config_issue) { + Some(issue) => format!( + "settings were not saved because {} could not be read ({}); fix the file, then try again", + issue.path.display(), + issue.message + ), + None => "configuration is invalid".to_owned(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_missing_or_valid_user_config_is_no_issue() { + let dir = tempfile::tempdir().unwrap(); + assert_eq!(user_config_issue(dir.path()), None); + std::fs::write(dir.path().join("config.toml"), "version = 1\n").unwrap(); + assert_eq!(user_config_issue(dir.path()), None); + } + + #[test] + fn a_broken_user_config_names_the_file_and_line() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write( + dir.path().join("config.toml"), + "version = 1\nmax_tool_rounds = \"oops\n", + ) + .unwrap(); + let issue = user_config_issue(dir.path()).expect("an issue"); + assert_eq!(issue.scope, "user"); + assert!(issue.message.contains("config.toml"), "{}", issue.message); + assert!(issue.message.contains("line 2"), "{}", issue.message); + } + + #[test] + fn a_too_new_format_is_an_issue() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("config.toml"), "version = 999\n").unwrap(); + let issue = user_config_issue(dir.path()).expect("an issue"); + assert!(issue.message.contains("unsupported config format version")); + } + + #[test] + fn a_refused_save_names_the_broken_file() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("config.toml"), "[default\n").unwrap(); + let message = invalid_config_error(Some(dir.path())); + assert!( + message.contains("config.toml could not be read"), + "{message}" + ); + assert_eq!(invalid_config_error(None), "configuration is invalid"); + } + + #[test] + fn a_broken_project_config_is_its_own_issue() { + let workspace = tempfile::tempdir().unwrap(); + let project = workspace.path().join(".rustcode"); + std::fs::create_dir_all(&project).unwrap(); + std::fs::write(project.join("config.toml"), "sandbox_mode = [\n").unwrap(); + let issues = config_load_issues(Some(workspace.path())); + let project_issue = issues + .iter() + .find(|issue| issue.scope == "project") + .expect("a project issue"); + assert!(project_issue.path.ends_with(".rustcode/config.toml")); + } +} diff --git a/rustcode/engine/src/doctor.rs b/rustcode/engine/src/doctor.rs index 90f724ba7..cff7be9aa 100644 --- a/rustcode/engine/src/doctor.rs +++ b/rustcode/engine/src/doctor.rs @@ -199,9 +199,9 @@ pub fn run_checks(fix: bool) -> Vec { // Config load. let workspace = std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")); let (api_base, model_name, _) = crate::config::load_config_for_workspace(&workspace); - checks.push(DoctorCheck::pass( - "config-load", - format!("model={model_name} base={api_base}"), + checks.extend(config_load_checks( + &crate::config::config_load_issues(Some(&workspace)), + &format!("model={model_name} base={api_base}"), )); // Provider API keys: report *where* each key resolved from so @@ -293,6 +293,35 @@ pub fn format_report(checks: &[DoctorCheck]) -> String { out } +/// The config rows: `config-load` fails when the user config could not be +/// read (the engine then runs on built-in defaults), and each project file +/// that could not be read gets a `project-config` row of its own. +fn config_load_checks(issues: &[crate::config::ConfigLoadIssue], loaded: &str) -> Vec { + let hint = |issue: &crate::config::ConfigLoadIssue| { + Some(format!( + "fix that line in {}, or move the file aside to start from defaults", + issue.path.display() + )) + }; + let mut checks = Vec::new(); + match issues.iter().find(|issue| issue.scope == "user") { + Some(issue) => checks.push(DoctorCheck::fail( + "config-load", + format!("{}; using built-in defaults", issue.message), + hint(issue), + )), + None => checks.push(DoctorCheck::pass("config-load", loaded.to_owned())), + } + for issue in issues.iter().filter(|issue| issue.scope == "project") { + checks.push(DoctorCheck::fail( + "project-config", + format!("{}; this file is skipped", issue.message), + hint(issue), + )); + } + checks +} + /// Entry point for `rustcode doctor [--fix]`. Returns a process exit code. pub fn run_doctor(fix: bool) -> i32 { let checks = run_checks(fix); @@ -334,6 +363,24 @@ mod tests { assert_eq!(check.fix_hint.as_deref(), Some("install it somehow")); } + #[test] + fn an_unreadable_config_fails_its_rows() { + let issue = |scope| crate::config::ConfigLoadIssue { + path: PathBuf::from("/x/config.toml"), + scope, + message: "Failed to parse /x/config.toml: line 2".to_owned(), + }; + let checks = config_load_checks(&[issue("user"), issue("project")], "model=m"); + assert_eq!(checks.len(), 2); + assert!(checks.iter().all(|check| !check.ok)); + assert_eq!(checks[0].name, "config-load"); + assert!(checks[0].detail.contains("line 2")); + assert_eq!(checks[1].name, "project-config"); + let clean = config_load_checks(&[], "model=m"); + assert!(clean[0].ok); + assert_eq!(clean[0].detail, "model=m"); + } + #[test] fn run_checks_does_not_panic() { let checks = run_checks(false); From 28ba3c41eb0e7df2946d8ef3377f5281163de5f5 Mon Sep 17 00:00:00 2001 From: LHaghfoss Date: Wed, 25 Nov 2026 23:29:45 +0100 Subject: [PATCH 2/2] fix(engine): answer configIssues on a full settings read --- rustcode/engine/src/acp/settings.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/rustcode/engine/src/acp/settings.rs b/rustcode/engine/src/acp/settings.rs index 717ca7f2e..c6752d048 100644 --- a/rustcode/engine/src/acp/settings.rs +++ b/rustcode/engine/src/acp/settings.rs @@ -286,6 +286,10 @@ pub(crate) fn read(request: GetSettingsRequest) -> Result = stored.keys().cloned().collect(); let mut answer = json!({ "values": values, "stored": stored_keys, "sources": sources }); + if request.keys.is_none() { + let workspace = request.project.as_deref().map(Path::new); + answer["configIssues"] = config_issues_json(&crate::config::config_load_issues(workspace)); + } if let Some(project) = project { answer["project"] = json!({ "path": project, @@ -296,6 +300,22 @@ pub(crate) fn read(request: GetSettingsRequest) -> Result Value { + Value::Array( + issues + .iter() + .map(|issue| { + json!({ + "path": issue.path.display().to_string(), + "scope": issue.scope, + "message": issue.message, + }) + }) + .collect(), + ) +} + /// One setting's current value, for engine code that has to apply a /// client-hosted setting itself (#3422). The registry default applies where /// the machine has not set it.