Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions apps/desktop/src/state/configIssues.test.ts
Original file line number Diff line number Diff line change
@@ -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([]);
});
});
27 changes: 27 additions & 0 deletions apps/desktop/src/state/configIssues.ts
Original file line number Diff line number Diff line change
@@ -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) });
}
2 changes: 2 additions & 0 deletions apps/desktop/src/state/settingsScope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -302,6 +303,7 @@ async function readServerSettings(host: string): Promise<void> {
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());
Expand Down
19 changes: 19 additions & 0 deletions apps/desktop/src/ui/ConfigIssueNotice.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<div className="mb-6 flex flex-col gap-2">
{issues.map((issue) => (
<Callout key={issue.path} tone="warning">
{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}.`}
</Callout>
))}
</div>
);
}
2 changes: 2 additions & 0 deletions apps/desktop/src/ui/Settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ import {
useApp,
} from "../state/store";
import { AddHarnessForm } from "./AddHarness";
import { ConfigIssueNotice } from "./ConfigIssueNotice";
import {
ArrowLeft,
Blocks,
Expand Down Expand Up @@ -1072,6 +1073,7 @@ export function SettingsPage() {
<PageActions slotRef={setTitleSlot} active={!scrolled} />
</div>
</div>
<ConfigIssueNotice />
<Suspense fallback={<Loading error={null} />}>
{section === "general" && <GeneralPage />}
{section === "chat" && <ChatPage />}
Expand Down
8 changes: 8 additions & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
52 changes: 52 additions & 0 deletions rustcode/engine/src/acp/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,10 @@ pub(crate) fn read(request: GetSettingsRequest) -> Result<Value, agent_client_pr
}
let stored_keys: Vec<String> = 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,
Expand All @@ -296,6 +300,22 @@ pub(crate) fn read(request: GetSettingsRequest) -> Result<Value, agent_client_pr
Ok(answer)
}

/// The config files the engine could not read, for the Settings notice.
fn config_issues_json(issues: &[crate::config::ConfigLoadIssue]) -> 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.
Expand Down Expand Up @@ -605,6 +625,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 {
Expand Down
44 changes: 16 additions & 28 deletions rustcode/engine/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<TomlConfig>(&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;
}
}
Expand Down Expand Up @@ -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())?;
Expand Down Expand Up @@ -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)
Expand All @@ -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() {
Expand Down Expand Up @@ -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!(
Expand Down Expand Up @@ -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::{
Expand Down
Loading
Loading