From 750ecf5e51ca2fb0257fca587e19e31ad62bcdb1 Mon Sep 17 00:00:00 2001 From: danny Date: Mon, 2 Nov 2026 18:53:08 +0100 Subject: [PATCH 1/5] F1: conflict toast closes when the merge ends, toasts keep off the commit box The merge store dismisses its conflict warning once the status lists no conflicted file (resolved, committed or aborted) and replaces it on a new conflicted merge. The toast stack moves above areas registered with keepClearOf; the Changes window registers its commit box. Co-Authored-By: Claude Opus 5.5 --- .../notifications/NotificationStack.vue | 57 ++++++++++++++- .../vcs/changes/ChangesToolWindow.vue | 20 +++++- ui/src/components/vcs/merge/merge.ts | 29 +++++++- ui/src/stores/notifications.ts | 71 ++++++++++++++++++- ui/tests/notifications/notifications.test.ts | 35 ++++++++- ui/tests/vcs/ChangesToolWindow.test.ts | 9 +++ ui/tests/vcs/Merge.test.ts | 23 ++++++ 7 files changed, 235 insertions(+), 9 deletions(-) diff --git a/ui/src/components/notifications/NotificationStack.vue b/ui/src/components/notifications/NotificationStack.vue index c9d9bc3..a3aebc1 100644 --- a/ui/src/components/notifications/NotificationStack.vue +++ b/ui/src/components/notifications/NotificationStack.vue @@ -8,13 +8,65 @@ * 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 * 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 { onBeforeUnmount, onMounted, ref, watch } from "vue"; import { t } from "../../i18n"; -import { useNotificationsStore, type NotificationLevel } from "../../stores/notifications"; +import { STACK_BOTTOM, stackBottom, useNotificationsStore, type NotificationLevel } from "../../stores/notifications"; 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. */ const ICONS = { info: Info, warning: TriangleAlert, error: CircleAlert } as const; @@ -32,6 +84,7 @@ function roleOf(level: NotificationLevel): "status" | "alert" {
@@ -85,14 +138,12 @@ function roleOf(level: NotificationLevel): "status" | "alert" { .toasts { position: fixed; right: 16px; - bottom: 36px; z-index: 100; display: flex; flex-direction: column; align-items: flex-end; gap: 8px; width: min(420px, calc(100vw - 32px)); - max-height: calc(100vh - 72px); overflow-y: auto; user-select: text; } diff --git a/ui/src/components/vcs/changes/ChangesToolWindow.vue b/ui/src/components/vcs/changes/ChangesToolWindow.vue index 46c74d0..26d6d72 100644 --- a/ui/src/components/vcs/changes/ChangesToolWindow.vue +++ b/ui/src/components/vcs/changes/ChangesToolWindow.vue @@ -25,13 +25,14 @@ * Open, and Add to .gitignore for untracked files. * - **Commit box:** the message, an Amend checkbox and Commit. Commit * saves dirty buffers first (`flushDirty`); `Mod+Enter` in the box - * commits too. + * commits too. Toasts never cover the box: it is registered with the + * notifications store's `keepClearOf`. * - State lives in the Changes store (`changes.ts`), so the status and the * message survive hiding the window. Icons are Lucide's; colours are * tokens. */ import { Archive, ArchiveRestore, RefreshCw } from "@lucide/vue"; -import { computed, nextTick, onMounted, ref, watch } from "vue"; +import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue"; import { useCommandsStore } from "../../../commands/store"; import { isMac } from "../../../commands/keymap"; import { t } from "../../../i18n"; @@ -50,6 +51,12 @@ const list = ref(null); /** The commit message box. */ const messageBox = ref(null); +/** The commit box, kept clear of toasts. */ +const commitBox = ref(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. */ const menu = ref<{ row: ChangeRow; x: number; y: number } | null>(null); @@ -317,6 +324,14 @@ watch(() => changes.focusRequest, takeFocus); onMounted(() => { void takeFocus(); + if (commitBox.value) { + releaseCommitBox = notifications.keepClearOf(commitBox.value); + } +}); + +onBeforeUnmount(() => { + releaseCommitBox?.(); + releaseCommitBox = null; }); watch( @@ -465,6 +480,7 @@ watch( @open="openRow" />
{ const busy = ref(false); /** Bumped on every load, so only the newest one lands. */ 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. */ const conflicts = computed(() => @@ -177,6 +183,23 @@ export const useMergeStore = defineStore("merge", () => { .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. */ const currentBranch = computed(() => status.snapshot?.repo?.branch ?? null); @@ -254,8 +277,9 @@ export const useMergeStore = defineStore("merge", () => { return null; } await status.refresh(); + dismissConflictToast(); if (answer.result === "conflicts") { - notifications.notify({ + conflictToast = notifications.notify({ level: "warning", messageKey: "notification.vcs.mergeConflicts", params: { branch, count: String(answer.conflicts.length) }, @@ -292,6 +316,7 @@ export const useMergeStore = defineStore("merge", () => { return false; } await status.refresh(); + dismissConflictToast(); notifications.notify({ level: "info", messageKey: "notification.vcs.mergeAborted" }); close(); return true; diff --git a/ui/src/stores/notifications.ts b/ui/src/stores/notifications.ts index 9668dcf..b300a18 100644 --- a/ui/src/stores/notifications.ts +++ b/ui/src/stores/notifications.ts @@ -10,9 +10,12 @@ * Info toasts dismiss themselves after {@link INFO_TIMEOUT_MS}; warnings * and errors stay until closed. At most {@link MAX_VISIBLE} toasts show; * 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 { computed, ref } from "vue"; +import { computed, ref, shallowRef } from "vue"; import { hasMessage, t, type MessageParams } from "../i18n"; import { onEngineEvent, type EngineError, type EngineEventPayload } from "../ipc"; @@ -34,6 +37,55 @@ export const KEY_WATCH_FAILED = "notification.watch.failed"; /** Catalog key of the toast for a failed command. Params: `command`, `message`. */ 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. */ export interface Toast { /** Unique id: the engine's (`n1`…) or a frontend one (`ui1`…). */ @@ -134,6 +186,8 @@ export const useNotificationsStore = defineStore("notifications", () => { let made = 0; /** Auto-dismiss timers of info toasts, by id. */ const timers = new Map>(); + /** Elements the stack must not cover, in registration order. */ + const keepClear = shallowRef([]); /** Ends the engine event subscription; set while started. */ let unsubscribe: (() => void) | null = null; @@ -228,6 +282,19 @@ export const useNotificationsStore = defineStore("notifications", () => { 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". */ function expand(): void { expanded.value = true; @@ -262,6 +329,8 @@ export const useNotificationsStore = defineStore("notifications", () => { visible, hiddenCount, expanded, + keepClear, + keepClearOf, notify, notifyError, dismiss, diff --git a/ui/tests/notifications/notifications.test.ts b/ui/tests/notifications/notifications.test.ts index c0b490b..649d0e1 100644 --- a/ui/tests/notifications/notifications.test.ts +++ b/ui/tests/notifications/notifications.test.ts @@ -3,7 +3,8 @@ * a toast, auto-dismiss of info toasts with fake timers, the overflow into * "+n more", ARIA roles, keyboard closing, engine `notification` and * `watchFailed` events (including untrusted fields), and the replay - * duplicate guard. + * duplicate guard, and keeping the stack off registered areas such as the + * commit box. */ import { mount, type VueWrapper } from "@vue/test-utils"; import { createPinia, setActivePinia, type Pinia } from "pinia"; @@ -21,6 +22,8 @@ import { MAX_VISIBLE, notificationFromEvent, notificationText, + STACK_BOTTOM, + stackBottom, useNotificationsStore, } from "../../src/stores/notifications"; @@ -277,3 +280,33 @@ describe("NotificationStack", () => { 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(); + }); +}); diff --git a/ui/tests/vcs/ChangesToolWindow.test.ts b/ui/tests/vcs/ChangesToolWindow.test.ts index 38c465a..ae5aee6 100644 --- a/ui/tests/vcs/ChangesToolWindow.test.ts +++ b/ui/tests/vcs/ChangesToolWindow.test.ts @@ -383,6 +383,15 @@ describe("the Changes store", () => { }); 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 () => { const wrapper = await mountChanges(); expect(wrapper.get("[data-test=changes-status]").text()).toBe("main: 3 staged, 2 changed, 1 untracked"); diff --git a/ui/tests/vcs/Merge.test.ts b/ui/tests/vcs/Merge.test.ts index a52dbb4..9deceef 100644 --- a/ui/tests/vcs/Merge.test.ts +++ b/ui/tests/vcs/Merge.test.ts @@ -416,6 +416,29 @@ describe("merging", () => { 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 () => { const wrapper = await mountDialog(); await runCommand("vcs.merge"); From 8a05f508c8b0c5b87640634b469acfede9ab2cb2 Mon Sep 17 00:00:00 2001 From: danny Date: Mon, 2 Nov 2026 19:02:08 +0100 Subject: [PATCH 2/5] F1: settings.set refuses quoted, padded and control-character paths Path settings get Kind::Path, checked by check_path in the engine: the one validator for settings.set from agents, the CLI and the dialog. settings.list marks them with path: true; the dialog uses that flag for Browse and shows the engine's reason (userMessage drops the invalid-params prefix). Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/settings.rs | 94 +++++++++++++++++++-- ui/src/components/settings/stringSetting.ts | 41 +++------ ui/src/i18n/en.json | 2 - ui/src/ipc.ts | 11 +++ ui/src/stores/settings.ts | 13 ++- ui/tests/ipc.test.ts | 12 ++- ui/tests/settings/SettingsDialog.test.ts | 4 +- ui/tests/settings/StringSettings.test.ts | 24 ++++-- 8 files changed, 150 insertions(+), 51 deletions(-) diff --git a/crates/engine/src/settings.rs b/crates/engine/src/settings.rs index 1d317bd..9792f7d 100644 --- a/crates/engine/src/settings.rs +++ b/crates/engine/src/settings.rs @@ -36,11 +36,46 @@ pub enum Kind { }, /// `true` or `false`. Bool, - /// Any string of at most `max_len` bytes, such as a file path. + /// Any string of at most `max_len` bytes without NUL. Str { /// Longest accepted value in bytes. max_len: usize, }, + /// A file path, or empty for "detect it": a string checked by + /// [`check_path`], the one validator for `settings.set` and the + /// settings dialog (which shows its message). + Path { + /// Longest accepted value in bytes. + max_len: usize, + }, +} + +/// Checks a path setting's text: at most `max_len` bytes, no control +/// characters (U+0000–U+001F, U+007F), not wrapped in quotes (as copied +/// from a shell or the file manager) and no spaces at either end. Values +/// are refused, never trimmed, so what is stored is what was typed. +/// +/// # Errors +/// What to change, as a sentence the dialog shows under the field. +pub fn check_path(text: &str, max_len: usize) -> Result<(), String> { + if text.len() > max_len { + return Err(format!("Enter at most {max_len} bytes")); + } + if text.chars().any(|c| c < ' ' || c == '\u{7f}') { + return Err("Remove tabs, line breaks and other control characters".into()); + } + let trimmed = text.trim(); + let quoted = trimmed.len() >= 2 + && ['"', '\''] + .iter() + .any(|q| trimmed.starts_with(*q) && trimmed.ends_with(*q)); + if quoted { + return Err("Remove the quotes around the path".into()); + } + if trimmed != text { + return Err("Remove the spaces at the start or end of the path".into()); + } + Ok(()) } /// The default value of a setting. @@ -121,6 +156,12 @@ impl Def { self.key )), }, + Kind::Path { max_len } => match value.as_str() { + Some(s) => { + check_path(s, max_len).map_err(|reason| format!("{}: {reason}", self.key)) + } + None => Err(format!("{} must be a path string, got {value}", self.key)), + }, } } @@ -130,7 +171,7 @@ impl Def { Kind::Enum(values) => ("enum", Some(values.to_vec()), None, None), Kind::Int { min, max } => ("int", None, Some(min), Some(max)), Kind::Bool => ("bool", None, None, None), - Kind::Str { .. } => ("string", None, None, None), + Kind::Str { .. } | Kind::Path { .. } => ("string", None, None, None), }; SettingInfo { key: self.key, @@ -139,6 +180,7 @@ impl Def { enum_values, min, max, + path: matches!(self.kind, Kind::Path { .. }), label_key: self.label_key, description_key: self.description_key, section: self.section, @@ -166,6 +208,10 @@ pub struct SettingInfo { /// Largest value of an int. #[serde(skip_serializing_if = "Option::is_none")] pub max: Option, + /// Whether a string is a file path ([`Kind::Path`]): the dialog adds + /// "Browse…" and shows [`check_path`]'s refusals. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub path: bool, /// Catalog key of the label. pub label_key: &'static str, /// Catalog key of the description. @@ -202,7 +248,7 @@ pub const DEFS: &[Def] = &[ }, Def { key: "php.executable", - kind: Kind::Str { max_len: 4096 }, + kind: Kind::Path { max_len: 4096 }, default: DefaultValue::Str(""), label_key: "settings.php.executable.label", description_key: "settings.php.executable.description", @@ -210,7 +256,7 @@ pub const DEFS: &[Def] = &[ }, Def { key: "phpactor.path", - kind: Kind::Str { max_len: 4096 }, + kind: Kind::Path { max_len: 4096 }, default: DefaultValue::Str(""), label_key: "settings.phpactor.path.label", description_key: "settings.phpactor.path.description", @@ -277,7 +323,7 @@ pub const DEFS: &[Def] = &[ }, Def { key: "git.executable", - kind: Kind::Str { max_len: 4096 }, + kind: Kind::Path { max_len: 4096 }, default: DefaultValue::Str(""), label_key: "settings.git.executable.label", description_key: "settings.git.executable.description", @@ -651,6 +697,44 @@ mod tests { assert_eq!(s.get("editor.fontSize"), Some(json!(14))); } + #[test] + fn path_settings_refuse_quotes_padding_and_control_characters() { + let mut s = Settings::in_memory(); + for key in ["php.executable", "phpactor.path", "git.executable"] { + for good in ["", r"C:\php\php.exe", "/opt/my php/php", "'"] { + assert!(s.set(key, json!(good)).is_ok(), "{key} {good:?}"); + } + for (bad, reason) in [ + (" php", "spaces"), + ("php ", "spaces"), + (r#""C:\Program Files\php\php.exe""#, "quotes"), + ("'/opt/php'", "quotes"), + (r#" "/opt/php" "#, "quotes"), + ("/opt/php\t", "control"), + ("/opt/\u{7f}php", "control"), + ] { + let Err(SetError::Invalid(message)) = s.set(key, json!(bad)) else { + panic!("{key} accepted {bad:?}"); + }; + assert!(message.starts_with(&format!("{key}: ")), "{message}"); + assert!(message.contains(reason), "{message}"); + } + assert!(s.set(key, json!("x".repeat(4097))).is_err()); + assert!(s.set(key, json!(1)).is_err()); + assert!(DEFS.iter().any(|d| d.key == key && d.info().path)); + } + assert!(!DEFS.iter().any(|d| d.key == "editor.fontSize" && d.info().path)); + } + + #[test] + fn a_stored_padded_path_counts_as_unset() { + let dir = tempfile::tempdir().unwrap(); + fs::write(dir.path().join(FILE_NAME), r#"{"php.executable": " php"}"#).unwrap(); + let (s, problem) = Settings::load(dir.path()); + assert!(problem.is_none()); + assert_eq!(s.get("php.executable"), Some(json!(""))); + } + #[test] fn autosave_defaults_and_validation() { let mut s = Settings::in_memory(); diff --git a/ui/src/components/settings/stringSetting.ts b/ui/src/components/settings/stringSetting.ts index b84f377..4312cc7 100644 --- a/ui/src/components/settings/stringSetting.ts +++ b/ui/src/components/settings/stringSetting.ts @@ -5,8 +5,9 @@ * * The rules work on any string setting `settings.list` reports, so a new * one (such as `git.executable`) gets the control without changes here. - * The engine still validates every value; these checks only catch mistakes - * early and say how to fix them. + * Path settings are checked only by the engine (`check_path` in + * `crates/engine/src/settings.rs`), the one validator shared with + * `settings.set` from agents and the CLI; the dialog shows its reason. */ import { t } from "../../i18n"; import type { SettingDef } from "../../stores/settings"; @@ -14,9 +15,6 @@ import type { SettingDef } from "../../stores/settings"; /** Longest value in UTF-8 bytes; the engine's limit for string settings. */ export const MAX_STRING_BYTES = 4096; -/** Endings of a key's last segment that mark a path setting. */ -const PATH_ENDINGS = ["path", "executable"]; - /** * Whether a text has control characters (U+0000–U+001F, U+007F), which no * single-line setting needs. @@ -34,18 +32,13 @@ function hasControlChars(text: string): boolean { } /** - * Whether a setting holds a file path: a string setting whose key ends in - * `path` or `executable` (`phpactor.path`, `php.executable`, - * `git.executable`, `x.pharPath`). + * Whether a setting holds a file path: a string setting the engine marks + * with `path` (`php.executable`, `phpactor.path`, `git.executable`). * * @param def - the setting. */ export function isPathSetting(def: SettingDef): boolean { - if (def.type !== "string") { - return false; - } - const last = (def.key.split(".").at(-1) ?? "").toLowerCase(); - return PATH_ENDINGS.some((ending) => last.endsWith(ending)); + return def.type === "string" && def.path; } /** @@ -60,32 +53,24 @@ export function placeholderOf(def: SettingDef): string { } /** - * Checks a typed value before it goes to `settings.set`. - * - * - Longer than {@link MAX_STRING_BYTES} UTF-8 bytes, or with control - * characters: refused for every string setting. - * - Paths: refused when wrapped in quotes (as copied from a shell or the - * file manager) or with spaces at either end. + * Checks a typed value before it goes to `settings.set`: longer than + * {@link MAX_STRING_BYTES} UTF-8 bytes, or with control characters, is + * refused. Paths are left to the engine, which refuses the same and + * quoted or padded paths too. * * @param def - the setting. * @param text - the typed value. * @returns the error text from the catalog, or null when the value may be sent. */ export function checkString(def: SettingDef, text: string): string | null { + if (isPathSetting(def)) { + return null; + } if (new TextEncoder().encode(text).length > MAX_STRING_BYTES) { return t("settings.error.stringTooLong", { max: MAX_STRING_BYTES }); } if (hasControlChars(text)) { return t("settings.error.stringControl"); } - if (!isPathSetting(def)) { - return null; - } - if (/^\s*(["']).*\1\s*$/.test(text) && text.trim().length >= 2) { - return t("settings.error.pathQuoted"); - } - if (text !== text.trim()) { - return t("settings.error.pathSpaces"); - } return null; } diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json index 9383992..fd45bdd 100644 --- a/ui/src/i18n/en.json +++ b/ui/src/i18n/en.json @@ -301,8 +301,6 @@ "settings.error.browseFailed": "The file picker could not open: {message}", "settings.error.int": "Enter a whole number", "settings.error.intRange": "Enter a whole number from {min} to {max}", - "settings.error.pathQuoted": "Remove the quotes around the path", - "settings.error.pathSpaces": "Remove the spaces at the start or end of the path", "settings.error.stringControl": "Remove tabs, line breaks and other control characters", "settings.error.stringTooLong": "Enter at most {max} bytes", "settings.git.executable.description": "Path to the git program (2.30 or newer) that Lutra runs for version control. Leave empty to use git from PATH.", diff --git a/ui/src/ipc.ts b/ui/src/ipc.ts index 2c2692a..baf84d2 100644 --- a/ui/src/ipc.ts +++ b/ui/src/ipc.ts @@ -254,6 +254,17 @@ export interface EngineError { message: string; } +/** + * The part of an engine error's message meant for a person: the reason + * without the engine's `invalid params for : ` prefix, which + * only repeats the command the caller just ran. + * + * @param error - the error. + */ +export function userMessage(error: EngineError): string { + return error.code === "invalid_params" ? error.message.replace(/^invalid params for [^:\s]+: /, "") : error.message; +} + /** Outcome of an engine call. */ export type RunResult = { ok: true; value: T } | { ok: false; error: EngineError }; diff --git a/ui/src/stores/settings.ts b/ui/src/stores/settings.ts index 1505309..a7951bd 100644 --- a/ui/src/stores/settings.ts +++ b/ui/src/stores/settings.ts @@ -19,7 +19,7 @@ import { defineStore } from "pinia"; import { reactive, ref } from "vue"; import { hasMessage, t } from "../i18n"; -import { onEngineEvent, run, type EngineEventPayload } from "../ipc"; +import { onEngineEvent, run, userMessage, type EngineError, type EngineEventPayload } from "../ipc"; import { setTokenOverride } from "../theme"; /** A setting value: settings are scalars. Values from the engine are unchecked. */ @@ -48,6 +48,8 @@ export interface SettingDef { descriptionKey: string; /** Section id; shown with `settings.section.`. */ section: string; + /** Whether a string setting holds a file path (the engine's `path` flag). */ + path: boolean; } /** A section of the dialog with its settings, in engine order. */ @@ -118,6 +120,7 @@ function toSettingDef(raw: unknown): SettingDef | null { labelKey, descriptionKey, section, + path: type === "string" && entry.path === true, }; } @@ -330,7 +333,8 @@ export const useSettingsStore = defineStore("settings", () => { } /** - * Stores the outcome of `settings.set` or `settings.reset`. + * Stores the outcome of `settings.set` or `settings.reset`. A refusal is + * kept as its reason, without the engine's command and key prefixes. * * @param key - the setting. * @param result - the command's outcome. @@ -338,10 +342,11 @@ export const useSettingsStore = defineStore("settings", () => { */ function settle( key: string, - result: { ok: true; value: unknown } | { ok: false; error: { message: string } }, + result: { ok: true; value: unknown } | { ok: false; error: EngineError }, ): boolean { if (!result.ok) { - errors[key] = clip(result.error.message); + const message = userMessage(result.error); + errors[key] = clip(message.startsWith(`${key}: `) ? message.slice(key.length + 2) : message); return false; } Reflect.deleteProperty(errors, key); diff --git a/ui/tests/ipc.test.ts b/ui/tests/ipc.test.ts index 63fd931..9c8e9b4 100644 --- a/ui/tests/ipc.test.ts +++ b/ui/tests/ipc.test.ts @@ -7,7 +7,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; const invoke = vi.hoisted(() => vi.fn()); vi.mock("@tauri-apps/api/core", () => ({ invoke })); -import { listCommands, run, runWaiting, toEngineError } from "../src/ipc"; +import { listCommands, run, runWaiting, toEngineError, userMessage } from "../src/ipc"; describe("run", () => { beforeEach(() => { @@ -66,3 +66,13 @@ describe("toEngineError", () => { expect(toEngineError({ code: 1, message: "x" }).code).toBe("ipc"); }); }); + +describe("userMessage", () => { + it("drops the engine's invalid params prefix and keeps other messages", () => { + expect(userMessage({ code: "invalid_params", message: "invalid params for search.find: unclosed group" })).toBe( + "unclosed group", + ); + expect(userMessage({ code: "failed", message: "invalid params for x.y: z" })).toBe("invalid params for x.y: z"); + expect(userMessage({ code: "invalid_params", message: "missing path" })).toBe("missing path"); + }); +}); diff --git a/ui/tests/settings/SettingsDialog.test.ts b/ui/tests/settings/SettingsDialog.test.ts index b961a84..4ed0175 100644 --- a/ui/tests/settings/SettingsDialog.test.ts +++ b/ui/tests/settings/SettingsDialog.test.ts @@ -361,13 +361,13 @@ describe("settings dialog", () => { expect((input().element as HTMLInputElement).value).toBe("20"); }); - it("shows the engine's error for a value it refuses", async () => { + it("shows the engine's error for a value it refuses, without the key the row already names", async () => { const wrapper = await mountDialog(); await open(wrapper); await useSettingsStore(pinia).set("editor.fontSize", 2); await wrapper.find("[data-section=editor]").trigger("click"); expect(row(wrapper, "editor.fontSize").find("[data-test=settings-error]").text()).toBe( - "editor.fontSize: expected an integer from 8 to 48", + "expected an integer from 8 to 48", ); }); diff --git a/ui/tests/settings/StringSettings.test.ts b/ui/tests/settings/StringSettings.test.ts index a58ed09..afff1b5 100644 --- a/ui/tests/settings/StringSettings.test.ts +++ b/ui/tests/settings/StringSettings.test.ts @@ -40,6 +40,7 @@ function stringEntry(key: string, section: string): Record { labelKey: `settings.${key}.label`, descriptionKey: `settings.${key}.description`, section, + path: /(path|executable)$/i.test(key), }; } @@ -159,6 +160,10 @@ beforeEach(() => { return Promise.resolve({ values: Object.fromEntries(keys.map((k) => [k, values[k]])) }); } case "settings.set": + if (typeof params.value === "string" && params.value.startsWith('"')) { + const message = `invalid params for settings.set: ${String(params.key)}: Remove the quotes around the path`; + return Promise.reject(Object.assign(new Error("x"), { code: "invalid_params", message })); + } if (params.value === "/does/not/exist") { return Promise.reject(Object.assign(new Error("x"), { code: "invalid_params", message: "no such file" })); } @@ -182,12 +187,13 @@ afterEach(() => { }); describe("string setting rules", () => { - it("treats keys ending in path or executable as paths", () => { + it("treats the settings the engine marks as paths as paths", () => { expect(isPathSetting(defOf("php.executable"))).toBe(true); expect(isPathSetting(defOf("phpactor.path"))).toBe(true); expect(isPathSetting(defOf("git.executable"))).toBe(true); expect(isPathSetting(defOf("x.pharPath"))).toBe(true); expect(isPathSetting(defOf("editor.name"))).toBe(false); + expect(isPathSetting({ ...defOf("php.executable"), path: false })).toBe(false); expect(isPathSetting({ ...defOf("php.executable"), type: "int" })).toBe(false); }); @@ -197,16 +203,16 @@ describe("string setting rules", () => { expect(placeholderOf(defOf("editor.name"))).toBe(""); }); - it("refuses long texts, control characters, quoted and padded paths", () => { + it("refuses long texts and control characters, and leaves paths to the engine", () => { const php = defOf("php.executable"); const name = defOf("editor.name"); expect(checkString(php, "C:\\php\\php.exe")).toBeNull(); expect(checkString(php, "")).toBeNull(); expect(checkString(php, "/opt/my php/php")).toBeNull(); - expect(checkString(php, '"C:\\Program Files\\php\\php.exe"')).toBe("Remove the quotes around the path"); - expect(checkString(php, "'/opt/php'")).toBe("Remove the quotes around the path"); - expect(checkString(php, " /opt/php")).toBe("Remove the spaces at the start or end of the path"); - expect(checkString(php, "/opt/php\t")).toBe("Remove tabs, line breaks and other control characters"); + expect(checkString(php, '"C:\\Program Files\\php\\php.exe"')).toBeNull(); + expect(checkString(php, "'/opt/php'")).toBeNull(); + expect(checkString(php, " /opt/php")).toBeNull(); + expect(checkString(php, "/opt/php\t")).toBeNull(); expect(checkString(name, " padded is fine ")).toBeNull(); expect(checkString(name, "ä".repeat(MAX_STRING_BYTES / 2))).toBeNull(); expect(checkString(name, "ä".repeat(MAX_STRING_BYTES / 2 + 1))).toBe(`Enter at most ${String(MAX_STRING_BYTES)} bytes`); @@ -238,16 +244,16 @@ describe("string and path controls", () => { expect(row(wrapper, "php.executable").find("[data-test=settings-error]").exists()).toBe(false); }); - it("refuses a quoted path in place and keeps the typed text", async () => { + it("shows the engine's refusal of a quoted path in place and keeps the typed text", async () => { const wrapper = await openDialog(); await commit(wrapper, "php.executable", '"C:\\php\\php.exe"'); - expect(sets()).toEqual([]); + expect(sets()).toEqual([{ key: "php.executable", value: '"C:\\php\\php.exe"' }]); const php = row(wrapper, "php.executable"); expect(php.find("[data-test=settings-error]").text()).toBe("Remove the quotes around the path"); expect(php.find("input").attributes("aria-invalid")).toBe("true"); expect((php.find("input").element as HTMLInputElement).value).toBe('"C:\\php\\php.exe"'); await commit(wrapper, "php.executable", "C:\\php\\php.exe"); - expect(sets()).toEqual([{ key: "php.executable", value: "C:\\php\\php.exe" }]); + expect(sets().at(-1)).toEqual({ key: "php.executable", value: "C:\\php\\php.exe" }); expect(php.find("[data-test=settings-error]").exists()).toBe(false); }); From f4dbc9188e5701ce8bb56ca19e01966504cb4603 Mon Sep 17 00:00:00 2001 From: danny Date: Mon, 2 Nov 2026 19:04:54 +0100 Subject: [PATCH 3/5] F1: lutra starts the desktop without passing on any handle lutra_proc::spawn_detached starts a program through CreateProcessW with bInheritHandles = FALSE and null standard handles (DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP as before), so lutra's output pipe closes when lutra exits. launch.rs uses it. Helper roles detached-plain/-proc show the standard library keeping the pipe open and spawn_detached not. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + apps/lutra-cli/Cargo.toml | 1 + apps/lutra-cli/src/launch.rs | 33 ++--- crates/proc/src/bin/lutra-proc-helper.rs | 41 ++++++ crates/proc/src/lib.rs | 81 +++++++++++ crates/proc/src/windows.rs | 171 +++++++++++++++++++++-- crates/proc/tests/process_tree.rs | 45 ++++++ 7 files changed, 340 insertions(+), 33 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 45a7cf0..c3a9bb1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2589,6 +2589,7 @@ dependencies = [ "lutra-control", "lutra-engine", "lutra-mcp", + "lutra-proc", "lutra-testkit", "proptest", "serde_json", diff --git a/apps/lutra-cli/Cargo.toml b/apps/lutra-cli/Cargo.toml index eb67709..245f79e 100644 --- a/apps/lutra-cli/Cargo.toml +++ b/apps/lutra-cli/Cargo.toml @@ -18,6 +18,7 @@ path = "src/main.rs" [dependencies] lutra-control.workspace = true lutra-mcp.workspace = true +lutra-proc.workspace = true serde_json = "1.0.154" [dev-dependencies] diff --git a/apps/lutra-cli/src/launch.rs b/apps/lutra-cli/src/launch.rs index 3d6be82..c4ad5f7 100644 --- a/apps/lutra-cli/src/launch.rs +++ b/apps/lutra-cli/src/launch.rs @@ -1,7 +1,6 @@ //! Finding and starting the desktop app when no Lutra is running. use std::path::{Path, PathBuf}; -use std::process::{Command, Stdio}; use std::thread; use std::time::{Duration, Instant}; @@ -70,11 +69,13 @@ fn resolve_link(path: PathBuf) -> PathBuf { std::fs::canonicalize(&path).unwrap_or(path) } -/// Starts `desktop` detached from this terminal (Windows: a detached process -/// in a new process group; Unix: a new process group, so a Ctrl-C or -/// hangup aimed at 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 +/// Starts `desktop` detached from this terminal through +/// [`lutra_proc::spawn_detached`] (Windows: a detached process in a new +/// process group that inherits none of this process's handles, so a script +/// reading `lutra`'s output through a pipe gets end of file as soon as +/// `lutra` exits; Unix: a new process group, so a Ctrl-C or hangup aimed at +/// 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 /// failed exit ends the wait early. /// @@ -82,25 +83,7 @@ fn resolve_link(path: PathBuf) -> PathBuf { /// A message if it cannot be started, exits early, or does not answer /// within [`START_TIMEOUT`]. pub fn start(desktop: &Path, dir: &Path) -> Result { - 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() + let mut child = lutra_proc::spawn_detached(desktop, &[]) .map_err(|e| format!("cannot start {}: {e}", desktop.display()))?; let deadline = Instant::now() + START_TIMEOUT; loop { diff --git a/crates/proc/src/bin/lutra-proc-helper.rs b/crates/proc/src/bin/lutra-proc-helper.rs index 389b531..b910b2c 100644 --- a/crates/proc/src/bin/lutra-proc-helper.rs +++ b/crates/proc/src/bin/lutra-proc-helper.rs @@ -16,6 +16,12 @@ //! - `tree-on-input`: reads one line from standard input first, then acts //! as `tree-plain`. A test adopts the helper in between, so the //! 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. @@ -32,6 +38,7 @@ fn main() -> ExitCode { let role = std::env::args().nth(1).unwrap_or_default(); match role.as_str() { "tree-plain" | "tree-proc" => tree(role == "tree-proc"), + "detached-plain" | "detached-proc" => detached(role == "detached-proc"), "tree-on-input" => { let mut line = String::new(); if std::io::stdin().lock().read_line(&mut line).is_err() { @@ -72,6 +79,40 @@ fn tree(guarded: bool) -> ExitCode { 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. fn grandchild() -> Command { let seconds = SLEEP.as_secs(); diff --git a/crates/proc/src/lib.rs b/crates/proc/src/lib.rs index 8f441b5..7fbfeed 100644 --- a/crates/proc/src/lib.rs +++ b/crates/proc/src/lib.rs @@ -37,9 +37,18 @@ //! integrated terminal's ConPTY shell, into a kill-on-close job and returns //! a [`Guard`] that holds it. [`enable_ctrl_c`] (Windows) undoes an //! 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::ops::{Deref, DerefMut}; +use std::path::Path; use std::process::{Command, ExitStatus}; #[cfg(unix)] @@ -147,6 +156,78 @@ 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 { + #[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> { + 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`] /// (Windows only, see [`adopt`]). Dropping it kills the process and /// everything it started. diff --git a/crates/proc/src/windows.rs b/crates/proc/src/windows.rs index c2aa990..8489d57 100644 --- a/crates/proc/src/windows.rs +++ b/crates/proc/src/windows.rs @@ -19,21 +19,29 @@ //! (`SetConsoleCtrlHandler(NULL, FALSE)`), so the terminal's shells pass //! 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, -//! Tool Help, thread and console APIs are only reachable through FFI. Every call gets +//! Tool Help, thread, process and console APIs are only reachable through FFI. Every call gets //! valid arguments by construction: handles come from `CreateJobObjectW`, -//! `CreateToolhelp32Snapshot` or `OpenThread` (owned by an [`OwnedHandle`] -//! right away) or from a live [`std::process::Child`], and the limit and -//! thread entry structures are plain C structs that are valid when zeroed. +//! `CreateToolhelp32Snapshot`, `OpenThread` or `CreateProcessW` (owned by an [`OwnedHandle`] +//! right away) or from a live [`std::process::Child`], strings passed in are +//! NUL-terminated UTF-16 buffers that outlive the call, and the limit, +//! thread entry, startup and process information structures are plain C +//! structs that are valid when zeroed. #![allow(unsafe_code)] +use std::ffi::OsStr; use std::io; +use std::os::windows::ffi::OsStrExt; use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle, RawHandle}; -use std::os::windows::process::CommandExt; -use std::process::Command; +use std::os::windows::process::{CommandExt, ExitStatusExt}; +use std::path::Path; +use std::process::{Command, ExitStatus}; -use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; +use windows_sys::Win32::Foundation::{INVALID_HANDLE_VALUE, WAIT_OBJECT_0, WAIT_TIMEOUT}; use windows_sys::Win32::System::Console::SetConsoleCtrlHandler; use windows_sys::Win32::System::Diagnostics::ToolHelp::{ CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next, @@ -44,7 +52,9 @@ use windows_sys::Win32::System::JobObjects::{ SetInformationJobObject, TerminateJobObject, }; use windows_sys::Win32::System::Threading::{ - CREATE_NO_WINDOW, CREATE_SUSPENDED, OpenThread, ResumeThread, THREAD_SUSPEND_RESUME, + CREATE_NEW_PROCESS_GROUP, CREATE_NO_WINDOW, CREATE_SUSPENDED, CreateProcessW, DETACHED_PROCESS, + GetExitCodeProcess, OpenThread, PROCESS_INFORMATION, ResumeThread, STARTF_USESTDHANDLES, + STARTUPINFOW, THREAD_SUSPEND_RESUME, WaitForSingleObject, }; /// The exit code a process killed with its job reports. @@ -201,3 +211,148 @@ fn resume_thread(tid: u32) -> io::Result<()> { } 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 { + 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::()).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> { + 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 { + let units: Vec = 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("e(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""#); + } +} diff --git a/crates/proc/tests/process_tree.rs b/crates/proc/tests/process_tree.rs index c9e5663..ed20814 100644 --- a/crates/proc/tests/process_tree.rs +++ b/crates/proc/tests/process_tree.rs @@ -135,3 +135,48 @@ fn dropping_an_adopt_guard_takes_the_tree_started_after_it() { assert_gone(reader); 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" + ); +} From 1b6bd1f8703bbcc6080bf722455e8ea06019204d Mon Sep 17 00:00:00 2001 From: danny Date: Mon, 2 Nov 2026 19:07:25 +0100 Subject: [PATCH 4/5] F1: the uninstaller keeps the Jump List of com.tyrveil.lutra The template's DeleteAppUserModelId cleared the Jump List of the app id every Lutra install shares, so removing a test or second install wiped the list of the one in use. Marked with a Lutra: comment; a desktop test fails if the call comes back. Also rustfmt of the settings test. Co-Authored-By: Claude Opus 5.5 --- apps/lutra-desktop/installer/installer.nsi | 7 ++++++- apps/lutra-desktop/src/main.rs | 10 ++++++++++ crates/engine/src/settings.rs | 6 +++++- 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/apps/lutra-desktop/installer/installer.nsi b/apps/lutra-desktop/installer/installer.nsi index ac88aad..115828a 100644 --- a/apps/lutra-desktop/installer/installer.nsi +++ b/apps/lutra-desktop/installer/installer.nsi @@ -867,7 +867,12 @@ Section Uninstall ; Remove shortcuts if not updating ${If} $UpdateMode <> 1 - !insertmacro DeleteAppUserModelId + ; Lutra: the template's `!insertmacro DeleteAppUserModelId` is left out. + ; 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 !insertmacro MUI_STARTMENU_GETFOLDER Application $AppStartMenuFolder diff --git a/apps/lutra-desktop/src/main.rs b/apps/lutra-desktop/src/main.rs index 8f62368..1512adc 100644 --- a/apps/lutra-desktop/src/main.rs +++ b/apps/lutra-desktop/src/main.rs @@ -408,4 +408,14 @@ mod tests { .collect(); 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()); + } } diff --git a/crates/engine/src/settings.rs b/crates/engine/src/settings.rs index 9792f7d..5f4ff5c 100644 --- a/crates/engine/src/settings.rs +++ b/crates/engine/src/settings.rs @@ -723,7 +723,11 @@ mod tests { 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)); + assert!( + !DEFS + .iter() + .any(|d| d.key == "editor.fontSize" && d.info().path) + ); } #[test] From 33a7185d7549b80bfd632707c65bf9bc1fbac81f Mon Sep 17 00:00:00 2001 From: danny Date: Mon, 2 Nov 2026 19:31:43 +0100 Subject: [PATCH 5/5] F1: cosmetics: regex error reason, one date format, Close Tab - Find shows a bad regex as "invalid pattern: unclosed group": the search crate keeps only the parser's reason, the UI drops the invalid-params prefix (userMessage). - Dates read YYYY-MM-DD / YYYY-MM-DD HH:mm in local time everywhere (i18n formatDate/formatDateTime): Log, stash list, blame, recovery. - buffer.close is "Close Tab" in the palette as in the menu; an engine test keeps palette labels starting with their menu item's wording. - Docs: architecture, install (Jump List), localization parity, checklist. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/buffer.rs | 2 +- crates/engine/src/engine.rs | 19 +++++++ crates/search/src/query.rs | 16 +++++- crates/search/tests/search.rs | 16 ++++-- docs/alpha-checklist.md | 5 +- docs/architecture.md | 8 +-- docs/install.md | 5 +- docs/localization-parity.md | 4 +- ui/src/components/editor/blame.ts | 15 ++---- ui/src/components/recovery/RecoveryDialog.vue | 4 +- ui/src/components/vcs/log/LogToolWindow.vue | 10 ++-- ui/src/components/vcs/stash/StashDialog.vue | 10 ++-- ui/src/i18n/index.ts | 52 +++++++++++++++++++ ui/src/stores/find.ts | 7 +-- ui/tests/find/FindToolWindow.test.ts | 4 +- ui/tests/i18n/catalog.test.ts | 16 +++++- ui/tests/menu/AppMenu.test.ts | 2 +- ui/tests/recovery/RecoveryDialog.test.ts | 4 +- 18 files changed, 147 insertions(+), 52 deletions(-) diff --git a/crates/engine/src/cmd/buffer.rs b/crates/engine/src/cmd/buffer.rs index 6dae200..8f4f949 100644 --- a/crates/engine/src/cmd/buffer.rs +++ b/crates/engine/src/cmd/buffer.rs @@ -197,7 +197,7 @@ impl Command for Close { fn spec(&self) -> &CommandSpec { &CommandSpec { id: "buffer.close", - label: "Close Buffer", + label: "Close Tab", menu_path: Some("File/Close Tab"), 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", diff --git a/crates/engine/src/engine.rs b/crates/engine/src/engine.rs index 6cf84cb..d6b6cb9 100644 --- a/crates/engine/src/engine.rs +++ b/crates/engine/src/engine.rs @@ -462,6 +462,25 @@ 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 = 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::::new()); + } + #[test] fn lists_commands_with_metadata() { let mut engine = Engine::new().unwrap(); diff --git a/crates/search/src/query.rs b/crates/search/src/query.rs index 5cfe997..836c32e 100644 --- a/crates/search/src/query.rs +++ b/crates/search/src/query.rs @@ -44,7 +44,7 @@ impl Search { .dfa_size_limit(REGEX_SIZE_LIMIT) .nest_limit(REGEX_NEST_LIMIT) .build(&query.pattern) - .map_err(|e| SearchError::InvalidPattern(e.to_string()))?; + .map_err(|e| SearchError::InvalidPattern(pattern_error(&e.to_string())))?; Ok(Self { matcher, filter: PathFilter::new(&query.include, &query.exclude)?, @@ -53,6 +53,20 @@ 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: `), 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::>().join(" ") +} + /// Include and exclude globs, split by whether they match a name or a path. #[derive(Debug, Clone)] pub(crate) struct PathFilter { diff --git a/crates/search/tests/search.rs b/crates/search/tests/search.rs index dcbe9cc..8396a5c 100644 --- a/crates/search/tests/search.rs +++ b/crates/search/tests/search.rs @@ -81,10 +81,18 @@ fn regex_and_invalid_input() { assert_eq!(files[0].matches[1].length, 5); q.pattern = "(".into(); - assert!(matches!( - Search::new(&q), - Err(SearchError::InvalidPattern(_)) - )); + assert_eq!( + Search::new(&q).unwrap_err().to_string(), + "invalid pattern: unclosed group" + ); + 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(); assert_eq!(Search::new(&q).unwrap_err(), SearchError::EmptyPattern); let mut q = Query::literal("x"); diff --git a/docs/alpha-checklist.md b/docs/alpha-checklist.md index 09759ad..a600854 100644 --- a/docs/alpha-checklist.md +++ b/docs/alpha-checklist.md @@ -1,6 +1,6 @@ # Alpha acceptance checklist -> **Status:** C7 A2, written against main `da58c83` (M0–M4) · **Last updated:** 2026-10-31 +> **Status:** C7 A2, written against main `da58c83` (M0–M4) · **Last updated:** 2026-11-02 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.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.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.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.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.25 | File › Open Folder… `DEMO/shop`. | The demo project is back, with the Git state from 5.22. | [ ] | [ ] | @@ -187,4 +187,5 @@ When everything is ticked on both platforms, say so in the chat with the build c | 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-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 | diff --git a/docs/architecture.md b/docs/architecture.md index b877126..9c64c7a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,6 +1,6 @@ # 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-10-28 +> **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 ## Overview @@ -170,7 +170,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat - `/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-` (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`. -- Commands: `settings.list` → `[{key, type: enum|int, default, enumValues?, min?, max?, labelKey, descriptionKey, section}]` (catalog keys `settings..label` / `.description`; `section` is an id shown with `settings.section.`), `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|bool|string, default, enumValues?, min?, max?, path?, labelKey, descriptionKey, section}]` (`path: true` marks a file path setting, `Kind::Path`) (catalog keys `settings..label` / `.description`; `section` is an id shown with `settings.section.`), `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`…). ### 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..label`, `.description`, `settings.section.`); enum values use `settings..value.`. 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. - **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 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). + - **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: : ` 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). - **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. - **Errors** show under the control (`role="alert"`, `aria-invalid`) and keep the typed text until the value changes. @@ -345,6 +345,7 @@ 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. - 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_detached(program, args) -> io::Result` (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` (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). - 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. @@ -771,6 +772,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat | 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 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`) | diff --git a/docs/install.md b/docs/install.md index 8c4f0c6..69b1ccd 100644 --- a/docs/install.md +++ b/docs/install.md @@ -1,6 +1,6 @@ # Installing Lutra -> **Status:** draft, alpha installers · **Last updated:** 2026-11-01 +> **Status:** draft, alpha installers · **Last updated:** 2026-11-02 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 -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**. +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. ## macOS @@ -116,4 +116,5 @@ 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 | 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 | diff --git a/docs/localization-parity.md b/docs/localization-parity.md index f3982bd..7113975 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization checklist -> **Status:** English catalog covers 100% of UI strings (M1.11); German not started · **Last updated:** 2026-10-16 +> **Status:** English catalog covers 100% of UI strings (M1.11); German not started · **Last updated:** 2026-11-02 | Language | Code | Status | Translated | |---|---|---|---:| @@ -18,6 +18,7 @@ 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) - [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) +- [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) - [ ] German catalog (G14) - [ ] Native menus and dialogs of the desktop shell (folder picker title, app menu) (G14) @@ -26,6 +27,7 @@ All interface strings go through the message catalog: `t(key, params?)` from `ui | 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.12: notification keys, key count 46 | | 2026-10-15 | minor | M1.11: English catalog, lint rule, checklist; engine-message gap | diff --git a/ui/src/components/editor/blame.ts b/ui/src/components/editor/blame.ts index 6d3c52d..b1d7e31 100644 --- a/ui/src/components/editor/blame.ts +++ b/ui/src/components/editor/blame.ts @@ -27,7 +27,7 @@ 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 { runWaiting, type JsonValue } from "../../ipc"; -import { t } from "../../i18n"; +import { formatDate, formatDateTime, t } from "../../i18n"; import type { AssistBuffer } from "./assist"; /** Delay between the last edit and the query. */ @@ -154,18 +154,13 @@ export function ageLevel(iso: string, now: number): number { } /** - * A short local date, `YYYY-MM-DD`. + * A short local date, `YYYY-MM-DD` ({@link formatDate}). * * @param iso - ISO 8601 date. * @returns the date, or the input when it cannot be read. */ export function shortDate(iso: string): string { - 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())}`; + return formatDate(iso); } /** The text and look of one annotated line. */ @@ -343,9 +338,7 @@ function hoverCard(line: BlameLine): { dom: HTMLElement; message: HTMLElement } head.textContent = t("editor.blame.notCommitted"); message.textContent = t("editor.blame.notCommittedHint"); } else { - 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 }); + head.textContent = t("editor.blame.byLine", { hash: line.hash.slice(0, 8), author: line.author, date: formatDateTime(line.date) }); message.textContent = messages.get(line.hash) ?? line.summary; const hint = document.createElement("div"); hint.className = "lt-blame-tooltip__hint"; diff --git a/ui/src/components/recovery/RecoveryDialog.vue b/ui/src/components/recovery/RecoveryDialog.vue index 44fe9a7..7ad300f 100644 --- a/ui/src/components/recovery/RecoveryDialog.vue +++ b/ui/src/components/recovery/RecoveryDialog.vue @@ -8,7 +8,7 @@ * failures, they are listed until the dialog is closed. */ import { nextTick, onMounted, onUnmounted, ref, watch } from "vue"; -import { t } from "../../i18n"; +import { formatDateTime, t } from "../../i18n"; import { useRecoveryStore } from "./recovery"; const recovery = useRecoveryStore(); @@ -55,7 +55,7 @@ watch( * @param savedAt - ms since the Unix epoch. */ function formatTime(savedAt: number): string { - return new Date(savedAt).toLocaleString(); + return formatDateTime(savedAt); } /** diff --git a/ui/src/components/vcs/log/LogToolWindow.vue b/ui/src/components/vcs/log/LogToolWindow.vue index 265fbe2..f87ccc0 100644 --- a/ui/src/components/vcs/log/LogToolWindow.vue +++ b/ui/src/components/vcs/log/LogToolWindow.vue @@ -17,7 +17,7 @@ */ import { RefreshCw, X } from "@lucide/vue"; import { computed, nextTick, onBeforeUnmount, ref } from "vue"; -import { t } from "../../../i18n"; +import { formatDateTime, t } from "../../../i18n"; import { useProjectStore } from "../../../stores/project"; import { SHORT_HASH } from "../changes/changes"; import { refBadges, useLogStore, type CommitFile, type CommitFileStatus } from "./log"; @@ -138,16 +138,12 @@ function rowAt(index: number): GraphRow | null { } /** - * A date for the list: the local date and time, short. + * A date for the list: the local date and time, `YYYY-MM-DD HH:mm`. * * @param iso - ISO 8601 date. */ function shortDate(iso: string): string { - 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" }); + return formatDateTime(iso); } /** Applies the typed filters now. */ diff --git a/ui/src/components/vcs/stash/StashDialog.vue b/ui/src/components/vcs/stash/StashDialog.vue index 78aa910..9fd0d28 100644 --- a/ui/src/components/vcs/stash/StashDialog.vue +++ b/ui/src/components/vcs/stash/StashDialog.vue @@ -22,7 +22,7 @@ import { Archive } from "@lucide/vue"; import { nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue"; import { useModalsStore } from "../../../commands/modals"; import { useCommandsStore } from "../../../commands/store"; -import { t } from "../../../i18n"; +import { formatDateTime, t } from "../../../i18n"; import { useStashStore, type StashEntry } from "./stash"; const stash = useStashStore(); @@ -57,16 +57,12 @@ function refName(entry: StashEntry): string { } /** - * A date for the list: the local date and time, short. + * A date for the list: the local date and time, `YYYY-MM-DD HH:mm`. * * @param iso - ISO 8601 date. */ function shortDate(iso: string): string { - 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" }); + return formatDateTime(iso); } /** diff --git a/ui/src/i18n/index.ts b/ui/src/i18n/index.ts index 709e257..b265942 100644 --- a/ui/src/i18n/index.ts +++ b/ui/src/i18n/index.ts @@ -55,3 +55,55 @@ export function t(key: string, params?: MessageParams): string { 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())}`; +} diff --git a/ui/src/stores/find.ts b/ui/src/stores/find.ts index d35c296..633aedf 100644 --- a/ui/src/stores/find.ts +++ b/ui/src/stores/find.ts @@ -12,7 +12,8 @@ * - **One search at a time:** a new search cancels the running one * (`search.cancel`); the engine does not do that by itself. * - **Errors:** a refused search (`invalid_params` for a bad regex or glob) - * shows its message in the window, not as a toast. + * shows its reason (`userMessage`, without the engine's command prefix) in + * the window, not as a toast. * - **Opening:** `open` shows the panel, takes the query from the params * (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. @@ -23,7 +24,7 @@ import type { EditorState } from "@codemirror/state"; import { defineStore } from "pinia"; import { computed, ref, shallowRef } from "vue"; import { t } from "../i18n"; -import { onEngineEvent, run, type EngineEventPayload, type JsonValue } from "../ipc"; +import { onEngineEvent, run, userMessage, type EngineEventPayload, type JsonValue } from "../ipc"; import { useEditorStore } from "./editor"; /** One match as the window shows it. */ @@ -351,7 +352,7 @@ export const useFindStore = defineStore("find", () => { early = []; if (!result.ok) { running.value = false; - error.value = result.error.message; + error.value = userMessage(result.error); return; } if (id === null) { diff --git a/ui/tests/find/FindToolWindow.test.ts b/ui/tests/find/FindToolWindow.test.ts index 3c17fc3..b8157dd 100644 --- a/ui/tests/find/FindToolWindow.test.ts +++ b/ui/tests/find/FindToolWindow.test.ts @@ -397,9 +397,9 @@ describe("Find tool window", () => { it("shows a refused regex as an alert", async () => { const { wrapper } = await mountFind(); - findError = { code: "invalid_params", message: "bad regex" }; + findError = { code: "invalid_params", message: "invalid params for search.find: invalid pattern: unclosed group" }; await searchFor(wrapper, "("); - expect(wrapper.get("[data-test=find-error]").text()).toBe("bad regex"); + expect(wrapper.get("[data-test=find-error]").text()).toBe("invalid pattern: unclosed group"); expect(wrapper.get("[data-test=find-query]").attributes("aria-invalid")).toBe("true"); expect(wrapper.get("[data-test=find-status]").text()).toBe(""); }); diff --git a/ui/tests/i18n/catalog.test.ts b/ui/tests/i18n/catalog.test.ts index 617e6a2..c5134da 100644 --- a/ui/tests/i18n/catalog.test.ts +++ b/ui/tests/i18n/catalog.test.ts @@ -1,13 +1,13 @@ /** * Tests of the message catalog: the `t` helper (lookup, interpolation, - * missing keys) and a scan of the frontend source that every literal key + * missing keys), the one date format, and a scan of the frontend source that every literal key * passed to `t` exists in `en.json`. */ import { readdirSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; import en from "../../src/i18n/en.json"; -import { hasMessage, t } from "../../src/i18n"; +import { formatDate, formatDateTime, hasMessage, t } from "../../src/i18n"; /** Root of the frontend source tree. */ const SRC = join(import.meta.dirname, "..", "..", "src"); @@ -205,3 +205,15 @@ describe("en.json", () => { 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(""); + }); +}); diff --git a/ui/tests/menu/AppMenu.test.ts b/ui/tests/menu/AppMenu.test.ts index 9fc76fa..e898e19 100644 --- a/ui/tests/menu/AppMenu.test.ts +++ b/ui/tests/menu/AppMenu.test.ts @@ -29,7 +29,7 @@ import SettingsDialog from "../../src/components/settings/SettingsDialog.vue"; const ENGINE_COMMANDS = [ { 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: "buffer.close", label: "Close Buffer", menuPath: "File/Close Tab", defaultShortcut: "Mod+W", params: "", enabled: false, ui: false }, + { id: "buffer.close", label: "Close Tab", 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: "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 }, diff --git a/ui/tests/recovery/RecoveryDialog.test.ts b/ui/tests/recovery/RecoveryDialog.test.ts index 746c433..184fa6b 100644 --- a/ui/tests/recovery/RecoveryDialog.test.ts +++ b/ui/tests/recovery/RecoveryDialog.test.ts @@ -112,9 +112,7 @@ describe("RecoveryDialog", () => { "src/b.php", "c.php", ]); - expect(rows[0]?.text()).toContain( - `Saved ${new Date(ENTRIES[0]?.savedAt ?? 0).toLocaleString()}`, - ); + expect(rows[0]?.text()).toMatch(/Saved \d{4}-\d{2}-\d{2} \d{2}:\d{2}/); expect(rows[0]?.find("[data-test=recovery-changed]").exists()).toBe(false); expect(rows[1]?.get("[data-test=recovery-changed]").text()).toBe( "The file changed on disk since then",