Compare commits

..

No commits in common. "33a7185d7549b80bfd632707c65bf9bc1fbac81f" and "e228d11ef973be286341dcee17d0b5b458e04bb7" have entirely different histories.

42 changed files with 146 additions and 892 deletions

1
Cargo.lock generated
View file

@ -2589,7 +2589,6 @@ dependencies = [
"lutra-control", "lutra-control",
"lutra-engine", "lutra-engine",
"lutra-mcp", "lutra-mcp",
"lutra-proc",
"lutra-testkit", "lutra-testkit",
"proptest", "proptest",
"serde_json", "serde_json",

View file

@ -18,7 +18,6 @@ path = "src/main.rs"
[dependencies] [dependencies]
lutra-control.workspace = true lutra-control.workspace = true
lutra-mcp.workspace = true lutra-mcp.workspace = true
lutra-proc.workspace = true
serde_json = "1.0.154" serde_json = "1.0.154"
[dev-dependencies] [dev-dependencies]

View file

@ -1,6 +1,7 @@
//! Finding and starting the desktop app when no Lutra is running. //! Finding and starting the desktop app when no Lutra is running.
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::thread; use std::thread;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
@ -69,13 +70,11 @@ fn resolve_link(path: PathBuf) -> PathBuf {
std::fs::canonicalize(&path).unwrap_or(path) std::fs::canonicalize(&path).unwrap_or(path)
} }
/// Starts `desktop` detached from this terminal through /// Starts `desktop` detached from this terminal (Windows: a detached process
/// [`lutra_proc::spawn_detached`] (Windows: a detached process in a new /// in a new process group; Unix: a new process group, so a Ctrl-C or
/// process group that inherits none of this process's handles, so a script /// hangup aimed at the terminal's foreground group does not reach it) and
/// reading `lutra`'s output through a pipe gets end of file as soon as /// waits until it answers
/// `lutra` exits; Unix: a new process group, so a Ctrl-C or hangup aimed at /// on the rendezvous file in `dir`. A desktop that exits successfully may
/// the terminal's foreground group does not reach it) and waits until it
/// answers on the rendezvous file in `dir`. A desktop that exits successfully may
/// have forwarded to an instance that started at the same time, so only a /// have forwarded to an instance that started at the same time, so only a
/// failed exit ends the wait early. /// failed exit ends the wait early.
/// ///
@ -83,7 +82,25 @@ fn resolve_link(path: PathBuf) -> PathBuf {
/// A message if it cannot be started, exits early, or does not answer /// A message if it cannot be started, exits early, or does not answer
/// within [`START_TIMEOUT`]. /// within [`START_TIMEOUT`].
pub fn start(desktop: &Path, dir: &Path) -> Result<Client, String> { pub fn start(desktop: &Path, dir: &Path) -> Result<Client, String> {
let mut child = lutra_proc::spawn_detached(desktop, &[]) let mut command = Command::new(desktop);
command
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
const DETACHED_PROCESS: u32 = 0x0000_0008;
const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
command.creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP);
}
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
command.process_group(0);
}
let mut child = command
.spawn()
.map_err(|e| format!("cannot start {}: {e}", desktop.display()))?; .map_err(|e| format!("cannot start {}: {e}", desktop.display()))?;
let deadline = Instant::now() + START_TIMEOUT; let deadline = Instant::now() + START_TIMEOUT;
loop { loop {

View file

@ -867,12 +867,7 @@ Section Uninstall
; Remove shortcuts if not updating ; Remove shortcuts if not updating
${If} $UpdateMode <> 1 ${If} $UpdateMode <> 1
; Lutra: the template's `!insertmacro DeleteAppUserModelId` is left out. !insertmacro DeleteAppUserModelId
; It clears the Jump List (recent and pinned files) of the app id
; com.tyrveil.lutra, which every Lutra install shares: uninstalling a
; second or test install wiped the list of the one still in use.
; Windows keeps a few kilobytes for the id after the last uninstall and
; shows them again on a reinstall.
; Remove start menu shortcut ; Remove start menu shortcut
!insertmacro MUI_STARTMENU_GETFOLDER Application $AppStartMenuFolder !insertmacro MUI_STARTMENU_GETFOLDER Application $AppStartMenuFolder

View file

@ -408,14 +408,4 @@ mod tests {
.collect(); .collect();
assert_eq!(mac_exts, windows_exts); assert_eq!(mac_exts, windows_exts);
} }
#[test]
fn the_uninstaller_keeps_the_jump_list_every_install_shares() {
let calls: Vec<&str> = include_str!("../installer/installer.nsi")
.lines()
.map(str::trim)
.filter(|line| line.starts_with("!insertmacro DeleteAppUserModelId"))
.collect();
assert_eq!(calls, Vec::<&str>::new());
}
} }

View file

@ -197,7 +197,7 @@ impl Command for Close {
fn spec(&self) -> &CommandSpec { fn spec(&self) -> &CommandSpec {
&CommandSpec { &CommandSpec {
id: "buffer.close", id: "buffer.close",
label: "Close Tab", label: "Close Buffer",
menu_path: Some("File/Close Tab"), menu_path: Some("File/Close Tab"),
default_shortcut: Some("Mod+W"), default_shortcut: Some("Mod+W"),
params: "{ id: number, force?: bool (discard unsaved changes) }; returns null; fails with unsaved_changes if the buffer is dirty and force is not set", params: "{ id: number, force?: bool (discard unsaved changes) }; returns null; fails with unsaved_changes if the buffer is dirty and force is not set",

View file

@ -462,25 +462,6 @@ mod tests {
); );
} }
/// The palette label of a menu command starts with the menu item's
/// wording; it may add context the menu gives by its place ("Rename
/// Symbol" for Refactor › Rename…), but never says it differently
/// ("Close Buffer" for File › Close Tab).
#[test]
fn a_command_in_a_menu_has_the_menu_items_wording_in_the_palette() {
let engine = Engine::new().unwrap();
let differing: Vec<String> = engine
.list_commands()
.iter()
.filter_map(|c| {
let item = c.menu_path.as_deref()?.rsplit('/').next()?;
(!c.label.starts_with(item.trim_end_matches('…')))
.then(|| format!("{}: {} / {item}", c.id, c.label))
})
.collect();
assert_eq!(differing, Vec::<String>::new());
}
#[test] #[test]
fn lists_commands_with_metadata() { fn lists_commands_with_metadata() {
let mut engine = Engine::new().unwrap(); let mut engine = Engine::new().unwrap();

View file

@ -36,46 +36,11 @@ pub enum Kind {
}, },
/// `true` or `false`. /// `true` or `false`.
Bool, Bool,
/// Any string of at most `max_len` bytes without NUL. /// Any string of at most `max_len` bytes, such as a file path.
Str { Str {
/// Longest accepted value in bytes. /// Longest accepted value in bytes.
max_len: usize, 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. /// The default value of a setting.
@ -156,12 +121,6 @@ impl Def {
self.key 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)),
},
} }
} }
@ -171,7 +130,7 @@ impl Def {
Kind::Enum(values) => ("enum", Some(values.to_vec()), None, None), Kind::Enum(values) => ("enum", Some(values.to_vec()), None, None),
Kind::Int { min, max } => ("int", None, Some(min), Some(max)), Kind::Int { min, max } => ("int", None, Some(min), Some(max)),
Kind::Bool => ("bool", None, None, None), Kind::Bool => ("bool", None, None, None),
Kind::Str { .. } | Kind::Path { .. } => ("string", None, None, None), Kind::Str { .. } => ("string", None, None, None),
}; };
SettingInfo { SettingInfo {
key: self.key, key: self.key,
@ -180,7 +139,6 @@ impl Def {
enum_values, enum_values,
min, min,
max, max,
path: matches!(self.kind, Kind::Path { .. }),
label_key: self.label_key, label_key: self.label_key,
description_key: self.description_key, description_key: self.description_key,
section: self.section, section: self.section,
@ -208,10 +166,6 @@ pub struct SettingInfo {
/// Largest value of an int. /// Largest value of an int.
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub max: Option<i64>, pub max: Option<i64>,
/// 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. /// Catalog key of the label.
pub label_key: &'static str, pub label_key: &'static str,
/// Catalog key of the description. /// Catalog key of the description.
@ -248,7 +202,7 @@ pub const DEFS: &[Def] = &[
}, },
Def { Def {
key: "php.executable", key: "php.executable",
kind: Kind::Path { max_len: 4096 }, kind: Kind::Str { max_len: 4096 },
default: DefaultValue::Str(""), default: DefaultValue::Str(""),
label_key: "settings.php.executable.label", label_key: "settings.php.executable.label",
description_key: "settings.php.executable.description", description_key: "settings.php.executable.description",
@ -256,7 +210,7 @@ pub const DEFS: &[Def] = &[
}, },
Def { Def {
key: "phpactor.path", key: "phpactor.path",
kind: Kind::Path { max_len: 4096 }, kind: Kind::Str { max_len: 4096 },
default: DefaultValue::Str(""), default: DefaultValue::Str(""),
label_key: "settings.phpactor.path.label", label_key: "settings.phpactor.path.label",
description_key: "settings.phpactor.path.description", description_key: "settings.phpactor.path.description",
@ -323,7 +277,7 @@ pub const DEFS: &[Def] = &[
}, },
Def { Def {
key: "git.executable", key: "git.executable",
kind: Kind::Path { max_len: 4096 }, kind: Kind::Str { max_len: 4096 },
default: DefaultValue::Str(""), default: DefaultValue::Str(""),
label_key: "settings.git.executable.label", label_key: "settings.git.executable.label",
description_key: "settings.git.executable.description", description_key: "settings.git.executable.description",
@ -697,48 +651,6 @@ mod tests {
assert_eq!(s.get("editor.fontSize"), Some(json!(14))); 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] #[test]
fn autosave_defaults_and_validation() { fn autosave_defaults_and_validation() {
let mut s = Settings::in_memory(); let mut s = Settings::in_memory();

View file

@ -16,12 +16,6 @@
//! - `tree-on-input`: reads one line from standard input first, then acts //! - `tree-on-input`: reads one line from standard input first, then acts
//! as `tree-plain`. A test adopts the helper in between, so the //! as `tree-plain`. A test adopts the helper in between, so the
//! grandchild starts only after the helper is in its job. //! grandchild starts only after the helper is in its job.
//! - `detached-plain`: starts the sleeping grandchild the way the `lutra`
//! CLI did before C9 F1 (a [`std::process::Command`] with null stdio,
//! detached in a new process group on Windows), `detached-proc`: through
//! [`lutra_proc::spawn_detached`]. Then it prints the grandchild's id and
//! exits. A test reading this output sees end of file at once unless the
//! grandchild inherited the pipe.
//! //!
//! Any other argument exits with code 2. //! Any other argument exits with code 2.
@ -38,7 +32,6 @@ fn main() -> ExitCode {
let role = std::env::args().nth(1).unwrap_or_default(); let role = std::env::args().nth(1).unwrap_or_default();
match role.as_str() { match role.as_str() {
"tree-plain" | "tree-proc" => tree(role == "tree-proc"), "tree-plain" | "tree-proc" => tree(role == "tree-proc"),
"detached-plain" | "detached-proc" => detached(role == "detached-proc"),
"tree-on-input" => { "tree-on-input" => {
let mut line = String::new(); let mut line = String::new();
if std::io::stdin().lock().read_line(&mut line).is_err() { if std::io::stdin().lock().read_line(&mut line).is_err() {
@ -79,40 +72,6 @@ fn tree(guarded: bool) -> ExitCode {
ExitCode::SUCCESS ExitCode::SUCCESS
} }
/// Starts the grandchild detached (through `lutra_proc` when `proc`),
/// prints its id and returns.
fn detached(proc: bool) -> ExitCode {
let command = grandchild();
let id = if proc {
let args: Vec<&std::ffi::OsStr> = command.get_args().collect();
let program = std::path::Path::new(command.get_program());
match lutra_proc::spawn_detached(program, &args) {
Ok(child) => child.id(),
Err(_) => return ExitCode::from(4),
}
} else {
let mut command = command;
command
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
command.creation_flags(0x0000_0008 | 0x0000_0200);
}
match command.spawn() {
Ok(child) => child.id(),
Err(_) => return ExitCode::from(4),
}
};
let mut out = std::io::stdout();
if writeln!(out, "{id}").and_then(|()| out.flush()).is_err() {
return ExitCode::from(5);
}
ExitCode::SUCCESS
}
/// A system program that sleeps for [`SLEEP`] without output. /// A system program that sleeps for [`SLEEP`] without output.
fn grandchild() -> Command { fn grandchild() -> Command {
let seconds = SLEEP.as_secs(); let seconds = SLEEP.as_secs();

View file

@ -37,18 +37,9 @@
//! integrated terminal's ConPTY shell, into a kill-on-close job and returns //! integrated terminal's ConPTY shell, into a kill-on-close job and returns
//! a [`Guard`] that holds it. [`enable_ctrl_c`] (Windows) undoes an //! a [`Guard`] that holds it. [`enable_ctrl_c`] (Windows) undoes an
//! inherited "ignore Ctrl+C" flag before that shell starts. //! inherited "ignore Ctrl+C" flag before that shell starts.
//!
//! [`spawn_detached`] is the opposite of [`spawn`]: it starts a program that
//! outlives the caller and holds none of its handles, as the `lutra` CLI
//! starts the desktop app. On Windows the standard library makes every
//! inheritable handle of the caller (such as the pipe a script reads the
//! CLI's output from) inheritable by the child, so the script would wait
//! until the app exits; `spawn_detached` passes no handles at all.
use std::ffi::OsStr;
use std::io; use std::io;
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
use std::path::Path;
use std::process::{Command, ExitStatus}; use std::process::{Command, ExitStatus};
#[cfg(unix)] #[cfg(unix)]
@ -156,78 +147,6 @@ fn spawn_with(
} }
} }
/// A program started by [`spawn_detached`]. Dropping it leaves the program
/// running.
pub struct Detached {
/// The process (Windows: its handle).
#[cfg(windows)]
inner: windows::DetachedProcess,
/// The process.
#[cfg(not(windows))]
inner: std::process::Child,
}
/// Starts `program` with `args` so that it outlives this process and holds
/// none of its handles: standard input, output and error are closed (null),
/// and it leaves this terminal's job control.
///
/// - **Windows:** a detached process in a new process group
/// (`DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP`, so it has no console
/// and a Ctrl+C in the caller's console does not reach it), created with
/// `bInheritHandles = FALSE`, so no handle of the caller is inherited.
/// - **Unix:** a new process group, so a Ctrl-C or hangup aimed at the
/// terminal's foreground group does not reach it; the standard library
/// opens its own descriptors close-on-exec.
///
/// The environment and working directory are this process's.
///
/// # Errors
/// The OS error of starting the program.
pub fn spawn_detached(program: &Path, args: &[&OsStr]) -> io::Result<Detached> {
#[cfg(windows)]
{
windows::spawn_detached(program, args).map(|inner| Detached { inner })
}
#[cfg(not(windows))]
{
let mut command = Command::new(program);
command
.args(args)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
command.process_group(0);
}
command.spawn().map(|inner| Detached { inner })
}
}
impl Detached {
/// The process id.
pub fn id(&self) -> u32 {
self.inner.id()
}
/// The exit status if the program has exited, without waiting.
///
/// # Errors
/// The OS error of asking for it.
pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
self.inner.try_wait()
}
}
impl std::fmt::Debug for Detached {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Detached")
.field("id", &self.id())
.finish_non_exhaustive()
}
}
/// A kill-on-close job for a process Lutra did not start through [`spawn`] /// A kill-on-close job for a process Lutra did not start through [`spawn`]
/// (Windows only, see [`adopt`]). Dropping it kills the process and /// (Windows only, see [`adopt`]). Dropping it kills the process and
/// everything it started. /// everything it started.

View file

@ -19,29 +19,21 @@
//! (`SetConsoleCtrlHandler(NULL, FALSE)`), so the terminal's shells pass //! (`SetConsoleCtrlHandler(NULL, FALSE)`), so the terminal's shells pass
//! Ctrl+C on to the programs they run. //! Ctrl+C on to the programs they run.
//! //!
//! [`spawn_detached`] starts a program through `CreateProcessW` directly,
//! with `bInheritHandles = FALSE`, which the standard library cannot do.
//!
//! This is the one module in Lutra that allows `unsafe`: the job object, //! This is the one module in Lutra that allows `unsafe`: the job object,
//! Tool Help, thread, process and console APIs are only reachable through FFI. Every call gets //! Tool Help, thread and console APIs are only reachable through FFI. Every call gets
//! valid arguments by construction: handles come from `CreateJobObjectW`, //! valid arguments by construction: handles come from `CreateJobObjectW`,
//! `CreateToolhelp32Snapshot`, `OpenThread` or `CreateProcessW` (owned by an [`OwnedHandle`] //! `CreateToolhelp32Snapshot` or `OpenThread` (owned by an [`OwnedHandle`]
//! right away) or from a live [`std::process::Child`], strings passed in are //! right away) or from a live [`std::process::Child`], and the limit and
//! NUL-terminated UTF-16 buffers that outlive the call, and the limit, //! thread entry structures are plain C structs that are valid when zeroed.
//! thread entry, startup and process information structures are plain C
//! structs that are valid when zeroed.
#![allow(unsafe_code)] #![allow(unsafe_code)]
use std::ffi::OsStr;
use std::io; use std::io;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle, RawHandle}; use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle, RawHandle};
use std::os::windows::process::{CommandExt, ExitStatusExt}; use std::os::windows::process::CommandExt;
use std::path::Path; use std::process::Command;
use std::process::{Command, ExitStatus};
use windows_sys::Win32::Foundation::{INVALID_HANDLE_VALUE, WAIT_OBJECT_0, WAIT_TIMEOUT}; use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
use windows_sys::Win32::System::Console::SetConsoleCtrlHandler; use windows_sys::Win32::System::Console::SetConsoleCtrlHandler;
use windows_sys::Win32::System::Diagnostics::ToolHelp::{ use windows_sys::Win32::System::Diagnostics::ToolHelp::{
CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next, CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next,
@ -52,9 +44,7 @@ use windows_sys::Win32::System::JobObjects::{
SetInformationJobObject, TerminateJobObject, SetInformationJobObject, TerminateJobObject,
}; };
use windows_sys::Win32::System::Threading::{ use windows_sys::Win32::System::Threading::{
CREATE_NEW_PROCESS_GROUP, CREATE_NO_WINDOW, CREATE_SUSPENDED, CreateProcessW, DETACHED_PROCESS, CREATE_NO_WINDOW, CREATE_SUSPENDED, OpenThread, ResumeThread, THREAD_SUSPEND_RESUME,
GetExitCodeProcess, OpenThread, PROCESS_INFORMATION, ResumeThread, STARTF_USESTDHANDLES,
STARTUPINFOW, THREAD_SUSPEND_RESUME, WaitForSingleObject,
}; };
/// The exit code a process killed with its job reports. /// The exit code a process killed with its job reports.
@ -211,148 +201,3 @@ fn resume_thread(tid: u32) -> io::Result<()> {
} }
Ok(()) Ok(())
} }
/// A program started by [`spawn_detached`]: its process handle and id.
pub(crate) struct DetachedProcess {
/// The process handle from `CreateProcessW`.
process: OwnedHandle,
/// The process id.
id: u32,
}
/// Starts `program` with `args` as a detached process in a new process
/// group (`DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP`) that inherits no
/// handle at all (`bInheritHandles = FALSE`) and has no standard handles
/// (`STARTF_USESTDHANDLES` with null handles). The standard library always
/// passes `TRUE`, so every inheritable handle of the caller, such as the
/// pipe a script reads its output from, would stay open in the program.
/// `program` is found the way `CreateProcessW` finds the first word of a
/// command line (`.exe` added, `PATH` searched), as the standard library
/// does for a bare name.
///
/// # Errors
/// The OS error of `CreateProcessW`.
pub(crate) fn spawn_detached(program: &Path, args: &[&OsStr]) -> io::Result<DetachedProcess> {
let mut line = quote(program.as_os_str());
for arg in args {
line.push(SPACE);
line.extend(quote(arg));
}
line.push(0);
let mut startup: STARTUPINFOW = unsafe { std::mem::zeroed() };
startup.cb = u32::try_from(std::mem::size_of::<STARTUPINFOW>()).unwrap_or(u32::MAX);
startup.dwFlags = STARTF_USESTDHANDLES;
let mut info: PROCESS_INFORMATION = unsafe { std::mem::zeroed() };
let ok = unsafe {
CreateProcessW(
std::ptr::null(),
line.as_mut_ptr(),
std::ptr::null(),
std::ptr::null(),
0,
DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP,
std::ptr::null(),
std::ptr::null(),
&raw const startup,
&raw mut info,
)
};
if ok == 0 {
return Err(io::Error::last_os_error());
}
let process = unsafe { OwnedHandle::from_raw_handle(info.hProcess) };
drop(unsafe { OwnedHandle::from_raw_handle(info.hThread) });
Ok(DetachedProcess {
process,
id: info.dwProcessId,
})
}
impl DetachedProcess {
/// The process id.
pub(crate) fn id(&self) -> u32 {
self.id
}
/// The exit status if the process has exited, without waiting.
///
/// # Errors
/// The OS error of `WaitForSingleObject` or `GetExitCodeProcess`.
pub(crate) fn try_wait(&self) -> io::Result<Option<ExitStatus>> {
let handle = self.process.as_raw_handle();
match unsafe { WaitForSingleObject(handle, 0) } {
WAIT_TIMEOUT => Ok(None),
WAIT_OBJECT_0 => {
let mut code = 0u32;
if unsafe { GetExitCodeProcess(handle, &raw mut code) } == 0 {
return Err(io::Error::last_os_error());
}
Ok(Some(ExitStatus::from_raw(code)))
}
_ => Err(io::Error::last_os_error()),
}
}
}
/// A backslash in UTF-16.
const BACKSLASH: u16 = 0x5c;
/// A double quote in UTF-16.
const QUOTE: u16 = 0x22;
/// A space in UTF-16.
const SPACE: u16 = 0x20;
/// A tab in UTF-16.
const TAB: u16 = 0x09;
/// One argument quoted for a Windows command line as the C runtime and
/// `CommandLineToArgvW` split it: wrapped in quotes when empty or when it
/// has spaces, tabs or quotes; quotes and the backslashes before them (or
/// before the closing quote) are escaped.
fn quote(arg: &OsStr) -> Vec<u16> {
let units: Vec<u16> = arg.encode_wide().collect();
let needs = units.is_empty() || units.iter().any(|&u| u == SPACE || u == TAB || u == QUOTE);
if !needs {
return units;
}
let mut out = vec![QUOTE];
let mut backslashes = 0usize;
for &unit in &units {
if unit == BACKSLASH {
backslashes += 1;
continue;
}
let escaped = if unit == QUOTE {
backslashes * 2 + 1
} else {
backslashes
};
out.extend(std::iter::repeat_n(BACKSLASH, escaped));
out.push(unit);
backslashes = 0;
}
out.extend(std::iter::repeat_n(BACKSLASH, backslashes * 2));
out.push(QUOTE);
out
}
#[cfg(test)]
mod tests {
use super::*;
fn quoted(arg: &str) -> String {
String::from_utf16(&quote(OsStr::new(arg))).unwrap()
}
#[test]
fn arguments_are_quoted_as_the_c_runtime_splits_them() {
assert_eq!(quoted("-n"), "-n");
assert_eq!(quoted(r"C:\a\b"), r"C:\a\b");
assert_eq!(quoted(""), r#""""#);
assert_eq!(quoted(r"C:\Program Files\x"), r#""C:\Program Files\x""#);
assert_eq!(quoted(r#"say "hi""#), r#""say \"hi\"""#);
assert_eq!(quoted(r"dir with space\"), r#""dir with space\\""#);
assert_eq!(quoted(r#"a\"b"#), r#""a\\\"b""#);
}
}

View file

@ -135,48 +135,3 @@ fn dropping_an_adopt_guard_takes_the_tree_started_after_it() {
assert_gone(reader); assert_gone(reader);
parent.wait().unwrap(); parent.wait().unwrap();
} }
/// Starts the helper in a `detached-*` role, reads the grandchild's id and
/// returns it with whether the output then reached end of file within
/// `within`. Kills the grandchild before returning.
fn detached_output_closes(role: &str, within: Duration) -> bool {
let mut parent = helper(role).spawn().unwrap();
let mut reader = BufReader::new(parent.stdout.take().unwrap());
let mut line = String::new();
reader.read_line(&mut line).unwrap();
let id: u32 = line.trim().parse().unwrap();
assert!(parent.wait().unwrap().success());
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let mut rest = Vec::new();
let _ = reader.read_to_end(&mut rest);
let _ = tx.send(());
});
let closed = rx.recv_timeout(within).is_ok();
let kill = if cfg!(windows) {
Command::new("taskkill")
.args(["/F", "/PID", &id.to_string()])
.output()
} else {
Command::new("kill").args(["-9", &id.to_string()]).output()
};
kill.unwrap();
closed
}
#[test]
fn a_detached_start_holds_none_of_the_callers_handles() {
assert!(
detached_output_closes("detached-proc", GONE_WITHIN),
"the detached grandchild holds its parent's output pipe"
);
}
#[cfg(windows)]
#[test]
fn a_plain_detached_start_inherits_the_callers_pipe_on_windows() {
assert!(
!detached_output_closes("detached-plain", Duration::from_secs(3)),
"the standard library no longer passes inheritable handles on; spawn_detached may be simpler now"
);
}

View file

@ -44,7 +44,7 @@ impl Search {
.dfa_size_limit(REGEX_SIZE_LIMIT) .dfa_size_limit(REGEX_SIZE_LIMIT)
.nest_limit(REGEX_NEST_LIMIT) .nest_limit(REGEX_NEST_LIMIT)
.build(&query.pattern) .build(&query.pattern)
.map_err(|e| SearchError::InvalidPattern(pattern_error(&e.to_string())))?; .map_err(|e| SearchError::InvalidPattern(e.to_string()))?;
Ok(Self { Ok(Self {
matcher, matcher,
filter: PathFilter::new(&query.include, &query.exclude)?, filter: PathFilter::new(&query.include, &query.exclude)?,
@ -53,20 +53,6 @@ impl Search {
} }
} }
/// The reason in a regex error for a person: the regex parser's report
/// spans several lines (the pattern as the matcher wrapped it, a caret, then
/// `error: <reason>`), so only the reason is kept; other errors keep their
/// text with line breaks and runs of spaces folded into one space.
pub(crate) fn pattern_error(text: &str) -> String {
if let Some(reason) = text
.lines()
.find_map(|line| line.trim().strip_prefix("error: "))
{
return reason.trim().to_string();
}
text.split_whitespace().collect::<Vec<_>>().join(" ")
}
/// Include and exclude globs, split by whether they match a name or a path. /// Include and exclude globs, split by whether they match a name or a path.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub(crate) struct PathFilter { pub(crate) struct PathFilter {

View file

@ -81,18 +81,10 @@ fn regex_and_invalid_input() {
assert_eq!(files[0].matches[1].length, 5); assert_eq!(files[0].matches[1].length, 5);
q.pattern = "(".into(); q.pattern = "(".into();
assert_eq!( assert!(matches!(
Search::new(&q).unwrap_err().to_string(), Search::new(&q),
"invalid pattern: unclosed group" Err(SearchError::InvalidPattern(_))
); ));
q.pattern = "a{".into();
let message = Search::new(&q).unwrap_err().to_string();
assert!(
message.starts_with("invalid pattern: ")
&& !message.contains('\n')
&& !message.contains("(?:"),
"{message}"
);
q.pattern = String::new(); q.pattern = String::new();
assert_eq!(Search::new(&q).unwrap_err(), SearchError::EmptyPattern); assert_eq!(Search::new(&q).unwrap_err(), SearchError::EmptyPattern);
let mut q = Query::literal("x"); let mut q = Query::literal("x");

View file

@ -1,6 +1,6 @@
# Alpha acceptance checklist # Alpha acceptance checklist
> **Status:** C7 A2, written against main `da58c83` (M0–M4) · **Last updated:** 2026-11-02 > **Status:** C7 A2, written against main `da58c83` (M0–M4) · **Last updated:** 2026-10-31
The alpha gate ([`roadmap.md`](roadmap.md) › Alpha gate) asks for six workflows to work end to end. This checklist turns them into steps you do by hand, once on Windows and once on macOS. Each step names the action, then what you should see. Plan on 30–45 minutes per platform. The alpha gate ([`roadmap.md`](roadmap.md) › Alpha gate) asks for six workflows to work end to end. This checklist turns them into steps you do by hand, once on Windows and once on macOS. Each step names the action, then what you should see. Plan on 30–45 minutes per platform.
@ -112,7 +112,7 @@ Before this section: `DEMO/shop` has the changes from 1.3, 3.3 and 3.10. The dem
| 5.19 | Git › Abort Merge…, confirm. | The merge is undone: `DiscountPolicy.php` is gone, no conflict colour, `main` as before. | [ ] | [ ] | | 5.19 | Git › Abort Merge…, confirm. | The merge is undone: `DiscountPolicy.php` is gone, no conflict colour, `main` as before. | [ ] | [ ] |
| 5.20 | Git › Merge… `feature/discounts` again, then "Resolve…" on `PriceCalculator.php`. | Three editors: current branch (left), result (middle), merged branch (right), "1 of 1 conflicts open" (or more). | [ ] | [ ] | | 5.20 | Git › Merge… `feature/discounts` again, then "Resolve…" on `PriceCalculator.php`. | Three editors: current branch (left), result (middle), merged branch (right), "1 of 1 conflicts open" (or more). | [ ] | [ ] |
| 5.21 | "Accept all left". Then, in the middle editor, change `gross(float $net)` to `gross(float $net, float $discount = 0.0)` and `round($net *` to `round(max(0.0, $net - $discount) *`. "Apply and mark resolved". | Apply is enabled once no chunk is open; afterwards the file is saved and the list says no conflicts are left, offering "Commit…". | [ ] | [ ] | | 5.21 | "Accept all left". Then, in the middle editor, change `gross(float $net)` to `gross(float $net, float $discount = 0.0)` and `round($net *` to `round(max(0.0, $net - $discount) *`. "Apply and mark resolved". | Apply is enabled once no chunk is open; afterwards the file is saved and the list says no conflicts are left, offering "Commit…". | [ ] | [ ] |
| 5.22 | "Commit…". Keep the prefilled message, Commit. (The conflict warning from 5.18 closes by itself once no conflict is left, and toasts never cover the commit box.) Then `php public/index.php` in the terminal. | The message box already holds `Merge branch 'feature/discounts'` (git's prepared message). The commit succeeds; the Log shows the merge with two parents; the script still prints `19.88 EUR`. | [ ] | [ ] | | 5.22 | "Commit…". Keep the prefilled message, Commit. (The conflict warnings from 5.18 and 5.20 stay until you close them with ×; close them if they cover the Commit button.) Then `php public/index.php` in the terminal. | The message box already holds `Merge branch 'feature/discounts'` (git's prepared message). The commit succeeds; the Log shows the merge with two parents; the script still prints `19.88 EUR`. | [ ] | [ ] |
| 5.23 | Git › Manage Remotes… Add a remote `backup` with the URL of `DEMO/origin.git`; then Remove it (confirm in the row). | `origin` is listed with its URL; `backup` appears and disappears again. | [ ] | [ ] | | 5.23 | Git › Manage Remotes… Add a remote `backup` with the URL of `DEMO/origin.git`; then Remove it (confirm in the row). | `origin` is listed with its URL; `backup` appears and disappears again. | [ ] | [ ] |
| 5.24 | Git › Clone Repository…, URL `DEMO/origin.git` (the full path), "Browse…" and choose `DEMO`. | The folder field becomes `DEMO/origin`. Clone shows progress, then the clone opens as the project (tree with `src`, `public`, `CHANGELOG.md`; branch `main`). | [ ] | [ ] | | 5.24 | Git › Clone Repository…, URL `DEMO/origin.git` (the full path), "Browse…" and choose `DEMO`. | The folder field becomes `DEMO/origin`. Clone shows progress, then the clone opens as the project (tree with `src`, `public`, `CHANGELOG.md`; branch `main`). | [ ] | [ ] |
| 5.25 | File › Open Folder… `DEMO/shop`. | The demo project is back, with the Git state from 5.22. | [ ] | [ ] | | 5.25 | File › Open Folder… `DEMO/shop`. | The demo project is back, with the Git state from 5.22. | [ ] | [ ] |
@ -187,5 +187,4 @@ When everything is ticked on both platforms, say so in the chat with the build c
| Date | Change | Summary | | Date | Change | Summary |
|---|---|---| |---|---|---|
| 2026-10-31 | new | A2: the six alpha workflows as manual steps, the demo project (`cargo xtask demo-project`), failure reports | | 2026-10-31 | new | A2: the six alpha workflows as manual steps, the demo project (`cargo xtask demo-project`), failure reports |
| 2026-11-02 | fix | C9 F1: 5.22 no longer asks to close the conflict warnings |
| 2026-11-01 | dry run | C8 C1: corrected after a Windows dry run (release build, control channel, CLI, MCP): 1.15 line break, 2.4 namespace node, 3.4 line 43, 3.7 `round` instead of `format_price`, 3.9 declaration, 5.2 staged label, 5.5 amend takes `.gitignore` along (else 5.16 stashes it), 5.6 own commits' author, 5.9 doc line, 5.13 no upstream next to "current", 5.22 sticky conflict toasts | | 2026-11-01 | dry run | C8 C1: corrected after a Windows dry run (release build, control channel, CLI, MCP): 1.15 line break, 2.4 namespace node, 3.4 line 43, 3.7 `round` instead of `format_price`, 3.9 declaration, 5.2 staged label, 5.5 amend takes `.gitignore` along (else 5.16 stashes it), 5.6 own commits' author, 5.9 doc line, 5.13 no upstream next to "current", 5.22 sticky conflict toasts |

View file

@ -1,6 +1,6 @@
# Architecture # Architecture
> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal, notifications, UI commands, the palette, the settings dialog, the app icon and the syntax layer documented; M2 highlighting and `editor.reveal`, plus the search backend, the Find tool window, the symbol index, the Structure tool window and the go-to popup; M3 CLI and single instance, LSP client library, toolchain (PHP detection, Phpactor download), the app menu, MCP server, autosave and `flushDirty`, integrated terminal; engine ↔ Phpactor wiring and diagnostics (M3.3), pending outcomes (M3.5), completion, hover and signature help (M3.4); C5 child process groups (H1), settings dialog string and path controls and assist settings (H4), the banner-aligned themes and diagnostic/VCS tokens (H5), Phpactor UX: fast tick, messages, progress, `php -l` (H3); Git backend (M4.1), Changes tool window (M4.2); line changes, gutter markers and status colours (M4.4), diff viewer (M4.3), branches (M4.5); remotes: fetch, pull, push, clone and remote management (M4.10); stash (M4.9) · **Last updated:** 2026-11-02 > **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal, notifications, UI commands, the palette, the settings dialog, the app icon and the syntax layer documented; M2 highlighting and `editor.reveal`, plus the search backend, the Find tool window, the symbol index, the Structure tool window and the go-to popup; M3 CLI and single instance, LSP client library, toolchain (PHP detection, Phpactor download), the app menu, MCP server, autosave and `flushDirty`, integrated terminal; engine ↔ Phpactor wiring and diagnostics (M3.3), pending outcomes (M3.5), completion, hover and signature help (M3.4); C5 child process groups (H1), settings dialog string and path controls and assist settings (H4), the banner-aligned themes and diagnostic/VCS tokens (H5), Phpactor UX: fast tick, messages, progress, `php -l` (H3); Git backend (M4.1), Changes tool window (M4.2); line changes, gutter markers and status colours (M4.4), diff viewer (M4.3), branches (M4.5); remotes: fetch, pull, push, clone and remote management (M4.10); stash (M4.9) · **Last updated:** 2026-10-28
## Overview ## Overview
@ -170,7 +170,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
- `<config_dir>/settings.json`, a flat JSON object of dotted keys, written with `lutra_vfs::write_atomic` on every change. Unknown keys are kept; a stored value that fails validation counts as unset. Read with a 1 MiB cap. - `<config_dir>/settings.json`, a flat JSON object of dotted keys, written with `lutra_vfs::write_atomic` on every change. Unknown keys are kept; a stored value that fails validation counts as unset. Read with a 1 MiB cap.
- A file that is not a JSON object (invalid JSON, not UTF-8, too large) is renamed to `settings.json.bad-<YYYYMMDDTHHMMSSZ>` (with `-n` if taken), the defaults are used and a `notification {level: "warning", messageKey: "notification.settings.corrupt", message, params: {reason, backup}}` is queued. If it cannot be moved, or the directory or file cannot be read, settings stay in memory for the session (`notification.settings.corruptNotMoved`, `notification.settings.unavailable`) so the file is never overwritten. - A file that is not a JSON object (invalid JSON, not UTF-8, too large) is renamed to `settings.json.bad-<YYYYMMDDTHHMMSSZ>` (with `-n` if taken), the defaults are used and a `notification {level: "warning", messageKey: "notification.settings.corrupt", message, params: {reason, backup}}` is queued. If it cannot be moved, or the directory or file cannot be read, settings stay in memory for the session (`notification.settings.corruptNotMoved`, `notification.settings.unavailable`) so the file is never overwritten.
- Keys: `appearance.theme` (`lutra-dark|lutra-light|system`, default `system`), `editor.fontSize` (int 8–48, default 14), `ui.language` (`en`), the autosave keys `editor.autosave.onBlur`, `editor.autosave.onTabSwitch` (bool, default true) and `editor.autosave.idleSeconds` (int 0–600, default 15; M3.10), the assist keys `editor.completion.autoPopup` (bool, default true), `editor.completion.delayMs` (int 0–2000, default 0) and `editor.hover.delayMs` (int 100–3000, default 350; H4). Defined in `lutra_engine::settings::DEFS`. - Keys: `appearance.theme` (`lutra-dark|lutra-light|system`, default `system`), `editor.fontSize` (int 8–48, default 14), `ui.language` (`en`), the autosave keys `editor.autosave.onBlur`, `editor.autosave.onTabSwitch` (bool, default true) and `editor.autosave.idleSeconds` (int 0–600, default 15; M3.10), the assist keys `editor.completion.autoPopup` (bool, default true), `editor.completion.delayMs` (int 0–2000, default 0) and `editor.hover.delayMs` (int 100–3000, default 350; H4). Defined in `lutra_engine::settings::DEFS`.
- Commands: `settings.list` → `[{key, type: enum|int|bool|string, default, enumValues?, min?, max?, path?, labelKey, descriptionKey, section}]` (`path: true` marks a file path setting, `Kind::Path`) (catalog keys `settings.<key>.label` / `.description`; `section` is an id shown with `settings.section.<id>`), `settings.get {keys?}` → `{values}`, `settings.set {key, value}` → `{value}`, `settings.reset {key}` → `{value}`. Unknown keys and bad values fail with `invalid_params`; a write failure fails with `failed` and changes nothing. - Commands: `settings.list` → `[{key, type: enum|int, default, enumValues?, min?, max?, labelKey, descriptionKey, section}]` (catalog keys `settings.<key>.label` / `.description`; `section` is an id shown with `settings.section.<id>`), `settings.get {keys?}` → `{values}`, `settings.set {key, value}` → `{value}`, `settings.reset {key}` → `{value}`. Unknown keys and bad values fail with `invalid_params`; a write failure fails with `failed` and changes nothing.
- Events: `settingsChanged {keys}` when an effective value changes; `notification {id, level: info|warning|error, messageKey?, message?, params?}` (ids `n1`, `n2`…). - Events: `settingsChanged {keys}` when an effective value changes; `notification {id, level: info|warning|error, messageKey?, message?, params?}` (ids `n1`, `n2`…).
### Notifications (M1.12) ### Notifications (M1.12)
@ -252,7 +252,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
- **Text:** labels, descriptions and section names come from the catalog keys the engine sends (`settings.<key>.label`, `.description`, `settings.section.<id>`); enum values use `settings.<key>.value.<value in camelCase>`. A key the catalog lacks shows the setting key (or the raw value). These keys are in the catalog test's runtime list. - **Text:** labels, descriptions and section names come from the catalog keys the engine sends (`settings.<key>.label`, `.description`, `settings.section.<id>`); enum values use `settings.<key>.value.<value in camelCase>`. A key the catalog lacks shows the setting key (or the raw value). These keys are in the catalog test's runtime list.
- **Font size:** `theme.ts` has `setTokenOverride(name, value)`: a value above the theme's that `applyTheme` keeps across theme switches. The store sets `--lt-font-size-editor` to `editor.fontSize` px; the editor reads only that token. - **Font size:** `theme.ts` has `setTokenOverride(name, value)`: a value above the theme's that `applyTheme` keeps across theme switches. The store sets `--lt-font-size-editor` to `editor.fontSize` px; the editor reads only that token.
- **Dialog:** `ui/src/components/settings/SettingsDialog.vue` (mounted in `App.vue`) provides `settings.open` (`Mod+,`, palette, `uiCommand`). Sections on the left, the chosen section's settings on the right; enum → select, int → number field (min/max, applied when committed; text that is no whole number in range is refused in place with `settings.error.intRange`), bool → switch, string → text field (H4). The theme picker is the `appearance.theme` select; the engine answers with `themeChanged`. - **Dialog:** `ui/src/components/settings/SettingsDialog.vue` (mounted in `App.vue`) provides `settings.open` (`Mod+,`, palette, `uiCommand`). Sections on the left, the chosen section's settings on the right; enum → select, int → number field (min/max, applied when committed; text that is no whole number in range is refused in place with `settings.error.intRange`), bool → switch, string → text field (H4). The theme picker is the `appearance.theme` select; the engine answers with `themeChanged`.
- **String and path settings (H4, `stringSetting.ts`):** every `string` setting from `settings.list` gets a text field, applied when committed, so a new key (M4.1's `git.executable`) needs no UI change. A string setting that `settings.list` marks with `path: true` (`php.executable`, `phpactor.path`, `git.executable`) is a path: it gets "Browse…", which calls the desktop's `pick_file {title}` IPC (the dialog plugin's native file picker, run off the main thread; `ipc.ts › pickFile`) and applies the chosen file through `settings.set`; a path with an empty default shows "Detected automatically" while empty. Checks before `settings.set`, each with its own catalog message: at most 4,096 UTF-8 bytes and no control characters (strings that are not paths). Paths are checked only by the engine's `settings::check_path` (C9 F1), the one validator for the dialog, agents and the CLI: at most 4,096 bytes, no control characters, no surrounding quotes, no spaces at either end; refused, never trimmed. The dialog shows the engine's reason without the `invalid params for settings.set: <key>: ` prefix (`ipc.ts › userMessage`). A stored path that fails the check counts as unset. The engine validates everything else. String rows stack the field under the label at full width. `settings.open {section?, query?}` opens on a section or with a search (for agents and live checks). - **String and path settings (H4, `stringSetting.ts`):** every `string` setting from `settings.list` gets a text field, applied when committed, so a new key (M4.1's `git.executable`) needs no UI change. A string setting whose key's last segment ends in `path` or `executable` is a path: it gets "Browse…", which calls the desktop's `pick_file {title}` IPC (the dialog plugin's native file picker, run off the main thread; `ipc.ts › pickFile`) and applies the chosen file through `settings.set`; a path with an empty default shows "Detected automatically" while empty. Checks before `settings.set`, each with its own catalog message: at most 4,096 UTF-8 bytes and no control characters (every string), no surrounding quotes and no spaces at either end (paths). The engine validates everything else. String rows stack the field under the label at full width. `settings.open {section?, query?}` opens on a section or with a search (for agents and live checks).
- **Search** matches label, description, key and section name (every word, ignoring case); while it has text every match shows, grouped by section, and sections without matches are dimmed. - **Search** matches label, description, key and section name (every word, ignoring case); while it has text every match shows, grouped by section, and sections without matches are dimmed.
- **Reset to default** per setting, enabled while the value differs from the default. - **Reset to default** per setting, enabled while the value differs from the default.
- **Errors** show under the control (`role="alert"`, `aria-invalid`) and keep the typed text until the value changes. - **Errors** show under the control (`role="alert"`, `aria-invalid`) and keep the typed text until the value changes.
@ -345,7 +345,6 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
- `Child` dereferences to `std::process::Child`. `Child::kill` replaces the standard `kill` and takes the whole group; `kill_and_wait` also reaps; `Drop` kills the group and reaps. - `Child` dereferences to `std::process::Child`. `Child::kill` replaces the standard `kill` and takes the whole group; `kill_and_wait` also reaps; `Drop` kills the group and reaps.
- A child of `spawn` runs for a moment before it joins its job (Windows) or before its watchdog exists (Unix); a grandchild started in those microseconds can escape. Short-lived tools (git, `php -l`, the `php -v` probe) keep this path: git starts hooks long after it is in its job. - A child of `spawn` runs for a moment before it joins its job (Windows) or before its watchdog exists (Unix); a grandchild started in those microseconds can escape. Short-lived tools (git, `php -l`, the `php -v` probe) keep this path: git starts hooks long after it is in its job.
- `lutra_proc::spawn_suspended` (F3) closes the window on Windows for long-lived children (Phpactor): `CREATE_SUSPENDED | CREATE_NO_WINDOW` (replacing the command's creation flags), assign to the job, then resume the primary thread. std keeps the thread handle to itself, so the thread is found with a Tool Help snapshot (`CreateToolhelp32Snapshot` + `Thread32First/Next`, `OpenThread` + `ResumeThread`). The snapshot covers every thread on the machine. Measured 2026-10-27, debug, 30× `cmd /c exit`, other builds running: std 35–38 ms, std + `CREATE_NO_WINDOW` 54–55 ms, `spawn` 55–65 ms (unchanged from H1), `spawn_suspended` 130–187 ms. That is why git does not use it. On Unix it is `spawn`. - `lutra_proc::spawn_suspended` (F3) closes the window on Windows for long-lived children (Phpactor): `CREATE_SUSPENDED | CREATE_NO_WINDOW` (replacing the command's creation flags), assign to the job, then resume the primary thread. std keeps the thread handle to itself, so the thread is found with a Tool Help snapshot (`CreateToolhelp32Snapshot` + `Thread32First/Next`, `OpenThread` + `ResumeThread`). The snapshot covers every thread on the machine. Measured 2026-10-27, debug, 30× `cmd /c exit`, other builds running: std 35–38 ms, std + `CREATE_NO_WINDOW` 54–55 ms, `spawn` 55–65 ms (unchanged from H1), `spawn_suspended` 130–187 ms. That is why git does not use it. On Unix it is `spawn`.
- `lutra_proc::spawn_detached(program, args) -> io::Result<Detached>` (C9 F1) starts a program that outlives the caller, as the `lutra` CLI starts the desktop: on Windows `CreateProcessW` with `bInheritHandles = FALSE`, null standard handles and `DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP`. The standard library always passes `TRUE`, so the desktop kept every inheritable handle of `lutra`, such as the pipe a script read its output from, and `lutra a.php | cat` returned only when the desktop exited. On Unix a new process group with null stdio. Tests: helper roles `detached-plain` (the pipe stays open) and `detached-proc` (end of file at once).
- `lutra_proc::adopt(RawHandle) -> io::Result<Guard>` (Windows, F3) puts a process someone else started into a new kill-on-close job; dropping the `Guard` or `Guard::kill` ends the process and everything it started since. - `lutra_proc::adopt(RawHandle) -> io::Result<Guard>` (Windows, F3) puts a process someone else started into a new kill-on-close job; dropping the `Guard` or `Guard::kill` ends the process and everything it started since.
- Tests: `crates/proc/tests/process_tree.rs` starts `lutra-proc-helper`, which starts a sleeping grandchild holding the test's pipe. A hard kill of the helper (`TerminateProcess` / `SIGKILL`, with and without the helper itself in a group), `Child::kill` and drop each end the tree; the pipe reaches end of file. Without `KILL_ON_JOB_CLOSE` the hard-kill tests fail. The same runs for `spawn_suspended`, and `adopt` is tested with a helper that starts its grandchild only after a line on stdin, i.e. after the adoption (9 tests). - Tests: `crates/proc/tests/process_tree.rs` starts `lutra-proc-helper`, which starts a sleeping grandchild holding the test's pipe. A hard kill of the helper (`TerminateProcess` / `SIGKILL`, with and without the helper itself in a group), `Child::kill` and drop each end the tree; the pipe reaches end of file. Without `KILL_ON_JOB_CLOSE` the hard-kill tests fail. The same runs for `spawn_suspended`, and `adopt` is tested with a helper that starts its grandchild only after a line on stdin, i.e. after the adoption (9 tests).
- The integrated terminal (portable-pty): on Windows the ConPTY shell is adopted into a job right after it starts (`portable_pty::Child::as_raw_handle`, F3). `Session::kill` and drop kill the job, so processes the shell started (a dev server, `start /b`) end with the terminal tab or with Lutra, even after the shell itself exited. A process the shell starts in the microseconds before the adoption is not in the job; the ConPTY host still ends its console clients when its pipes break. On Unix portable-pty makes the shell a session leader, and closing the PTY master on Lutra's exit hangs it up. - The integrated terminal (portable-pty): on Windows the ConPTY shell is adopted into a job right after it starts (`portable_pty::Child::as_raw_handle`, F3). `Session::kill` and drop kill the job, so processes the shell started (a dev server, `start /b`) end with the terminal tab or with Lutra, even after the shell itself exited. A process the shell starts in the microseconds before the adoption is not in the job; the ConPTY host still ends its console clients when its pipes break. On Unix portable-pty makes the shell a session leader, and closing the PTY master on Lutra's exit hangs it up.
@ -772,7 +771,6 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
| Date | Change | Summary | | Date | Change | Summary |
|---|---|---| |---|---|---|
| 2026-11-02 | minor | C9 F1: `Kind::Path` and `check_path` (one validator for `settings.set` and the dialog, `path` in `settings.list`), `lutra_proc::spawn_detached` for the CLI's desktop start |
| 2026-10-31 | minor | C7 B1: app identifier `com.tyrveil.lutra` with the one-time copy from `dev.lutra.desktop`, NSIS and DMG installers, `cargo xtask bundle` | | 2026-10-31 | minor | C7 B1: app identifier `com.tyrveil.lutra` with the one-time copy from `dev.lutra.desktop`, NSIS and DMG installers, `cargo xtask bundle` |
| 2026-10-31 | minor | C7 A3: `git.mergeMessage` and the merge message prefill, `git.ignore` and the Changes context menu, gutter markers kept on their line, per-module `COMMAND_IDS` for the command listing test | | 2026-10-31 | minor | C7 A3: `git.mergeMessage` and the merge message prefill, `git.ignore` and the Changes context menu, gutter markers kept on their line, per-module `COMMAND_IDS` for the command listing test |
| 2026-10-30 | minor | M4.7: blame (`git.blame` with `--contents` from the buffer, the annotation gutter by age, hover with the commit message, `vcs.toggleBlame`, `vcs.showCommit`) | | 2026-10-30 | minor | M4.7: blame (`git.blame` with `--contents` from the buffer, the annotation gutter by age, hover with the commit message, `vcs.toggleBlame`, `vcs.showCommit`) |

View file

@ -1,6 +1,6 @@
# Installing Lutra # Installing Lutra
> **Status:** draft, alpha installers · **Last updated:** 2026-11-02 > **Status:** draft, alpha installers · **Last updated:** 2026-11-01
Lutra's alpha comes as an installer for Windows (a setup `.exe`) and macOS (a `.dmg`). Both are **not signed yet**, so Windows and macOS warn before the first start; the steps below get past that once. Linux has no installer yet: build it from source ([`development.md`](development.md)). Lutra's alpha comes as an installer for Windows (a setup `.exe`) and macOS (a `.dmg`). Both are **not signed yet**, so Windows and macOS warn before the first start; the steps below get past that once. Linux has no installer yet: build it from source ([`development.md`](development.md)).
@ -61,7 +61,7 @@ Since 0.1.0-alpha the finish page starts Lutra through Explorer (`explorer.exe "
### Uninstalling on Windows ### Uninstalling on Windows
Settings → Apps → Installed apps → **Lutra** → … → **Uninstall**, or run `uninstall.exe` in the install folder. The uninstaller removes the app and `lutra.exe`, its shortcuts, its Installed-apps entry, the **Open with** entries and the PATH entry the setup added. Your settings, recovery journal and Phpactor stay unless you tick **Delete the application data**. The taskbar's Jump List (recent and pinned files) stays too: every Lutra install shares one app id (`com.tyrveil.lutra`), so clearing it, as Tauri's template does, would also empty the list of another Lutra still installed. Settings → Apps → Installed apps → **Lutra** → … → **Uninstall**, or run `uninstall.exe` in the install folder. The uninstaller removes the app and `lutra.exe`, its shortcuts, its Installed-apps entry, the **Open with** entries and the PATH entry the setup added. Your settings, recovery journal and Phpactor stay unless you tick **Delete the application data**.
## macOS ## macOS
@ -116,5 +116,4 @@ An instance started with `--control PORT` or `--data-dir DIR` keeps its files in
|---|---|---| |---|---|---|
| 2026-10-31 | major | B1: initial version, NSIS setup and DMG, unsigned | | 2026-10-31 | major | B1: initial version, NSIS setup and DMG, unsigned |
| 2026-10-31 | minor | B2: finish-page hang found and fixed, Open with for PHP files, version 0.1.0-alpha | | 2026-10-31 | minor | B2: finish-page hang found and fixed, Open with for PHP files, version 0.1.0-alpha |
| 2026-11-02 | minor | C9 F1: the uninstaller keeps the Jump List |
| 2026-11-01 | minor | C2: `lutra` CLI in both installers, optional per-user PATH entry on Windows, macOS link step, `xtask bundle` prints the version; the web view's folder holds no user state | | 2026-11-01 | minor | C2: `lutra` CLI in both installers, optional per-user PATH entry on Windows, macOS link step, `xtask bundle` prints the version; the web view's folder holds no user state |

View file

@ -1,6 +1,6 @@
# Localization checklist # Localization checklist
> **Status:** English catalog covers 100% of UI strings (M1.11); German not started · **Last updated:** 2026-11-02 > **Status:** English catalog covers 100% of UI strings (M1.11); German not started · **Last updated:** 2026-10-16
| Language | Code | Status | Translated | | Language | Code | Status | Translated |
|---|---|---|---:| |---|---|---|---:|
@ -18,7 +18,6 @@ All interface strings go through the message catalog: `t(key, params?)` from `ui
- [ ] Engine messages: `EngineError.message` and other texts the engine sends are English only; they need message keys and params (G14) - [ ] Engine messages: `EngineError.message` and other texts the engine sends are English only; they need message keys and params (G14)
- [x] Setting labels, descriptions, section names and enum value names from `settings.list` in the catalog (M1.9b) - [x] Setting labels, descriptions, section names and enum value names from `settings.list` in the catalog (M1.9b)
- [ ] Language switch through `ui.language`; the catalog becomes reactive (G14) - [ ] Language switch through `ui.language`; the catalog becomes reactive (G14)
- [x] One date format everywhere until G14 (C9 F1): `YYYY-MM-DD` and `YYYY-MM-DD HH:mm` in local time (`i18n › formatDate`, `formatDateTime`) in the Log, stash list, blame and the recovery dialog, instead of the system locale's format next to English text
- [ ] Plural forms and number/date formatting per locale (G14) - [ ] Plural forms and number/date formatting per locale (G14)
- [ ] German catalog (G14) - [ ] German catalog (G14)
- [ ] Native menus and dialogs of the desktop shell (folder picker title, app menu) (G14) - [ ] Native menus and dialogs of the desktop shell (folder picker title, app menu) (G14)
@ -27,7 +26,6 @@ All interface strings go through the message catalog: `t(key, params?)` from `ui
| Date | Change | Summary | | Date | Change | Summary |
|---|---|---| |---|---|---|
| 2026-11-02 | minor | C9 F1: one documented date format; path refusals from the engine (two catalog keys removed) |
| 2026-10-16 | minor | M1.9b: settings keys, key count 80 | | 2026-10-16 | minor | M1.9b: settings keys, key count 80 |
| 2026-10-16 | minor | M1.12: notification keys, key count 46 | | 2026-10-16 | minor | M1.12: notification keys, key count 46 |
| 2026-10-15 | minor | M1.11: English catalog, lint rule, checklist; engine-message gap | | 2026-10-15 | minor | M1.11: English catalog, lint rule, checklist; engine-message gap |

View file

@ -27,7 +27,7 @@
import { RangeSet, RangeSetBuilder, StateEffect, StateField, type EditorState, type Extension, type Text } from "@codemirror/state"; import { RangeSet, RangeSetBuilder, StateEffect, StateField, type EditorState, type Extension, type Text } from "@codemirror/state";
import { EditorView, GutterMarker, ViewPlugin, gutter, showTooltip, type PluginValue, type Tooltip, type ViewUpdate } from "@codemirror/view"; import { EditorView, GutterMarker, ViewPlugin, gutter, showTooltip, type PluginValue, type Tooltip, type ViewUpdate } from "@codemirror/view";
import { runWaiting, type JsonValue } from "../../ipc"; import { runWaiting, type JsonValue } from "../../ipc";
import { formatDate, formatDateTime, t } from "../../i18n"; import { t } from "../../i18n";
import type { AssistBuffer } from "./assist"; import type { AssistBuffer } from "./assist";
/** Delay between the last edit and the query. */ /** Delay between the last edit and the query. */
@ -154,13 +154,18 @@ export function ageLevel(iso: string, now: number): number {
} }
/** /**
* A short local date, `YYYY-MM-DD` ({@link formatDate}). * A short local date, `YYYY-MM-DD`.
* *
* @param iso - ISO 8601 date. * @param iso - ISO 8601 date.
* @returns the date, or the input when it cannot be read. * @returns the date, or the input when it cannot be read.
*/ */
export function shortDate(iso: string): string { export function shortDate(iso: string): string {
return formatDate(iso); const date = new Date(iso);
if (Number.isNaN(date.getTime())) {
return iso;
}
const pad = (n: number): string => String(n).padStart(2, "0");
return `${String(date.getFullYear())}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
} }
/** The text and look of one annotated line. */ /** The text and look of one annotated line. */
@ -338,7 +343,9 @@ function hoverCard(line: BlameLine): { dom: HTMLElement; message: HTMLElement }
head.textContent = t("editor.blame.notCommitted"); head.textContent = t("editor.blame.notCommitted");
message.textContent = t("editor.blame.notCommittedHint"); message.textContent = t("editor.blame.notCommittedHint");
} else { } else {
head.textContent = t("editor.blame.byLine", { hash: line.hash.slice(0, 8), author: line.author, date: formatDateTime(line.date) }); const date = new Date(line.date);
const when = Number.isNaN(date.getTime()) ? line.date : date.toLocaleString();
head.textContent = t("editor.blame.byLine", { hash: line.hash.slice(0, 8), author: line.author, date: when });
message.textContent = messages.get(line.hash) ?? line.summary; message.textContent = messages.get(line.hash) ?? line.summary;
const hint = document.createElement("div"); const hint = document.createElement("div");
hint.className = "lt-blame-tooltip__hint"; hint.className = "lt-blame-tooltip__hint";

View file

@ -8,65 +8,13 @@
* toasts beyond the visible limit collapse into a "+n more" button. The * toasts beyond the visible limit collapse into a "+n more" button. The
* colours match the editor's in-place notices (`--lt-notice-bg`, the error * colours match the editor's in-place notices (`--lt-notice-bg`, the error
* tint). * tint).
*
* The stack never covers an area registered with `keepClearOf` (the commit
* box): it moves above it ({@link stackBottom}) and is placed again when
* toasts come, the window resizes or a kept area changes size.
*/ */
import { CircleAlert, Info, TriangleAlert, X } from "@lucide/vue"; import { CircleAlert, Info, TriangleAlert, X } from "@lucide/vue";
import { onBeforeUnmount, onMounted, ref, watch } from "vue";
import { t } from "../../i18n"; import { t } from "../../i18n";
import { STACK_BOTTOM, stackBottom, useNotificationsStore, type NotificationLevel } from "../../stores/notifications"; import { useNotificationsStore, type NotificationLevel } from "../../stores/notifications";
const notifications = useNotificationsStore(); const notifications = useNotificationsStore();
/** The stack's CSS `bottom`, in pixels. */
const bottom = ref(STACK_BOTTOM);
/** Watches the kept areas and their parents for size changes; null where unsupported. */
const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(place);
/** Moves the stack above every kept area it would cover. */
function place(): void {
const areas = notifications.keepClear.map((element) => element.getBoundingClientRect());
bottom.value = stackBottom(window.innerWidth, window.innerHeight, areas);
}
/** Observes the kept areas and the elements around them (a resized panel moves them). */
function observe(): void {
if (!observer) {
return;
}
observer.disconnect();
for (const element of notifications.keepClear) {
observer.observe(element);
if (element.parentElement) {
observer.observe(element.parentElement);
}
}
}
watch(
() => notifications.keepClear,
() => {
observe();
place();
},
);
watch(() => notifications.toasts.length, place);
onMounted(() => {
window.addEventListener("resize", place);
observe();
place();
});
onBeforeUnmount(() => {
window.removeEventListener("resize", place);
observer?.disconnect();
});
/** Icon of each level. */ /** Icon of each level. */
const ICONS = { info: Info, warning: TriangleAlert, error: CircleAlert } as const; const ICONS = { info: Info, warning: TriangleAlert, error: CircleAlert } as const;
@ -84,7 +32,6 @@ function roleOf(level: NotificationLevel): "status" | "alert" {
<section <section
v-if="notifications.toasts.length > 0" v-if="notifications.toasts.length > 0"
class="toasts" class="toasts"
:style="{ bottom: `${bottom}px`, maxHeight: `calc(100vh - ${bottom + STACK_BOTTOM}px)` }"
:aria-label="t('notification.stack.label')" :aria-label="t('notification.stack.label')"
data-test="toasts" data-test="toasts"
> >
@ -138,12 +85,14 @@ function roleOf(level: NotificationLevel): "status" | "alert" {
.toasts { .toasts {
position: fixed; position: fixed;
right: 16px; right: 16px;
bottom: 36px;
z-index: 100; z-index: 100;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
align-items: flex-end; align-items: flex-end;
gap: 8px; gap: 8px;
width: min(420px, calc(100vw - 32px)); width: min(420px, calc(100vw - 32px));
max-height: calc(100vh - 72px);
overflow-y: auto; overflow-y: auto;
user-select: text; user-select: text;
} }

View file

@ -8,7 +8,7 @@
* failures, they are listed until the dialog is closed. * failures, they are listed until the dialog is closed.
*/ */
import { nextTick, onMounted, onUnmounted, ref, watch } from "vue"; import { nextTick, onMounted, onUnmounted, ref, watch } from "vue";
import { formatDateTime, t } from "../../i18n"; import { t } from "../../i18n";
import { useRecoveryStore } from "./recovery"; import { useRecoveryStore } from "./recovery";
const recovery = useRecoveryStore(); const recovery = useRecoveryStore();
@ -55,7 +55,7 @@ watch(
* @param savedAt - ms since the Unix epoch. * @param savedAt - ms since the Unix epoch.
*/ */
function formatTime(savedAt: number): string { function formatTime(savedAt: number): string {
return formatDateTime(savedAt); return new Date(savedAt).toLocaleString();
} }
/** /**

View file

@ -5,9 +5,8 @@
* *
* The rules work on any string setting `settings.list` reports, so a new * The rules work on any string setting `settings.list` reports, so a new
* one (such as `git.executable`) gets the control without changes here. * one (such as `git.executable`) gets the control without changes here.
* Path settings are checked only by the engine (`check_path` in * The engine still validates every value; these checks only catch mistakes
* `crates/engine/src/settings.rs`), the one validator shared with * early and say how to fix them.
* `settings.set` from agents and the CLI; the dialog shows its reason.
*/ */
import { t } from "../../i18n"; import { t } from "../../i18n";
import type { SettingDef } from "../../stores/settings"; import type { SettingDef } from "../../stores/settings";
@ -15,6 +14,9 @@ import type { SettingDef } from "../../stores/settings";
/** Longest value in UTF-8 bytes; the engine's limit for string settings. */ /** Longest value in UTF-8 bytes; the engine's limit for string settings. */
export const MAX_STRING_BYTES = 4096; 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 * Whether a text has control characters (U+0000–U+001F, U+007F), which no
* single-line setting needs. * single-line setting needs.
@ -32,13 +34,18 @@ function hasControlChars(text: string): boolean {
} }
/** /**
* Whether a setting holds a file path: a string setting the engine marks * Whether a setting holds a file path: a string setting whose key ends in
* with `path` (`php.executable`, `phpactor.path`, `git.executable`). * `path` or `executable` (`phpactor.path`, `php.executable`,
* `git.executable`, `x.pharPath`).
* *
* @param def - the setting. * @param def - the setting.
*/ */
export function isPathSetting(def: SettingDef): boolean { export function isPathSetting(def: SettingDef): boolean {
return def.type === "string" && def.path; if (def.type !== "string") {
return false;
}
const last = (def.key.split(".").at(-1) ?? "").toLowerCase();
return PATH_ENDINGS.some((ending) => last.endsWith(ending));
} }
/** /**
@ -53,24 +60,32 @@ export function placeholderOf(def: SettingDef): string {
} }
/** /**
* Checks a typed value before it goes to `settings.set`: longer than * Checks a typed value before it goes to `settings.set`.
* {@link MAX_STRING_BYTES} UTF-8 bytes, or with control characters, is *
* refused. Paths are left to the engine, which refuses the same and * - Longer than {@link MAX_STRING_BYTES} UTF-8 bytes, or with control
* quoted or padded paths too. * 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.
* *
* @param def - the setting. * @param def - the setting.
* @param text - the typed value. * @param text - the typed value.
* @returns the error text from the catalog, or null when the value may be sent. * @returns the error text from the catalog, or null when the value may be sent.
*/ */
export function checkString(def: SettingDef, text: string): string | null { export function checkString(def: SettingDef, text: string): string | null {
if (isPathSetting(def)) {
return null;
}
if (new TextEncoder().encode(text).length > MAX_STRING_BYTES) { if (new TextEncoder().encode(text).length > MAX_STRING_BYTES) {
return t("settings.error.stringTooLong", { max: MAX_STRING_BYTES }); return t("settings.error.stringTooLong", { max: MAX_STRING_BYTES });
} }
if (hasControlChars(text)) { if (hasControlChars(text)) {
return t("settings.error.stringControl"); 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; return null;
} }

View file

@ -25,14 +25,13 @@
* Open, and Add to .gitignore for untracked files. * Open, and Add to .gitignore for untracked files.
* - **Commit box:** the message, an Amend checkbox and Commit. Commit * - **Commit box:** the message, an Amend checkbox and Commit. Commit
* saves dirty buffers first (`flushDirty`); `Mod+Enter` in the box * saves dirty buffers first (`flushDirty`); `Mod+Enter` in the box
* commits too. Toasts never cover the box: it is registered with the * commits too.
* notifications store's `keepClearOf`.
* - State lives in the Changes store (`changes.ts`), so the status and the * - State lives in the Changes store (`changes.ts`), so the status and the
* message survive hiding the window. Icons are Lucide's; colours are * message survive hiding the window. Icons are Lucide's; colours are
* tokens. * tokens.
*/ */
import { Archive, ArchiveRestore, RefreshCw } from "@lucide/vue"; import { Archive, ArchiveRestore, RefreshCw } from "@lucide/vue";
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue"; import { computed, nextTick, onMounted, ref, watch } from "vue";
import { useCommandsStore } from "../../../commands/store"; import { useCommandsStore } from "../../../commands/store";
import { isMac } from "../../../commands/keymap"; import { isMac } from "../../../commands/keymap";
import { t } from "../../../i18n"; import { t } from "../../../i18n";
@ -51,12 +50,6 @@ const list = ref<HTMLElement | null>(null);
/** The commit message box. */ /** The commit message box. */
const messageBox = ref<HTMLTextAreaElement | null>(null); const messageBox = ref<HTMLTextAreaElement | null>(null);
/** The commit box, kept clear of toasts. */
const commitBox = ref<HTMLFormElement | null>(null);
/** Releases the commit box from the toast stack; null while not registered. */
let releaseCommitBox: (() => void) | null = null;
/** The open context menu: its row and where it shows; null when closed. */ /** The open context menu: its row and where it shows; null when closed. */
const menu = ref<{ row: ChangeRow; x: number; y: number } | null>(null); const menu = ref<{ row: ChangeRow; x: number; y: number } | null>(null);
@ -324,14 +317,6 @@ watch(() => changes.focusRequest, takeFocus);
onMounted(() => { onMounted(() => {
void takeFocus(); void takeFocus();
if (commitBox.value) {
releaseCommitBox = notifications.keepClearOf(commitBox.value);
}
});
onBeforeUnmount(() => {
releaseCommitBox?.();
releaseCommitBox = null;
}); });
watch( watch(
@ -480,7 +465,6 @@ watch(
@open="openRow" @open="openRow"
/> />
<form <form
ref="commitBox"
class="changes__commit" class="changes__commit"
data-test="changes-commit" data-test="changes-commit"
@submit.prevent="changes.commit()" @submit.prevent="changes.commit()"

View file

@ -17,7 +17,7 @@
*/ */
import { RefreshCw, X } from "@lucide/vue"; import { RefreshCw, X } from "@lucide/vue";
import { computed, nextTick, onBeforeUnmount, ref } from "vue"; import { computed, nextTick, onBeforeUnmount, ref } from "vue";
import { formatDateTime, t } from "../../../i18n"; import { t } from "../../../i18n";
import { useProjectStore } from "../../../stores/project"; import { useProjectStore } from "../../../stores/project";
import { SHORT_HASH } from "../changes/changes"; import { SHORT_HASH } from "../changes/changes";
import { refBadges, useLogStore, type CommitFile, type CommitFileStatus } from "./log"; import { refBadges, useLogStore, type CommitFile, type CommitFileStatus } from "./log";
@ -138,12 +138,16 @@ function rowAt(index: number): GraphRow | null {
} }
/** /**
* A date for the list: the local date and time, `YYYY-MM-DD HH:mm`. * A date for the list: the local date and time, short.
* *
* @param iso - ISO 8601 date. * @param iso - ISO 8601 date.
*/ */
function shortDate(iso: string): string { function shortDate(iso: string): string {
return formatDateTime(iso); const date = new Date(iso);
if (Number.isNaN(date.getTime())) {
return iso;
}
return date.toLocaleString(undefined, { year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" });
} }
/** Applies the typed filters now. */ /** Applies the typed filters now. */

View file

@ -16,14 +16,10 @@
* deleted on one side offers to keep the other side's version; binary and * deleted on one side offers to keep the other side's version; binary and
* too large files can only be marked resolved as they are on disk. * too large files can only be marked resolved as they are on disk.
* - **Abort:** `git.mergeAbort` after a confirmation in the dialog. * - **Abort:** `git.mergeAbort` after a confirmation in the dialog.
* - **Conflict toast:** the warning a conflicted merge shows stays only
* while the status store lists conflicted files. Once they are resolved,
* the merge is committed or aborted, it closes; a new conflicted merge
* replaces it.
* - **Untrusted input:** every result is checked field by field. * - **Untrusted input:** every result is checked field by field.
*/ */
import { defineStore } from "pinia"; import { defineStore } from "pinia";
import { computed, ref, shallowRef, watch } from "vue"; import { computed, ref, shallowRef } from "vue";
import { t } from "../../../i18n"; import { t } from "../../../i18n";
import { runWaiting, type JsonValue } from "../../../ipc"; import { runWaiting, type JsonValue } from "../../../ipc";
import { useAutosaveStore } from "../../../stores/autosave"; import { useAutosaveStore } from "../../../stores/autosave";
@ -173,8 +169,6 @@ export const useMergeStore = defineStore("merge", () => {
const busy = ref(false); const busy = ref(false);
/** Bumped on every load, so only the newest one lands. */ /** Bumped on every load, so only the newest one lands. */
let generation = 0; let generation = 0;
/** Id of the shown conflict warning toast; null when none is shown. */
let conflictToast: string | null = null;
/** The conflicted files, sorted by path. */ /** The conflicted files, sorted by path. */
const conflicts = computed(() => const conflicts = computed(() =>
@ -183,23 +177,6 @@ export const useMergeStore = defineStore("merge", () => {
.map((file) => file.path), .map((file) => file.path),
); );
/** Closes the conflict warning toast, if one is shown. */
function dismissConflictToast(): void {
if (conflictToast !== null) {
notifications.dismiss(conflictToast);
conflictToast = null;
}
}
watch(
() => conflicts.value.length,
(count) => {
if (count === 0) {
dismissConflictToast();
}
},
);
/** The current branch, null when detached or unknown. */ /** The current branch, null when detached or unknown. */
const currentBranch = computed(() => status.snapshot?.repo?.branch ?? null); const currentBranch = computed(() => status.snapshot?.repo?.branch ?? null);
@ -277,9 +254,8 @@ export const useMergeStore = defineStore("merge", () => {
return null; return null;
} }
await status.refresh(); await status.refresh();
dismissConflictToast();
if (answer.result === "conflicts") { if (answer.result === "conflicts") {
conflictToast = notifications.notify({ notifications.notify({
level: "warning", level: "warning",
messageKey: "notification.vcs.mergeConflicts", messageKey: "notification.vcs.mergeConflicts",
params: { branch, count: String(answer.conflicts.length) }, params: { branch, count: String(answer.conflicts.length) },
@ -316,7 +292,6 @@ export const useMergeStore = defineStore("merge", () => {
return false; return false;
} }
await status.refresh(); await status.refresh();
dismissConflictToast();
notifications.notify({ level: "info", messageKey: "notification.vcs.mergeAborted" }); notifications.notify({ level: "info", messageKey: "notification.vcs.mergeAborted" });
close(); close();
return true; return true;

View file

@ -22,7 +22,7 @@ import { Archive } from "@lucide/vue";
import { nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue"; import { nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { useModalsStore } from "../../../commands/modals"; import { useModalsStore } from "../../../commands/modals";
import { useCommandsStore } from "../../../commands/store"; import { useCommandsStore } from "../../../commands/store";
import { formatDateTime, t } from "../../../i18n"; import { t } from "../../../i18n";
import { useStashStore, type StashEntry } from "./stash"; import { useStashStore, type StashEntry } from "./stash";
const stash = useStashStore(); const stash = useStashStore();
@ -57,12 +57,16 @@ function refName(entry: StashEntry): string {
} }
/** /**
* A date for the list: the local date and time, `YYYY-MM-DD HH:mm`. * A date for the list: the local date and time, short.
* *
* @param iso - ISO 8601 date. * @param iso - ISO 8601 date.
*/ */
function shortDate(iso: string): string { function shortDate(iso: string): string {
return formatDateTime(iso); const date = new Date(iso);
if (Number.isNaN(date.getTime())) {
return iso;
}
return date.toLocaleString(undefined, { year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" });
} }
/** /**

View file

@ -301,6 +301,8 @@
"settings.error.browseFailed": "The file picker could not open: {message}", "settings.error.browseFailed": "The file picker could not open: {message}",
"settings.error.int": "Enter a whole number", "settings.error.int": "Enter a whole number",
"settings.error.intRange": "Enter a whole number from {min} to {max}", "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.stringControl": "Remove tabs, line breaks and other control characters",
"settings.error.stringTooLong": "Enter at most {max} bytes", "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.", "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.",

View file

@ -55,55 +55,3 @@ export function t(key: string, params?: MessageParams): string {
return value === undefined ? placeholder : String(value); return value === undefined ? placeholder : String(value);
}); });
} }
/**
* Two digits, with a leading zero.
*
* @param n - a number from 0 to 99.
*/
function pad(n: number): string {
return String(n).padStart(2, "0");
}
/**
* Reads a date: an ISO 8601 text or milliseconds since the Unix epoch.
*
* @param value - the date.
* @returns the date, or null when it cannot be read.
*/
function toDate(value: string | number): Date | null {
const date = new Date(value);
return Number.isNaN(date.getTime()) ? null : date;
}
/**
* A date as Lutra shows it everywhere: `YYYY-MM-DD` in local time. One
* fixed format instead of the system locale's, so dates read the same in
* every part of the English interface (`01.11.2026` next to English text
* looked broken). G14 may switch to the interface language's format.
*
* @param value - an ISO 8601 text or milliseconds since the Unix epoch.
* @returns the date, or the input as text when it cannot be read.
*/
export function formatDate(value: string | number): string {
const date = toDate(value);
if (!date) {
return String(value);
}
return `${String(date.getFullYear())}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
}
/**
* A date and time as Lutra shows it everywhere: `YYYY-MM-DD HH:mm` in
* local time, 24-hour clock (see {@link formatDate}).
*
* @param value - an ISO 8601 text or milliseconds since the Unix epoch.
* @returns the date and time, or the input as text when it cannot be read.
*/
export function formatDateTime(value: string | number): string {
const date = toDate(value);
if (!date) {
return String(value);
}
return `${formatDate(value)} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
}

View file

@ -254,17 +254,6 @@ export interface EngineError {
message: string; message: string;
} }
/**
* The part of an engine error's message meant for a person: the reason
* without the engine's `invalid params for <command>: ` 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. */ /** Outcome of an engine call. */
export type RunResult<T> = { ok: true; value: T } | { ok: false; error: EngineError }; export type RunResult<T> = { ok: true; value: T } | { ok: false; error: EngineError };

View file

@ -12,8 +12,7 @@
* - **One search at a time:** a new search cancels the running one * - **One search at a time:** a new search cancels the running one
* (`search.cancel`); the engine does not do that by itself. * (`search.cancel`); the engine does not do that by itself.
* - **Errors:** a refused search (`invalid_params` for a bad regex or glob) * - **Errors:** a refused search (`invalid_params` for a bad regex or glob)
* shows its reason (`userMessage`, without the engine's command prefix) in * shows its message in the window, not as a toast.
* the window, not as a toast.
* - **Opening:** `open` shows the panel, takes the query from the params * - **Opening:** `open` shows the panel, takes the query from the params
* (an agent's `find.open {query}` searches at once) or from the editor * (an agent's `find.open {query}` searches at once) or from the editor
* (selection or word at the cursor) and asks the window to focus its field. * (selection or word at the cursor) and asks the window to focus its field.
@ -24,7 +23,7 @@ import type { EditorState } from "@codemirror/state";
import { defineStore } from "pinia"; import { defineStore } from "pinia";
import { computed, ref, shallowRef } from "vue"; import { computed, ref, shallowRef } from "vue";
import { t } from "../i18n"; import { t } from "../i18n";
import { onEngineEvent, run, userMessage, type EngineEventPayload, type JsonValue } from "../ipc"; import { onEngineEvent, run, type EngineEventPayload, type JsonValue } from "../ipc";
import { useEditorStore } from "./editor"; import { useEditorStore } from "./editor";
/** One match as the window shows it. */ /** One match as the window shows it. */
@ -352,7 +351,7 @@ export const useFindStore = defineStore("find", () => {
early = []; early = [];
if (!result.ok) { if (!result.ok) {
running.value = false; running.value = false;
error.value = userMessage(result.error); error.value = result.error.message;
return; return;
} }
if (id === null) { if (id === null) {

View file

@ -10,12 +10,9 @@
* Info toasts dismiss themselves after {@link INFO_TIMEOUT_MS}; warnings * Info toasts dismiss themselves after {@link INFO_TIMEOUT_MS}; warnings
* and errors stay until closed. At most {@link MAX_VISIBLE} toasts show; * and errors stay until closed. At most {@link MAX_VISIBLE} toasts show;
* older ones collapse into a "+n more" entry. * older ones collapse into a "+n more" entry.
*
* Areas the stack must never cover (the commit box) register themselves
* with `keepClear`; the stack then sits above them ({@link stackBottom}).
*/ */
import { defineStore } from "pinia"; import { defineStore } from "pinia";
import { computed, ref, shallowRef } from "vue"; import { computed, ref } from "vue";
import { hasMessage, t, type MessageParams } from "../i18n"; import { hasMessage, t, type MessageParams } from "../i18n";
import { onEngineEvent, type EngineError, type EngineEventPayload } from "../ipc"; import { onEngineEvent, type EngineError, type EngineEventPayload } from "../ipc";
@ -37,55 +34,6 @@ export const KEY_WATCH_FAILED = "notification.watch.failed";
/** Catalog key of the toast for a failed command. Params: `command`, `message`. */ /** Catalog key of the toast for a failed command. Params: `command`, `message`. */
export const KEY_COMMAND_FAILED = "notification.command.failed"; export const KEY_COMMAND_FAILED = "notification.command.failed";
/** Distance of the stack from the window's bottom edge, in pixels. */
export const STACK_BOTTOM = 36;
/** Distance of the stack from the window's right edge, in pixels. */
export const STACK_RIGHT = 16;
/** Widest the stack gets, in pixels. */
export const STACK_WIDTH = 420;
/** Gap kept between the stack and an area it must not cover, in pixels. */
export const KEEP_CLEAR_GAP = 8;
/** Where an area sits in the window, as `getBoundingClientRect` gives it. */
export interface Area {
/** Left edge. */
left: number;
/** Right edge. */
right: number;
/** Top edge. */
top: number;
/** Bottom edge. */
bottom: number;
}
/**
* The stack's distance from the window's bottom edge so that it covers
* none of the given areas, however tall it grows: above the highest one
* it overlaps horizontally, else {@link STACK_BOTTOM}. Hidden areas (no
* width or height, as under `v-show`) are skipped.
*
* @param width - the window's inner width.
* @param height - the window's inner height.
* @param areas - the areas to keep clear.
* @returns the CSS `bottom` in pixels.
*/
export function stackBottom(width: number, height: number, areas: readonly Area[]): number {
const right = width - STACK_RIGHT;
const left = right - Math.min(STACK_WIDTH, width - 2 * STACK_RIGHT);
let bottom = STACK_BOTTOM;
for (const area of areas) {
const hidden = area.right <= area.left || area.bottom <= area.top;
const beside = area.right <= left || area.left >= right;
if (!hidden && !beside) {
bottom = Math.max(bottom, height - area.top + KEEP_CLEAR_GAP);
}
}
return bottom;
}
/** A toast as the stack shows it. */ /** A toast as the stack shows it. */
export interface Toast { export interface Toast {
/** Unique id: the engine's (`n1`…) or a frontend one (`ui1`…). */ /** Unique id: the engine's (`n1`…) or a frontend one (`ui1`…). */
@ -186,8 +134,6 @@ export const useNotificationsStore = defineStore("notifications", () => {
let made = 0; let made = 0;
/** Auto-dismiss timers of info toasts, by id. */ /** Auto-dismiss timers of info toasts, by id. */
const timers = new Map<string, ReturnType<typeof setTimeout>>(); const timers = new Map<string, ReturnType<typeof setTimeout>>();
/** Elements the stack must not cover, in registration order. */
const keepClear = shallowRef<HTMLElement[]>([]);
/** Ends the engine event subscription; set while started. */ /** Ends the engine event subscription; set while started. */
let unsubscribe: (() => void) | null = null; let unsubscribe: (() => void) | null = null;
@ -282,19 +228,6 @@ export const useNotificationsStore = defineStore("notifications", () => {
expanded.value = false; expanded.value = false;
} }
/**
* Keeps the stack off an element until the returned function is called.
*
* @param element - the element, e.g. the commit box.
* @returns a function that releases the element again.
*/
function keepClearOf(element: HTMLElement): () => void {
keepClear.value = [...keepClear.value, element];
return () => {
keepClear.value = keepClear.value.filter((kept) => kept !== element);
};
}
/** Shows the toasts collapsed into "+n more". */ /** Shows the toasts collapsed into "+n more". */
function expand(): void { function expand(): void {
expanded.value = true; expanded.value = true;
@ -329,8 +262,6 @@ export const useNotificationsStore = defineStore("notifications", () => {
visible, visible,
hiddenCount, hiddenCount,
expanded, expanded,
keepClear,
keepClearOf,
notify, notify,
notifyError, notifyError,
dismiss, dismiss,

View file

@ -19,7 +19,7 @@
import { defineStore } from "pinia"; import { defineStore } from "pinia";
import { reactive, ref } from "vue"; import { reactive, ref } from "vue";
import { hasMessage, t } from "../i18n"; import { hasMessage, t } from "../i18n";
import { onEngineEvent, run, userMessage, type EngineError, type EngineEventPayload } from "../ipc"; import { onEngineEvent, run, type EngineEventPayload } from "../ipc";
import { setTokenOverride } from "../theme"; import { setTokenOverride } from "../theme";
/** A setting value: settings are scalars. Values from the engine are unchecked. */ /** A setting value: settings are scalars. Values from the engine are unchecked. */
@ -48,8 +48,6 @@ export interface SettingDef {
descriptionKey: string; descriptionKey: string;
/** Section id; shown with `settings.section.<id>`. */ /** Section id; shown with `settings.section.<id>`. */
section: string; 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. */ /** A section of the dialog with its settings, in engine order. */
@ -120,7 +118,6 @@ function toSettingDef(raw: unknown): SettingDef | null {
labelKey, labelKey,
descriptionKey, descriptionKey,
section, section,
path: type === "string" && entry.path === true,
}; };
} }
@ -333,8 +330,7 @@ export const useSettingsStore = defineStore("settings", () => {
} }
/** /**
* Stores the outcome of `settings.set` or `settings.reset`. A refusal is * Stores the outcome of `settings.set` or `settings.reset`.
* kept as its reason, without the engine's command and key prefixes.
* *
* @param key - the setting. * @param key - the setting.
* @param result - the command's outcome. * @param result - the command's outcome.
@ -342,11 +338,10 @@ export const useSettingsStore = defineStore("settings", () => {
*/ */
function settle( function settle(
key: string, key: string,
result: { ok: true; value: unknown } | { ok: false; error: EngineError }, result: { ok: true; value: unknown } | { ok: false; error: { message: string } },
): boolean { ): boolean {
if (!result.ok) { if (!result.ok) {
const message = userMessage(result.error); errors[key] = clip(result.error.message);
errors[key] = clip(message.startsWith(`${key}: `) ? message.slice(key.length + 2) : message);
return false; return false;
} }
Reflect.deleteProperty(errors, key); Reflect.deleteProperty(errors, key);

View file

@ -397,9 +397,9 @@ describe("Find tool window", () => {
it("shows a refused regex as an alert", async () => { it("shows a refused regex as an alert", async () => {
const { wrapper } = await mountFind(); const { wrapper } = await mountFind();
findError = { code: "invalid_params", message: "invalid params for search.find: invalid pattern: unclosed group" }; findError = { code: "invalid_params", message: "bad regex" };
await searchFor(wrapper, "("); await searchFor(wrapper, "(");
expect(wrapper.get("[data-test=find-error]").text()).toBe("invalid pattern: unclosed group"); expect(wrapper.get("[data-test=find-error]").text()).toBe("bad regex");
expect(wrapper.get("[data-test=find-query]").attributes("aria-invalid")).toBe("true"); expect(wrapper.get("[data-test=find-query]").attributes("aria-invalid")).toBe("true");
expect(wrapper.get("[data-test=find-status]").text()).toBe(""); expect(wrapper.get("[data-test=find-status]").text()).toBe("");
}); });

View file

@ -1,13 +1,13 @@
/** /**
* Tests of the message catalog: the `t` helper (lookup, interpolation, * Tests of the message catalog: the `t` helper (lookup, interpolation,
* missing keys), the one date format, and a scan of the frontend source that every literal key * missing keys) and a scan of the frontend source that every literal key
* passed to `t` exists in `en.json`. * passed to `t` exists in `en.json`.
*/ */
import { readdirSync, readFileSync } from "node:fs"; import { readdirSync, readFileSync } from "node:fs";
import { join } from "node:path"; import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest"; import { afterEach, describe, expect, it, vi } from "vitest";
import en from "../../src/i18n/en.json"; import en from "../../src/i18n/en.json";
import { formatDate, formatDateTime, hasMessage, t } from "../../src/i18n"; import { hasMessage, t } from "../../src/i18n";
/** Root of the frontend source tree. */ /** Root of the frontend source tree. */
const SRC = join(import.meta.dirname, "..", "..", "src"); const SRC = join(import.meta.dirname, "..", "..", "src");
@ -205,15 +205,3 @@ describe("en.json", () => {
expect(Object.keys(en).filter((key) => !used.has(key))).toEqual([]); expect(Object.keys(en).filter((key) => !used.has(key))).toEqual([]);
}); });
}); });
describe("dates", () => {
it("shows every date as YYYY-MM-DD and times as HH:mm in local time, whatever the system locale", () => {
const local = new Date(2026, 10, 1, 9, 5, 30);
expect(formatDate(local.getTime())).toBe("2026-11-01");
expect(formatDateTime(local.getTime())).toBe("2026-11-01 09:05");
expect(formatDateTime("2026-12-24T18:30:00")).toBe("2026-12-24 18:30");
expect(formatDate("2026-03-07T23:59:00")).toBe("2026-03-07");
expect(formatDateTime("not a date")).toBe("not a date");
expect(formatDate("")).toBe("");
});
});

View file

@ -7,7 +7,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
const invoke = vi.hoisted(() => vi.fn()); const invoke = vi.hoisted(() => vi.fn());
vi.mock("@tauri-apps/api/core", () => ({ invoke })); vi.mock("@tauri-apps/api/core", () => ({ invoke }));
import { listCommands, run, runWaiting, toEngineError, userMessage } from "../src/ipc"; import { listCommands, run, runWaiting, toEngineError } from "../src/ipc";
describe("run", () => { describe("run", () => {
beforeEach(() => { beforeEach(() => {
@ -66,13 +66,3 @@ describe("toEngineError", () => {
expect(toEngineError({ code: 1, message: "x" }).code).toBe("ipc"); 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");
});
});

View file

@ -29,7 +29,7 @@ import SettingsDialog from "../../src/components/settings/SettingsDialog.vue";
const ENGINE_COMMANDS = [ const ENGINE_COMMANDS = [
{ id: "app.about", label: "About Lutra", menuPath: "Help/About Lutra", defaultShortcut: null, params: "", enabled: true, ui: false }, { id: "app.about", label: "About Lutra", menuPath: "Help/About Lutra", defaultShortcut: null, params: "", enabled: true, ui: false },
{ id: "app.quit", label: "Quit", menuPath: "File/Quit", defaultShortcut: "Mod+Q", params: "", enabled: true, ui: false }, { id: "app.quit", label: "Quit", menuPath: "File/Quit", defaultShortcut: "Mod+Q", params: "", enabled: true, ui: false },
{ id: "buffer.close", label: "Close Tab", menuPath: "File/Close Tab", defaultShortcut: "Mod+W", params: "", enabled: false, ui: false }, { id: "buffer.close", label: "Close Buffer", menuPath: "File/Close Tab", defaultShortcut: "Mod+W", params: "", enabled: false, ui: false },
{ id: "buffer.edit", label: "Edit Buffer", menuPath: null, defaultShortcut: null, params: "", enabled: true, ui: false }, { id: "buffer.edit", label: "Edit Buffer", menuPath: null, defaultShortcut: null, params: "", enabled: true, ui: false },
{ id: "file.save", label: "Save", menuPath: "File/Save", defaultShortcut: "Mod+S", params: "", enabled: true, ui: false }, { id: "file.save", label: "Save", menuPath: "File/Save", defaultShortcut: "Mod+S", params: "", enabled: true, ui: false },
{ id: "file.saveAll", label: "Save All", menuPath: "File/Save All", defaultShortcut: "Mod+Alt+S", params: "", enabled: true, ui: false }, { id: "file.saveAll", label: "Save All", menuPath: "File/Save All", defaultShortcut: "Mod+Alt+S", params: "", enabled: true, ui: false },

View file

@ -3,8 +3,7 @@
* a toast, auto-dismiss of info toasts with fake timers, the overflow into * a toast, auto-dismiss of info toasts with fake timers, the overflow into
* "+n more", ARIA roles, keyboard closing, engine `notification` and * "+n more", ARIA roles, keyboard closing, engine `notification` and
* `watchFailed` events (including untrusted fields), and the replay * `watchFailed` events (including untrusted fields), and the replay
* duplicate guard, and keeping the stack off registered areas such as the * duplicate guard.
* commit box.
*/ */
import { mount, type VueWrapper } from "@vue/test-utils"; import { mount, type VueWrapper } from "@vue/test-utils";
import { createPinia, setActivePinia, type Pinia } from "pinia"; import { createPinia, setActivePinia, type Pinia } from "pinia";
@ -22,8 +21,6 @@ import {
MAX_VISIBLE, MAX_VISIBLE,
notificationFromEvent, notificationFromEvent,
notificationText, notificationText,
STACK_BOTTOM,
stackBottom,
useNotificationsStore, useNotificationsStore,
} from "../../src/stores/notifications"; } from "../../src/stores/notifications";
@ -280,33 +277,3 @@ describe("NotificationStack", () => {
expect(stack.find('[data-test="toast"]').exists()).toBe(false); expect(stack.find('[data-test="toast"]').exists()).toBe(false);
}); });
}); });
describe("keeping areas clear", () => {
it("places the stack above an area it would cover, and ignores hidden or distant ones", () => {
const box = { left: 0, right: 1000, top: 700, bottom: 780 };
expect(stackBottom(1000, 800, [])).toBe(STACK_BOTTOM);
expect(stackBottom(1000, 800, [box])).toBe(108);
expect(stackBottom(1000, 800, [{ left: 0, right: 0, top: 0, bottom: 0 }])).toBe(STACK_BOTTOM);
expect(stackBottom(1000, 800, [{ ...box, right: 500 }])).toBe(STACK_BOTTOM);
expect(stackBottom(1000, 800, [box, { ...box, top: 600 }])).toBe(208);
});
it("moves the shown stack above a registered element until it is released", async () => {
Object.assign(window, { innerWidth: 1000, innerHeight: 800 });
const store = useNotificationsStore();
const commit = document.createElement("form");
commit.getBoundingClientRect = () => new DOMRect(0, 700, 1000, 80);
document.body.append(commit);
store.notify({ level: "warning", message: "conflicts" });
const stack = mountStack();
await stack.vm.$nextTick();
expect(stack.get('[data-test="toasts"]').attributes("style")).toContain(`bottom: ${String(STACK_BOTTOM)}px`);
const release = store.keepClearOf(commit);
await stack.vm.$nextTick();
expect(stack.get('[data-test="toasts"]').attributes("style")).toContain("bottom: 108px");
release();
await stack.vm.$nextTick();
expect(stack.get('[data-test="toasts"]').attributes("style")).toContain(`bottom: ${String(STACK_BOTTOM)}px`);
commit.remove();
});
});

View file

@ -112,7 +112,9 @@ describe("RecoveryDialog", () => {
"src/b.php", "src/b.php",
"c.php", "c.php",
]); ]);
expect(rows[0]?.text()).toMatch(/Saved \d{4}-\d{2}-\d{2} \d{2}:\d{2}/); expect(rows[0]?.text()).toContain(
`Saved ${new Date(ENTRIES[0]?.savedAt ?? 0).toLocaleString()}`,
);
expect(rows[0]?.find("[data-test=recovery-changed]").exists()).toBe(false); expect(rows[0]?.find("[data-test=recovery-changed]").exists()).toBe(false);
expect(rows[1]?.get("[data-test=recovery-changed]").text()).toBe( expect(rows[1]?.get("[data-test=recovery-changed]").text()).toBe(
"The file changed on disk since then", "The file changed on disk since then",

View file

@ -361,13 +361,13 @@ describe("settings dialog", () => {
expect((input().element as HTMLInputElement).value).toBe("20"); expect((input().element as HTMLInputElement).value).toBe("20");
}); });
it("shows the engine's error for a value it refuses, without the key the row already names", async () => { it("shows the engine's error for a value it refuses", async () => {
const wrapper = await mountDialog(); const wrapper = await mountDialog();
await open(wrapper); await open(wrapper);
await useSettingsStore(pinia).set("editor.fontSize", 2); await useSettingsStore(pinia).set("editor.fontSize", 2);
await wrapper.find("[data-section=editor]").trigger("click"); await wrapper.find("[data-section=editor]").trigger("click");
expect(row(wrapper, "editor.fontSize").find("[data-test=settings-error]").text()).toBe( expect(row(wrapper, "editor.fontSize").find("[data-test=settings-error]").text()).toBe(
"expected an integer from 8 to 48", "editor.fontSize: expected an integer from 8 to 48",
); );
}); });

View file

@ -40,7 +40,6 @@ function stringEntry(key: string, section: string): Record<string, unknown> {
labelKey: `settings.${key}.label`, labelKey: `settings.${key}.label`,
descriptionKey: `settings.${key}.description`, descriptionKey: `settings.${key}.description`,
section, section,
path: /(path|executable)$/i.test(key),
}; };
} }
@ -160,10 +159,6 @@ beforeEach(() => {
return Promise.resolve({ values: Object.fromEntries(keys.map((k) => [k, values[k]])) }); return Promise.resolve({ values: Object.fromEntries(keys.map((k) => [k, values[k]])) });
} }
case "settings.set": 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") { if (params.value === "/does/not/exist") {
return Promise.reject(Object.assign(new Error("x"), { code: "invalid_params", message: "no such file" })); return Promise.reject(Object.assign(new Error("x"), { code: "invalid_params", message: "no such file" }));
} }
@ -187,13 +182,12 @@ afterEach(() => {
}); });
describe("string setting rules", () => { describe("string setting rules", () => {
it("treats the settings the engine marks as paths as paths", () => { it("treats keys ending in path or executable as paths", () => {
expect(isPathSetting(defOf("php.executable"))).toBe(true); expect(isPathSetting(defOf("php.executable"))).toBe(true);
expect(isPathSetting(defOf("phpactor.path"))).toBe(true); expect(isPathSetting(defOf("phpactor.path"))).toBe(true);
expect(isPathSetting(defOf("git.executable"))).toBe(true); expect(isPathSetting(defOf("git.executable"))).toBe(true);
expect(isPathSetting(defOf("x.pharPath"))).toBe(true); expect(isPathSetting(defOf("x.pharPath"))).toBe(true);
expect(isPathSetting(defOf("editor.name"))).toBe(false); 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); expect(isPathSetting({ ...defOf("php.executable"), type: "int" })).toBe(false);
}); });
@ -203,16 +197,16 @@ describe("string setting rules", () => {
expect(placeholderOf(defOf("editor.name"))).toBe(""); expect(placeholderOf(defOf("editor.name"))).toBe("");
}); });
it("refuses long texts and control characters, and leaves paths to the engine", () => { it("refuses long texts, control characters, quoted and padded paths", () => {
const php = defOf("php.executable"); const php = defOf("php.executable");
const name = defOf("editor.name"); const name = defOf("editor.name");
expect(checkString(php, "C:\\php\\php.exe")).toBeNull(); expect(checkString(php, "C:\\php\\php.exe")).toBeNull();
expect(checkString(php, "")).toBeNull(); expect(checkString(php, "")).toBeNull();
expect(checkString(php, "/opt/my php/php")).toBeNull(); expect(checkString(php, "/opt/my php/php")).toBeNull();
expect(checkString(php, '"C:\\Program Files\\php\\php.exe"')).toBeNull(); expect(checkString(php, '"C:\\Program Files\\php\\php.exe"')).toBe("Remove the quotes around the path");
expect(checkString(php, "'/opt/php'")).toBeNull(); expect(checkString(php, "'/opt/php'")).toBe("Remove the quotes around the path");
expect(checkString(php, " /opt/php")).toBeNull(); expect(checkString(php, " /opt/php")).toBe("Remove the spaces at the start or end of the path");
expect(checkString(php, "/opt/php\t")).toBeNull(); expect(checkString(php, "/opt/php\t")).toBe("Remove tabs, line breaks and other control characters");
expect(checkString(name, " padded is fine ")).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))).toBeNull();
expect(checkString(name, "ä".repeat(MAX_STRING_BYTES / 2 + 1))).toBe(`Enter at most ${String(MAX_STRING_BYTES)} bytes`); expect(checkString(name, "ä".repeat(MAX_STRING_BYTES / 2 + 1))).toBe(`Enter at most ${String(MAX_STRING_BYTES)} bytes`);
@ -244,16 +238,16 @@ describe("string and path controls", () => {
expect(row(wrapper, "php.executable").find("[data-test=settings-error]").exists()).toBe(false); expect(row(wrapper, "php.executable").find("[data-test=settings-error]").exists()).toBe(false);
}); });
it("shows the engine's refusal of a quoted path in place and keeps the typed text", async () => { it("refuses a quoted path in place and keeps the typed text", async () => {
const wrapper = await openDialog(); const wrapper = await openDialog();
await commit(wrapper, "php.executable", '"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()).toEqual([]);
const php = row(wrapper, "php.executable"); const php = row(wrapper, "php.executable");
expect(php.find("[data-test=settings-error]").text()).toBe("Remove the quotes around the path"); 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").attributes("aria-invalid")).toBe("true");
expect((php.find("input").element as HTMLInputElement).value).toBe('"C:\\php\\php.exe"'); expect((php.find("input").element as HTMLInputElement).value).toBe('"C:\\php\\php.exe"');
await commit(wrapper, "php.executable", "C:\\php\\php.exe"); await commit(wrapper, "php.executable", "C:\\php\\php.exe");
expect(sets().at(-1)).toEqual({ key: "php.executable", value: "C:\\php\\php.exe" }); expect(sets()).toEqual([{ key: "php.executable", value: "C:\\php\\php.exe" }]);
expect(php.find("[data-test=settings-error]").exists()).toBe(false); expect(php.find("[data-test=settings-error]").exists()).toBe(false);
}); });

View file

@ -383,15 +383,6 @@ describe("the Changes store", () => {
}); });
describe("the Changes window", () => { describe("the Changes window", () => {
it("keeps toasts off the commit box while it is mounted", async () => {
const wrapper = await mountChanges();
const notifications = useNotificationsStore(pinia);
expect(notifications.keepClear).toEqual([wrapper.get("[data-test=changes-commit]").element]);
mounted = mounted.filter((m) => m !== wrapper);
wrapper.unmount();
expect(notifications.keepClear).toEqual([]);
});
it("shows the branch, the counts and the three groups", async () => { it("shows the branch, the counts and the three groups", async () => {
const wrapper = await mountChanges(); const wrapper = await mountChanges();
expect(wrapper.get("[data-test=changes-status]").text()).toBe("main: 3 staged, 2 changed, 1 untracked"); expect(wrapper.get("[data-test=changes-status]").text()).toBe("main: 3 staged, 2 changed, 1 untracked");

View file

@ -416,29 +416,6 @@ describe("merging", () => {
expect(useNotificationsStore(pinia).toasts.some((n) => n.text.includes("cancelled"))).toBe(true); expect(useNotificationsStore(pinia).toasts.some((n) => n.text.includes("cancelled"))).toBe(true);
}); });
it("closes the conflict toast once no conflict is left, and a new conflicted merge replaces it", async () => {
await mountDialog();
const notifications = useNotificationsStore(pinia);
const conflictToasts = (): number => notifications.toasts.filter((n) => n.text.includes("stopped on conflicts")).length;
await runCommand("vcs.merge", { branch: "feature" });
await runCommand("vcs.merge", { branch: "feature" });
expect(conflictToasts()).toBe(1);
gitStatus = { ...gitStatus, files: [{ path: "b.php", index: "modified", worktree: "unmodified" }] };
await useVcsStatusStore(pinia).refresh();
await flushPromises();
expect(conflictToasts()).toBe(0);
});
it("closes the conflict toast when the merge is aborted", async () => {
const wrapper = await mountDialog();
await runCommand("vcs.merge", { branch: "feature" });
expect(useNotificationsStore(pinia).toasts.some((n) => n.text.includes("stopped on conflicts"))).toBe(true);
await runCommand("vcs.abortMerge");
await wrapper.get("[data-test=merge-abort]").trigger("click");
await flushPromises();
expect(useNotificationsStore(pinia).toasts.some((n) => n.text.includes("stopped on conflicts"))).toBe(false);
});
it("lists the other branches and merges the one chosen", async () => { it("lists the other branches and merges the one chosen", async () => {
const wrapper = await mountDialog(); const wrapper = await mountDialog();
await runCommand("vcs.merge"); await runCommand("vcs.merge");