H4: string and path settings controls, live completion and tooltip settings

- Settings dialog: every string setting gets a text field with in-place
  hints (quotes or spaces around a path, control characters, length);
  keys ending in path/executable also get "Browse…" through the dialog
  plugin's native picker (new desktop IPC pick_file). git.executable
  from M4.1 gets the control without UI changes.
- settings.open {section?, query?} for agents and live checks.
- New keys editor.completion.autoPopup, editor.completion.delayMs and
  editor.hover.delayMs; the assist module reads them live through
  CodeMirror compartments.
- Tests: engine settings test, control/engine key lists, Vitest for the
  controls and the live wiring. Docs: architecture, ui-parity, parity
  Settings row, gaps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-25 13:10:19 +01:00
parent b0f8550aeb
commit 197d5b7d27
19 changed files with 1149 additions and 41 deletions

View file

@ -0,0 +1,195 @@
/**
* Tests of the live assist settings (H4, `assist/settings.ts`): reading
* and clamping the values, following the settings store, reconfiguring
* open editors when a value changes, and the effect on completion (auto
* popup on/off, popup delay) through `assistExtensions`.
*/
import { EditorState, type Extension } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { createPinia, setActivePinia } from "pinia";
import { afterEach, describe, expect, it, vi } from "vitest";
import { nextTick } from "vue";
import { assistExtensions } from "../../../src/components/editor/assist";
import {
ASSIST_DEFAULTS,
liveAssistSettings,
storeAssistSettings,
toAssistSettings,
type AssistSettings,
type AssistSettingsSource,
} from "../../../src/components/editor/assist/settings";
import { useSettingsStore } from "../../../src/stores/settings";
import { fakeBuffer, fakeTransport } from "./fakes";
/** Views created by a test, destroyed after it. */
let views: EditorView[] = [];
afterEach(() => {
vi.useRealTimers();
for (const view of views) {
view.destroy();
}
views = [];
});
/** A mounted view with `doc` and `extensions`. */
function mount(doc: string, extensions: Extension): EditorView {
const parent = document.createElement("div");
document.body.append(parent);
const view = new EditorView({ state: EditorState.create({ doc, extensions }), parent });
views.push(view);
return view;
}
/** A settings source the test changes by hand. */
function fakeSource(initial: Partial<AssistSettings> = {}): AssistSettingsSource & {
change(next: Partial<AssistSettings>): void;
listeners: Set<() => void>;
} {
let value: AssistSettings = { ...ASSIST_DEFAULTS, ...initial };
const listeners = new Set<() => void>();
return {
listeners,
current: () => ({ ...value }),
subscribe(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
},
change(next) {
value = { ...value, ...next };
for (const listener of listeners) {
listener();
}
},
};
}
/**
* Lets `ms` milliseconds pass on the fake clock, running the timers and
* promises due meanwhile.
*/
async function wait(ms: number): Promise<void> {
await vi.advanceTimersByTimeAsync(ms);
}
/** Types `text` at the end of the view's document as the user would. */
function type(view: EditorView, text: string): void {
const end = view.state.doc.length;
view.dispatch({
changes: { from: end, insert: text },
selection: { anchor: end + text.length },
userEvent: "input.type",
});
}
/** The completion queries a transport received. */
function completions(transport: ReturnType<typeof fakeTransport>): number {
return transport.calls.filter((c) => c.command === "lsp.completion").length;
}
describe("assist settings values", () => {
it("uses the defaults for missing or malformed values and clamps numbers", () => {
expect(toAssistSettings({})).toEqual({ autoPopup: true, completionDelay: 0, hoverDelay: 350 });
expect(
toAssistSettings({
"editor.completion.autoPopup": "no",
"editor.completion.delayMs": Number.NaN,
"editor.hover.delayMs": null,
}),
).toEqual(ASSIST_DEFAULTS);
expect(
toAssistSettings({
"editor.completion.autoPopup": false,
"editor.completion.delayMs": 9999,
"editor.hover.delayMs": 10.4,
}),
).toEqual({ autoPopup: false, completionDelay: 2000, hoverDelay: 100 });
});
it("reads and follows the settings store", async () => {
setActivePinia(createPinia());
const store = useSettingsStore();
expect(storeAssistSettings.current()).toEqual(ASSIST_DEFAULTS);
let changes = 0;
const stop = storeAssistSettings.subscribe(() => {
changes += 1;
});
store.values["editor.hover.delayMs"] = 800;
await nextTick();
expect(changes).toBe(1);
expect(storeAssistSettings.current().hoverDelay).toBe(800);
store.values["editor.fontSize"] = 20;
await nextTick();
expect(changes).toBe(1);
stop();
store.values["editor.completion.autoPopup"] = false;
await nextTick();
expect(changes).toBe(1);
});
});
describe("live reconfiguration", () => {
it("rebuilds the dependent extensions with new values and stops on destroy", async () => {
const source = fakeSource({ hoverDelay: 500 });
const built: number[] = [];
const view = mount("<?php\n", liveAssistSettings(source, [(s) => (built.push(s.hoverDelay), [])]));
await Promise.resolve();
expect(built).toEqual([500]);
source.change({ hoverDelay: 1200 });
expect(built).toEqual([500, 1200]);
source.change({ hoverDelay: 1200 });
expect(built).toEqual([500, 1200]);
view.destroy();
views = [];
expect(source.listeners.size).toBe(0);
});
it("catches up when a view gets a state built with older values", async () => {
const source = fakeSource();
const built: boolean[] = [];
const state = EditorState.create({
doc: "<?php\n",
extensions: liveAssistSettings(source, [(s) => (built.push(s.autoPopup), [])]),
});
source.change({ autoPopup: false });
const parent = document.createElement("div");
document.body.append(parent);
views.push(new EditorView({ state, parent }));
await Promise.resolve();
expect(built).toEqual([true, false]);
});
});
describe("completion follows the settings", () => {
it("opens while typing only with auto popup on", async () => {
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
const source = fakeSource({ autoPopup: false });
const transport = fakeTransport({ isIncomplete: false, items: [{ label: "Foo", kind: "class" }] });
const view = mount("<?php\n", assistExtensions("a.php", fakeBuffer(1), transport, source));
type(view, "Fo");
await wait(30);
expect(completions(transport)).toBe(0);
source.change({ autoPopup: true });
type(view, "o");
await wait(30);
expect(completions(transport)).toBe(1);
});
it("waits for the popup delay after typing", async () => {
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
const source = fakeSource({ completionDelay: 200 });
const transport = fakeTransport({ isIncomplete: true, items: [{ label: "Foo", kind: "class" }] });
const view = mount("<?php\n", assistExtensions("a.php", fakeBuffer(1), transport, source));
type(view, "F");
await wait(190);
expect(completions(transport)).toBe(0);
await wait(20);
expect(completions(transport)).toBe(1);
source.change({ completionDelay: 0 });
type(view, "o");
await wait(30);
expect(completions(transport)).toBe(2);
});
});

View file

@ -77,8 +77,14 @@ const RUNTIME_KEYS = new Set([
"settings.editor.autosave.onBlur.label",
"settings.editor.autosave.onTabSwitch.description",
"settings.editor.autosave.onTabSwitch.label",
"settings.editor.completion.autoPopup.description",
"settings.editor.completion.autoPopup.label",
"settings.editor.completion.delayMs.description",
"settings.editor.completion.delayMs.label",
"settings.editor.fontSize.description",
"settings.editor.fontSize.label",
"settings.editor.hover.delayMs.description",
"settings.editor.hover.delayMs.label",
"settings.php.executable.description",
"settings.php.executable.label",
"settings.phpactor.autoDownload.description",

View file

@ -0,0 +1,333 @@
/**
* Tests of the string and path controls of the settings dialog (H4,
* `components/settings/stringSetting.ts`): which settings are paths, the
* checks before `settings.set` and their messages, the text field and its
* placeholder, "Browse…" through the shell's `pick_file`, engine errors,
* live updates, `settings.open {section, query}`, and a string setting the dialog has never seen
* (`git.executable`) getting the control without changes. The engine is a
* fake behind the mocked Tauri `invoke` and `listen`.
*/
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
import { createPinia, setActivePinia, type Pinia } from "pinia";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const invoke = vi.hoisted(() => vi.fn());
const listen = vi.hoisted(() => vi.fn());
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
vi.mock("@tauri-apps/api/event", () => ({ listen }));
import { useCommandsStore } from "../../src/commands/store";
import SettingsDialog from "../../src/components/settings/SettingsDialog.vue";
import {
checkString,
isPathSetting,
MAX_STRING_BYTES,
placeholderOf,
} from "../../src/components/settings/stringSetting";
import { toSettingDefs, useSettingsStore, type SettingDef } from "../../src/stores/settings";
/**
* A string setting as `settings.list` reports it.
*
* @param key - the key.
* @param section - the section id.
*/
function stringEntry(key: string, section: string): Record<string, unknown> {
return {
key,
type: "string",
default: "",
labelKey: `settings.${key}.label`,
descriptionKey: `settings.${key}.description`,
section,
};
}
/** The fake engine's base `settings.list`. */
const BASE = [
stringEntry("php.executable", "php"),
stringEntry("phpactor.path", "php"),
{ ...stringEntry("editor.name", "php"), default: "Lutra" },
];
/** What `settings.list` returns in the current test. */
let list: Record<string, unknown>[];
/** The fake engine's values. */
let values: Record<string, unknown>;
/** Every `engine_execute` call, in order. */
let calls: { command: string; params: Record<string, unknown> }[];
/** What `pick_file` answers: a path, null (cancelled) or an error. */
let picked: string | null | Error;
/** The titles `pick_file` was called with. */
let pickTitles: string[];
/** The engine event callbacks. */
let listeners: ((payload: unknown) => void)[];
/** Pinia of the current test. */
let pinia: Pinia;
/** Mounted components. */
let mounted: VueWrapper[];
/**
* The setting definitions of the base list.
*
* @param key - the key.
*/
function defOf(key: string): SettingDef {
const def = toSettingDefs([...BASE, stringEntry("git.executable", "git"), { ...BASE[0], key: "x.pharPath" }])?.find(
(d) => d.key === key,
);
if (!def) {
throw new Error(key);
}
return def;
}
/** Mounts and opens the dialog on the first section. */
async function openDialog(): Promise<VueWrapper> {
const wrapper = mount(SettingsDialog, { attachTo: document.body, global: { plugins: [pinia] } });
mounted.push(wrapper);
await useCommandsStore(pinia).start();
await useSettingsStore(pinia).start();
await (wrapper.vm as unknown as { show(): Promise<void> }).show();
await flushPromises();
return wrapper;
}
/**
* A setting's row.
*
* @param wrapper - the dialog.
* @param key - the setting.
*/
function row(wrapper: VueWrapper, key: string) {
return wrapper.find(`[data-test=settings-row][data-key="${key}"]`);
}
/**
* Types into a setting's text field and commits it (as leaving the field does).
*
* @param wrapper - the dialog.
* @param key - the setting.
* @param text - the text.
*/
async function commit(wrapper: VueWrapper, key: string, text: string): Promise<void> {
const input = row(wrapper, key).find("input");
(input.element as HTMLInputElement).value = text;
await input.trigger("change");
await flushPromises();
}
/** The `settings.set` calls. */
function sets(): Record<string, unknown>[] {
return calls.filter((c) => c.command === "settings.set").map((c) => c.params);
}
beforeEach(() => {
pinia = createPinia();
setActivePinia(pinia);
list = [...BASE];
values = { "php.executable": "", "phpactor.path": "/opt/phpactor.phar", "editor.name": "Lutra" };
calls = [];
picked = null;
pickTitles = [];
listeners = [];
mounted = [];
listen.mockReset();
listen.mockImplementation((_name: string, callback: (event: { payload: unknown }) => void) => {
listeners.push((payload) => {
callback({ payload });
});
return Promise.resolve(() => undefined);
});
invoke.mockReset();
invoke.mockImplementation((cmd: string, args?: Record<string, unknown>) => {
if (cmd === "pick_file") {
pickTitles.push(String(args?.title));
return picked instanceof Error ? Promise.reject(picked) : Promise.resolve(picked);
}
if (cmd !== "engine_execute" || !args) {
return Promise.resolve(cmd === "engine_list_commands" ? [] : null);
}
const command = args.command as string;
const params = args.params as Record<string, unknown>;
calls.push({ command, params });
switch (command) {
case "settings.list":
return Promise.resolve(list);
case "settings.get": {
const keys = Array.isArray(params.keys) ? (params.keys as string[]) : Object.keys(values);
return Promise.resolve({ values: Object.fromEntries(keys.map((k) => [k, values[k]])) });
}
case "settings.set":
if (params.value === "/does/not/exist") {
return Promise.reject(Object.assign(new Error("x"), { code: "invalid_params", message: "no such file" }));
}
values[params.key as string] = params.value;
return Promise.resolve({ value: params.value });
case "settings.reset":
values[params.key as string] = "";
return Promise.resolve({ value: "" });
default:
return Promise.resolve(null);
}
});
});
afterEach(() => {
useCommandsStore(pinia).stop();
useSettingsStore(pinia).stop();
for (const wrapper of mounted) {
wrapper.unmount();
}
});
describe("string setting rules", () => {
it("treats keys ending in path or executable 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"), type: "int" })).toBe(false);
});
it("shows 'Detected automatically' only for paths with an empty default", () => {
expect(placeholderOf(defOf("php.executable"))).toBe("Detected automatically");
expect(placeholderOf({ ...defOf("php.executable"), default: "/usr/bin/php" })).toBe("");
expect(placeholderOf(defOf("editor.name"))).toBe("");
});
it("refuses long texts, control characters, quoted and padded paths", () => {
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(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`);
});
});
describe("string and path controls", () => {
it("shows a text field with the value, a placeholder and Browse for paths", async () => {
const wrapper = await openDialog();
const php = row(wrapper, "php.executable");
const field = php.find("input");
expect(field.attributes()).toMatchObject({ type: "text", placeholder: "Detected automatically" });
expect((field.element as HTMLInputElement).value).toBe("");
expect(php.find("label").text()).toBe("PHP executable");
expect(php.find("[data-test=settings-browse]").text()).toBe("Browse…");
expect(php.find("[data-test=settings-browse]").attributes("aria-label")).toBe("Choose a file for PHP executable");
expect((row(wrapper, "phpactor.path").find("input").element as HTMLInputElement).value).toBe("/opt/phpactor.phar");
expect(row(wrapper, "phpactor.path").find("[data-test=settings-reset]").attributes("disabled")).toBeUndefined();
const name = row(wrapper, "editor.name");
expect(name.find("input").attributes("placeholder")).toBeUndefined();
expect(name.find("[data-test=settings-browse]").exists()).toBe(false);
});
it("applies a committed text through settings.set", async () => {
const wrapper = await openDialog();
await commit(wrapper, "php.executable", "C:\\php\\php.exe");
expect(sets()).toEqual([{ key: "php.executable", value: "C:\\php\\php.exe" }]);
expect(useSettingsStore(pinia).values["php.executable"]).toBe("C:\\php\\php.exe");
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 () => {
const wrapper = await openDialog();
await commit(wrapper, "php.executable", '"C:\\php\\php.exe"');
expect(sets()).toEqual([]);
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(php.find("[data-test=settings-error]").exists()).toBe(false);
});
it("shows the engine's error for a value it refuses", async () => {
const wrapper = await openDialog();
await commit(wrapper, "phpactor.path", "/does/not/exist");
const path = row(wrapper, "phpactor.path");
expect(path.find("[data-test=settings-error]").text()).toBe("no such file");
expect((path.find("input").element as HTMLInputElement).value).toBe("/does/not/exist");
});
it("browses for a file and applies it; cancelling changes nothing", async () => {
const wrapper = await openDialog();
picked = null;
await row(wrapper, "php.executable").find("[data-test=settings-browse]").trigger("click");
await flushPromises();
expect(pickTitles).toEqual(["Choose PHP executable"]);
expect(sets()).toEqual([]);
picked = "C:\\tools\\php\\php.exe";
await row(wrapper, "php.executable").find("[data-test=settings-browse]").trigger("click");
await flushPromises();
expect(sets()).toEqual([{ key: "php.executable", value: "C:\\tools\\php\\php.exe" }]);
expect((row(wrapper, "php.executable").find("input").element as HTMLInputElement).value).toBe(
"C:\\tools\\php\\php.exe",
);
});
it("shows why the file picker could not open", async () => {
const wrapper = await openDialog();
picked = new Error("no shell");
await row(wrapper, "phpactor.path").find("[data-test=settings-browse]").trigger("click");
await flushPromises();
expect(row(wrapper, "phpactor.path").find("[data-test=settings-error]").text()).toBe(
"The file picker could not open: no shell",
);
expect(sets()).toEqual([]);
});
it("follows settingsChanged and resets to the default", async () => {
const wrapper = await openDialog();
values["php.executable"] = "/usr/bin/php8.4";
for (const listener of listeners) {
listener({ kind: "settingsChanged", keys: ["php.executable"] });
}
await flushPromises();
expect((row(wrapper, "php.executable").find("input").element as HTMLInputElement).value).toBe("/usr/bin/php8.4");
await row(wrapper, "php.executable").find("[data-test=settings-reset]").trigger("click");
await flushPromises();
expect((row(wrapper, "php.executable").find("input").element as HTMLInputElement).value).toBe("");
});
it("opens on a section or with a search from settings.open params (agents)", async () => {
list = [...BASE, { ...stringEntry("git.executable", "git") }];
values["git.executable"] = "";
const wrapper = mount(SettingsDialog, { attachTo: document.body, global: { plugins: [pinia] } });
mounted.push(wrapper);
await useCommandsStore(pinia).start();
await useSettingsStore(pinia).start();
for (const listener of listeners) {
listener({ kind: "uiCommand", id: "settings.open", params: { section: "git" } });
}
await flushPromises();
expect(wrapper.findAll("[data-test=settings-row]").map((r) => r.attributes("data-key"))).toEqual(["git.executable"]);
for (const listener of listeners) {
listener({ kind: "uiCommand", id: "settings.open", params: { query: "phar" } });
}
await flushPromises();
expect((wrapper.find("[data-test=settings-search]").element as HTMLInputElement).value).toBe("phar");
expect(wrapper.findAll("[data-test=settings-row]").map((r) => r.attributes("data-key"))).toEqual(["phpactor.path"]);
});
it("gives a string setting it has never seen the control (git.executable)", async () => {
list = [...BASE, stringEntry("git.executable", "git")];
values["git.executable"] = "";
const wrapper = await openDialog();
await wrapper.find("[data-section=git]").trigger("click");
const git = row(wrapper, "git.executable");
expect(git.find("input").attributes()).toMatchObject({ type: "text", placeholder: "Detected automatically" });
expect(git.find("[data-test=settings-browse]").exists()).toBe(true);
await commit(wrapper, "git.executable", "/usr/bin/git");
expect(sets()).toEqual([{ key: "git.executable", value: "/usr/bin/git" }]);
});
});