diff --git a/crates/engine/src/settings.rs b/crates/engine/src/settings.rs index 1d317bd..9792f7d 100644 --- a/crates/engine/src/settings.rs +++ b/crates/engine/src/settings.rs @@ -36,11 +36,46 @@ pub enum Kind { }, /// `true` or `false`. Bool, - /// Any string of at most `max_len` bytes, such as a file path. + /// Any string of at most `max_len` bytes without NUL. Str { /// Longest accepted value in bytes. max_len: usize, }, + /// A file path, or empty for "detect it": a string checked by + /// [`check_path`], the one validator for `settings.set` and the + /// settings dialog (which shows its message). + Path { + /// Longest accepted value in bytes. + max_len: usize, + }, +} + +/// Checks a path setting's text: at most `max_len` bytes, no control +/// characters (U+0000–U+001F, U+007F), not wrapped in quotes (as copied +/// from a shell or the file manager) and no spaces at either end. Values +/// are refused, never trimmed, so what is stored is what was typed. +/// +/// # Errors +/// What to change, as a sentence the dialog shows under the field. +pub fn check_path(text: &str, max_len: usize) -> Result<(), String> { + if text.len() > max_len { + return Err(format!("Enter at most {max_len} bytes")); + } + if text.chars().any(|c| c < ' ' || c == '\u{7f}') { + return Err("Remove tabs, line breaks and other control characters".into()); + } + let trimmed = text.trim(); + let quoted = trimmed.len() >= 2 + && ['"', '\''] + .iter() + .any(|q| trimmed.starts_with(*q) && trimmed.ends_with(*q)); + if quoted { + return Err("Remove the quotes around the path".into()); + } + if trimmed != text { + return Err("Remove the spaces at the start or end of the path".into()); + } + Ok(()) } /// The default value of a setting. @@ -121,6 +156,12 @@ impl Def { self.key )), }, + Kind::Path { max_len } => match value.as_str() { + Some(s) => { + check_path(s, max_len).map_err(|reason| format!("{}: {reason}", self.key)) + } + None => Err(format!("{} must be a path string, got {value}", self.key)), + }, } } @@ -130,7 +171,7 @@ impl Def { Kind::Enum(values) => ("enum", Some(values.to_vec()), None, None), Kind::Int { min, max } => ("int", None, Some(min), Some(max)), Kind::Bool => ("bool", None, None, None), - Kind::Str { .. } => ("string", None, None, None), + Kind::Str { .. } | Kind::Path { .. } => ("string", None, None, None), }; SettingInfo { key: self.key, @@ -139,6 +180,7 @@ impl Def { enum_values, min, max, + path: matches!(self.kind, Kind::Path { .. }), label_key: self.label_key, description_key: self.description_key, section: self.section, @@ -166,6 +208,10 @@ pub struct SettingInfo { /// Largest value of an int. #[serde(skip_serializing_if = "Option::is_none")] pub max: Option, + /// Whether a string is a file path ([`Kind::Path`]): the dialog adds + /// "Browse…" and shows [`check_path`]'s refusals. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub path: bool, /// Catalog key of the label. pub label_key: &'static str, /// Catalog key of the description. @@ -202,7 +248,7 @@ pub const DEFS: &[Def] = &[ }, Def { key: "php.executable", - kind: Kind::Str { max_len: 4096 }, + kind: Kind::Path { max_len: 4096 }, default: DefaultValue::Str(""), label_key: "settings.php.executable.label", description_key: "settings.php.executable.description", @@ -210,7 +256,7 @@ pub const DEFS: &[Def] = &[ }, Def { key: "phpactor.path", - kind: Kind::Str { max_len: 4096 }, + kind: Kind::Path { max_len: 4096 }, default: DefaultValue::Str(""), label_key: "settings.phpactor.path.label", description_key: "settings.phpactor.path.description", @@ -277,7 +323,7 @@ pub const DEFS: &[Def] = &[ }, Def { key: "git.executable", - kind: Kind::Str { max_len: 4096 }, + kind: Kind::Path { max_len: 4096 }, default: DefaultValue::Str(""), label_key: "settings.git.executable.label", description_key: "settings.git.executable.description", @@ -651,6 +697,44 @@ mod tests { assert_eq!(s.get("editor.fontSize"), Some(json!(14))); } + #[test] + fn path_settings_refuse_quotes_padding_and_control_characters() { + let mut s = Settings::in_memory(); + for key in ["php.executable", "phpactor.path", "git.executable"] { + for good in ["", r"C:\php\php.exe", "/opt/my php/php", "'"] { + assert!(s.set(key, json!(good)).is_ok(), "{key} {good:?}"); + } + for (bad, reason) in [ + (" php", "spaces"), + ("php ", "spaces"), + (r#""C:\Program Files\php\php.exe""#, "quotes"), + ("'/opt/php'", "quotes"), + (r#" "/opt/php" "#, "quotes"), + ("/opt/php\t", "control"), + ("/opt/\u{7f}php", "control"), + ] { + let Err(SetError::Invalid(message)) = s.set(key, json!(bad)) else { + panic!("{key} accepted {bad:?}"); + }; + assert!(message.starts_with(&format!("{key}: ")), "{message}"); + assert!(message.contains(reason), "{message}"); + } + assert!(s.set(key, json!("x".repeat(4097))).is_err()); + assert!(s.set(key, json!(1)).is_err()); + assert!(DEFS.iter().any(|d| d.key == key && d.info().path)); + } + assert!(!DEFS.iter().any(|d| d.key == "editor.fontSize" && d.info().path)); + } + + #[test] + fn a_stored_padded_path_counts_as_unset() { + let dir = tempfile::tempdir().unwrap(); + fs::write(dir.path().join(FILE_NAME), r#"{"php.executable": " php"}"#).unwrap(); + let (s, problem) = Settings::load(dir.path()); + assert!(problem.is_none()); + assert_eq!(s.get("php.executable"), Some(json!(""))); + } + #[test] fn autosave_defaults_and_validation() { let mut s = Settings::in_memory(); diff --git a/ui/src/components/settings/stringSetting.ts b/ui/src/components/settings/stringSetting.ts index b84f377..4312cc7 100644 --- a/ui/src/components/settings/stringSetting.ts +++ b/ui/src/components/settings/stringSetting.ts @@ -5,8 +5,9 @@ * * The rules work on any string setting `settings.list` reports, so a new * one (such as `git.executable`) gets the control without changes here. - * The engine still validates every value; these checks only catch mistakes - * early and say how to fix them. + * Path settings are checked only by the engine (`check_path` in + * `crates/engine/src/settings.rs`), the one validator shared with + * `settings.set` from agents and the CLI; the dialog shows its reason. */ import { t } from "../../i18n"; import type { SettingDef } from "../../stores/settings"; @@ -14,9 +15,6 @@ import type { SettingDef } from "../../stores/settings"; /** Longest value in UTF-8 bytes; the engine's limit for string settings. */ export const MAX_STRING_BYTES = 4096; -/** Endings of a key's last segment that mark a path setting. */ -const PATH_ENDINGS = ["path", "executable"]; - /** * Whether a text has control characters (U+0000–U+001F, U+007F), which no * single-line setting needs. @@ -34,18 +32,13 @@ function hasControlChars(text: string): boolean { } /** - * Whether a setting holds a file path: a string setting whose key ends in - * `path` or `executable` (`phpactor.path`, `php.executable`, - * `git.executable`, `x.pharPath`). + * Whether a setting holds a file path: a string setting the engine marks + * with `path` (`php.executable`, `phpactor.path`, `git.executable`). * * @param def - the setting. */ export function isPathSetting(def: SettingDef): boolean { - if (def.type !== "string") { - return false; - } - const last = (def.key.split(".").at(-1) ?? "").toLowerCase(); - return PATH_ENDINGS.some((ending) => last.endsWith(ending)); + return def.type === "string" && def.path; } /** @@ -60,32 +53,24 @@ export function placeholderOf(def: SettingDef): string { } /** - * Checks a typed value before it goes to `settings.set`. - * - * - Longer than {@link MAX_STRING_BYTES} UTF-8 bytes, or with control - * characters: refused for every string setting. - * - Paths: refused when wrapped in quotes (as copied from a shell or the - * file manager) or with spaces at either end. + * Checks a typed value before it goes to `settings.set`: longer than + * {@link MAX_STRING_BYTES} UTF-8 bytes, or with control characters, is + * refused. Paths are left to the engine, which refuses the same and + * quoted or padded paths too. * * @param def - the setting. * @param text - the typed value. * @returns the error text from the catalog, or null when the value may be sent. */ export function checkString(def: SettingDef, text: string): string | null { + if (isPathSetting(def)) { + return null; + } if (new TextEncoder().encode(text).length > MAX_STRING_BYTES) { return t("settings.error.stringTooLong", { max: MAX_STRING_BYTES }); } if (hasControlChars(text)) { return t("settings.error.stringControl"); } - if (!isPathSetting(def)) { - return null; - } - if (/^\s*(["']).*\1\s*$/.test(text) && text.trim().length >= 2) { - return t("settings.error.pathQuoted"); - } - if (text !== text.trim()) { - return t("settings.error.pathSpaces"); - } return null; } diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json index 9383992..fd45bdd 100644 --- a/ui/src/i18n/en.json +++ b/ui/src/i18n/en.json @@ -301,8 +301,6 @@ "settings.error.browseFailed": "The file picker could not open: {message}", "settings.error.int": "Enter a whole number", "settings.error.intRange": "Enter a whole number from {min} to {max}", - "settings.error.pathQuoted": "Remove the quotes around the path", - "settings.error.pathSpaces": "Remove the spaces at the start or end of the path", "settings.error.stringControl": "Remove tabs, line breaks and other control characters", "settings.error.stringTooLong": "Enter at most {max} bytes", "settings.git.executable.description": "Path to the git program (2.30 or newer) that Lutra runs for version control. Leave empty to use git from PATH.", diff --git a/ui/src/ipc.ts b/ui/src/ipc.ts index 2c2692a..baf84d2 100644 --- a/ui/src/ipc.ts +++ b/ui/src/ipc.ts @@ -254,6 +254,17 @@ export interface EngineError { message: string; } +/** + * The part of an engine error's message meant for a person: the reason + * without the engine's `invalid params for : ` prefix, which + * only repeats the command the caller just ran. + * + * @param error - the error. + */ +export function userMessage(error: EngineError): string { + return error.code === "invalid_params" ? error.message.replace(/^invalid params for [^:\s]+: /, "") : error.message; +} + /** Outcome of an engine call. */ export type RunResult = { ok: true; value: T } | { ok: false; error: EngineError }; diff --git a/ui/src/stores/settings.ts b/ui/src/stores/settings.ts index 1505309..a7951bd 100644 --- a/ui/src/stores/settings.ts +++ b/ui/src/stores/settings.ts @@ -19,7 +19,7 @@ import { defineStore } from "pinia"; import { reactive, ref } from "vue"; import { hasMessage, t } from "../i18n"; -import { onEngineEvent, run, type EngineEventPayload } from "../ipc"; +import { onEngineEvent, run, userMessage, type EngineError, type EngineEventPayload } from "../ipc"; import { setTokenOverride } from "../theme"; /** A setting value: settings are scalars. Values from the engine are unchecked. */ @@ -48,6 +48,8 @@ export interface SettingDef { descriptionKey: string; /** Section id; shown with `settings.section.`. */ section: string; + /** Whether a string setting holds a file path (the engine's `path` flag). */ + path: boolean; } /** A section of the dialog with its settings, in engine order. */ @@ -118,6 +120,7 @@ function toSettingDef(raw: unknown): SettingDef | null { labelKey, descriptionKey, section, + path: type === "string" && entry.path === true, }; } @@ -330,7 +333,8 @@ export const useSettingsStore = defineStore("settings", () => { } /** - * Stores the outcome of `settings.set` or `settings.reset`. + * Stores the outcome of `settings.set` or `settings.reset`. A refusal is + * kept as its reason, without the engine's command and key prefixes. * * @param key - the setting. * @param result - the command's outcome. @@ -338,10 +342,11 @@ export const useSettingsStore = defineStore("settings", () => { */ function settle( key: string, - result: { ok: true; value: unknown } | { ok: false; error: { message: string } }, + result: { ok: true; value: unknown } | { ok: false; error: EngineError }, ): boolean { if (!result.ok) { - errors[key] = clip(result.error.message); + const message = userMessage(result.error); + errors[key] = clip(message.startsWith(`${key}: `) ? message.slice(key.length + 2) : message); return false; } Reflect.deleteProperty(errors, key); diff --git a/ui/tests/ipc.test.ts b/ui/tests/ipc.test.ts index 63fd931..9c8e9b4 100644 --- a/ui/tests/ipc.test.ts +++ b/ui/tests/ipc.test.ts @@ -7,7 +7,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; const invoke = vi.hoisted(() => vi.fn()); vi.mock("@tauri-apps/api/core", () => ({ invoke })); -import { listCommands, run, runWaiting, toEngineError } from "../src/ipc"; +import { listCommands, run, runWaiting, toEngineError, userMessage } from "../src/ipc"; describe("run", () => { beforeEach(() => { @@ -66,3 +66,13 @@ describe("toEngineError", () => { expect(toEngineError({ code: 1, message: "x" }).code).toBe("ipc"); }); }); + +describe("userMessage", () => { + it("drops the engine's invalid params prefix and keeps other messages", () => { + expect(userMessage({ code: "invalid_params", message: "invalid params for search.find: unclosed group" })).toBe( + "unclosed group", + ); + expect(userMessage({ code: "failed", message: "invalid params for x.y: z" })).toBe("invalid params for x.y: z"); + expect(userMessage({ code: "invalid_params", message: "missing path" })).toBe("missing path"); + }); +}); diff --git a/ui/tests/settings/SettingsDialog.test.ts b/ui/tests/settings/SettingsDialog.test.ts index b961a84..4ed0175 100644 --- a/ui/tests/settings/SettingsDialog.test.ts +++ b/ui/tests/settings/SettingsDialog.test.ts @@ -361,13 +361,13 @@ describe("settings dialog", () => { expect((input().element as HTMLInputElement).value).toBe("20"); }); - it("shows the engine's error for a value it refuses", async () => { + it("shows the engine's error for a value it refuses, without the key the row already names", async () => { const wrapper = await mountDialog(); await open(wrapper); await useSettingsStore(pinia).set("editor.fontSize", 2); await wrapper.find("[data-section=editor]").trigger("click"); expect(row(wrapper, "editor.fontSize").find("[data-test=settings-error]").text()).toBe( - "editor.fontSize: expected an integer from 8 to 48", + "expected an integer from 8 to 48", ); }); diff --git a/ui/tests/settings/StringSettings.test.ts b/ui/tests/settings/StringSettings.test.ts index a58ed09..afff1b5 100644 --- a/ui/tests/settings/StringSettings.test.ts +++ b/ui/tests/settings/StringSettings.test.ts @@ -40,6 +40,7 @@ function stringEntry(key: string, section: string): Record { labelKey: `settings.${key}.label`, descriptionKey: `settings.${key}.description`, section, + path: /(path|executable)$/i.test(key), }; } @@ -159,6 +160,10 @@ beforeEach(() => { return Promise.resolve({ values: Object.fromEntries(keys.map((k) => [k, values[k]])) }); } case "settings.set": + if (typeof params.value === "string" && params.value.startsWith('"')) { + const message = `invalid params for settings.set: ${String(params.key)}: Remove the quotes around the path`; + return Promise.reject(Object.assign(new Error("x"), { code: "invalid_params", message })); + } if (params.value === "/does/not/exist") { return Promise.reject(Object.assign(new Error("x"), { code: "invalid_params", message: "no such file" })); } @@ -182,12 +187,13 @@ afterEach(() => { }); describe("string setting rules", () => { - it("treats keys ending in path or executable as paths", () => { + it("treats the settings the engine marks as paths as paths", () => { expect(isPathSetting(defOf("php.executable"))).toBe(true); expect(isPathSetting(defOf("phpactor.path"))).toBe(true); expect(isPathSetting(defOf("git.executable"))).toBe(true); expect(isPathSetting(defOf("x.pharPath"))).toBe(true); expect(isPathSetting(defOf("editor.name"))).toBe(false); + expect(isPathSetting({ ...defOf("php.executable"), path: false })).toBe(false); expect(isPathSetting({ ...defOf("php.executable"), type: "int" })).toBe(false); }); @@ -197,16 +203,16 @@ describe("string setting rules", () => { expect(placeholderOf(defOf("editor.name"))).toBe(""); }); - it("refuses long texts, control characters, quoted and padded paths", () => { + it("refuses long texts and control characters, and leaves paths to the engine", () => { const php = defOf("php.executable"); const name = defOf("editor.name"); expect(checkString(php, "C:\\php\\php.exe")).toBeNull(); expect(checkString(php, "")).toBeNull(); expect(checkString(php, "/opt/my php/php")).toBeNull(); - expect(checkString(php, '"C:\\Program Files\\php\\php.exe"')).toBe("Remove the quotes around the path"); - expect(checkString(php, "'/opt/php'")).toBe("Remove the quotes around the path"); - expect(checkString(php, " /opt/php")).toBe("Remove the spaces at the start or end of the path"); - expect(checkString(php, "/opt/php\t")).toBe("Remove tabs, line breaks and other control characters"); + expect(checkString(php, '"C:\\Program Files\\php\\php.exe"')).toBeNull(); + expect(checkString(php, "'/opt/php'")).toBeNull(); + expect(checkString(php, " /opt/php")).toBeNull(); + expect(checkString(php, "/opt/php\t")).toBeNull(); expect(checkString(name, " padded is fine ")).toBeNull(); expect(checkString(name, "ä".repeat(MAX_STRING_BYTES / 2))).toBeNull(); expect(checkString(name, "ä".repeat(MAX_STRING_BYTES / 2 + 1))).toBe(`Enter at most ${String(MAX_STRING_BYTES)} bytes`); @@ -238,16 +244,16 @@ describe("string and path controls", () => { expect(row(wrapper, "php.executable").find("[data-test=settings-error]").exists()).toBe(false); }); - it("refuses a quoted path in place and keeps the typed text", async () => { + it("shows the engine's refusal of a quoted path in place and keeps the typed text", async () => { const wrapper = await openDialog(); await commit(wrapper, "php.executable", '"C:\\php\\php.exe"'); - expect(sets()).toEqual([]); + expect(sets()).toEqual([{ key: "php.executable", value: '"C:\\php\\php.exe"' }]); const php = row(wrapper, "php.executable"); expect(php.find("[data-test=settings-error]").text()).toBe("Remove the quotes around the path"); expect(php.find("input").attributes("aria-invalid")).toBe("true"); expect((php.find("input").element as HTMLInputElement).value).toBe('"C:\\php\\php.exe"'); await commit(wrapper, "php.executable", "C:\\php\\php.exe"); - expect(sets()).toEqual([{ key: "php.executable", value: "C:\\php\\php.exe" }]); + expect(sets().at(-1)).toEqual({ key: "php.executable", value: "C:\\php\\php.exe" }); expect(php.find("[data-test=settings-error]").exists()).toBe(false); });