Lutra/ui/tests/problems/ProblemsToolWindow.test.ts
danny 13c76d3046 M3.3: engine wiring for Phpactor and diagnostics
- One Phpactor per open project on its own session thread, started when
  the toolchain is ready; ordered document sync from buffer.edit and the
  pump; lspStatus, diagnosticsChanged, diagnostics.list, lsp.status,
  lsp.restart; app.quit stops the server synchronously.
- Phpactor 2026.06.25.0 on Windows: keep-alive $/lutra/tick (its event
  loop only runs on stdin input), in-process diagnostics and a polling
  watcher through initializationOptions (amphp subprocesses fail), 500 ms
  shutdown timeout.
- Editor lint extension (underlines, gutter dots, hover; tokens only) and
  a Problems tab in the bottom panel; problems.open Mod+Alt+P.
- Tests: engine tests against the fake server (incl. sync proptest), an
  ignored real-Phpactor test, a TCP test, Vitest for lint and Problems.
- Docs: architecture, gaps G6, parity (Inspections 4% est.), ui-parity,
  roadmap, ROADMAP.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 18:58:32 +02:00

300 lines
13 KiB
TypeScript

/**
* Tests of the Problems tool window (M3.3): the store (reading untrusted
* items, ordering, `diagnostics.list` on start and project open,
* `diagnosticsChanged` replacing and removing files, `lspStatus`, project
* close, hand-over to the editor's lint), the window (status line,
* grouping, click and Enter revealing through `editor.reveal`, keyboard
* navigation), and `problems.open` with its shortcut and tabs next to
* Find in the main layout. 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 { diagnosticsOf } from "../../src/components/editor/lint";
import MainLayout from "../../src/components/layout/MainLayout.vue";
import ProblemsToolWindow from "../../src/components/problems/ProblemsToolWindow.vue";
import { toItems, toStatus, useProblemsStore } from "../../src/components/problems/problems";
/** Every `engine_execute` call, in order. */
let calls: { command: string; params: Record<string, unknown> }[];
/** Engine event callbacks of every subscription. */
let listeners: ((event: { payload: unknown }) => void)[];
/** What `diagnostics.list` answers. */
let listed: unknown;
/** What `lsp.status` answers. */
let status: unknown;
/** Pinia of the current test. */
let pinia: Pinia;
/** Mounted components, unmounted after each test. */
let mounted: VueWrapper[];
/**
* Sends an engine event to every subscription.
*
* @param payload - the event.
*/
async function emit(payload: unknown): Promise<void> {
for (const listener of [...listeners]) {
listener({ payload });
}
await flushPromises();
}
/**
* A diagnostic as the engine sends it.
*
* @param line - 0-based line.
* @param severity - its severity.
* @param message - its message.
*/
function diag(line: number, severity: string, message: string): Record<string, unknown> {
return {
range: { start: { line, column: 2 }, end: { line, column: 6 } },
severity,
message,
source: "phpactor",
};
}
/** The params of every call of a command. */
function paramsOf(command: string): Record<string, unknown>[] {
return calls.filter((c) => c.command === command).map((c) => c.params);
}
/** Mounts the window with a started store and an `editor.reveal` spy. */
async function mountProblems(): Promise<{ wrapper: VueWrapper; reveals: unknown[] }> {
const reveals: unknown[] = [];
useCommandsStore(pinia).provide("editor.reveal", { run: (params) => void reveals.push(params) });
useProblemsStore(pinia).start();
const wrapper = mount(ProblemsToolWindow, { attachTo: document.body, global: { plugins: [pinia] } });
mounted.push(wrapper);
await flushPromises();
return { wrapper, reveals };
}
/**
* The text of every row.
*
* @param wrapper - the window.
*/
function rowTexts(wrapper: VueWrapper): string[] {
return wrapper.findAll("[data-test=problems-row]").map((row) => row.text());
}
beforeEach(() => {
pinia = createPinia();
setActivePinia(pinia);
calls = [];
listeners = [];
mounted = [];
listed = { files: [] };
status = { state: "stopped" };
Element.prototype.scrollIntoView = () => undefined;
invoke.mockReset();
listen.mockReset();
listen.mockImplementation((_name: string, callback: (event: { payload: unknown }) => void) => {
listeners.push(callback);
return Promise.resolve(() => {
listeners = listeners.filter((l) => l !== callback);
});
});
invoke.mockImplementation((cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
if (cmd === "engine_list_commands") {
return Promise.resolve([]);
}
if (cmd !== "engine_execute" || !args) {
return Promise.resolve(null);
}
calls.push({ command: args.command, params: args.params });
if (args.command === "diagnostics.list") {
return Promise.resolve(listed);
}
if (args.command === "lsp.status") {
return Promise.resolve(status);
}
return Promise.resolve(null);
});
});
afterEach(() => {
for (const wrapper of mounted) {
wrapper.unmount();
}
useProblemsStore(pinia).stop();
useProblemsStore(pinia).onEvent({ kind: "projectClosed" });
useCommandsStore(pinia).stop();
});
describe("problems store", () => {
it("drops malformed items and orders errors first, then by position", () => {
const items = toItems([
diag(9, "warning", "w"),
diag(5, "error", "e2"),
diag(1, "error", "e1"),
{ ...diag(0, "fatal", "bad severity") },
{ range: { start: { line: -1, column: 0 }, end: { line: 0, column: 0 } }, severity: "error", message: "neg" },
{ range: null, severity: "error", message: "no range" },
{ ...diag(0, "info", "no message"), message: 4 },
"junk",
diag(3, "hint", "h"),
]);
expect(items.map((i) => i.message)).toEqual(["e1", "e2", "w", "h"]);
expect(toItems("nope")).toEqual([]);
expect(toStatus({ state: "failed", message: "crashed" })).toEqual({ state: "failed", message: "crashed" });
expect(toStatus({ state: "exploded" })).toBeNull();
});
it("loads on start, follows diagnosticsChanged and hands files to the editor", async () => {
listed = { files: [{ path: "src/b.php", items: [diag(0, "error", "B")] }, { path: 3, items: [] }] };
status = { state: "ready" };
const problems = useProblemsStore();
problems.start();
await flushPromises();
expect(paramsOf("diagnostics.list")).toEqual([{}]);
expect(problems.lsp).toEqual({ state: "ready", message: null });
expect(problems.files.map((f) => f.path)).toEqual(["src/b.php"]);
expect(diagnosticsOf("src/b.php")).toHaveLength(1);
await emit({ kind: "diagnosticsChanged", path: "a.php", items: [diag(2, "warning", "A")] });
expect(problems.files.map((f) => f.path)).toEqual(["a.php", "src/b.php"]);
expect(problems.counts).toEqual({ error: 1, warning: 1, info: 0, hint: 0 });
expect(diagnosticsOf("a.php").map((i) => i.message)).toEqual(["A"]);
await emit({ kind: "diagnosticsChanged", path: "src/b.php", items: [] });
expect(problems.files.map((f) => f.path)).toEqual(["a.php"]);
expect(diagnosticsOf("src/b.php")).toEqual([]);
await emit({ kind: "diagnosticsChanged", path: 7, items: [diag(0, "error", "x")] });
expect(problems.files).toHaveLength(1);
await emit({ kind: "lspStatus", state: "restarting", message: "exit 7" });
expect(problems.lsp).toEqual({ state: "restarting", message: "exit 7" });
await emit({ kind: "projectClosed" });
expect(problems.files).toEqual([]);
expect(problems.lsp).toBeNull();
expect(diagnosticsOf("a.php")).toEqual([]);
listed = { files: [{ path: "c.php", items: [diag(0, "info", "C")] }] };
await emit({ kind: "projectOpened", root: "/p", name: "p" });
expect(problems.files.map((f) => f.path)).toEqual(["c.php"]);
});
});
describe("ProblemsToolWindow", () => {
it("shows the server state while there is nothing to list", async () => {
const { wrapper } = await mountProblems();
const line = (): string => wrapper.get("[data-test=problems-status]").text();
expect(line()).toContain("No PHP language server is running");
await emit({ kind: "lspStatus", state: "starting" });
expect(line()).toBe("Phpactor is starting…");
await emit({ kind: "lspStatus", state: "ready" });
expect(line()).toBe("No problems found in open files");
await emit({ kind: "lspStatus", state: "failed", message: "php.exe vanished" });
expect(line()).toBe("Phpactor stopped: php.exe vanished");
});
it("groups by file with counts, severity icons, origin and position", async () => {
status = { state: "ready" };
const { wrapper } = await mountProblems();
await emit({
kind: "diagnosticsChanged",
path: "src/Service.php",
items: [diag(4, "warning", "Unused variable"), { ...diag(1, "error", "Undefined method"), code: "E12" }],
});
await emit({ kind: "diagnosticsChanged", path: "a.php", items: [diag(0, "hint", "Could be final")] });
expect(wrapper.get("[data-test=problems-status]").text()).toBe("1 errors, 1 warnings, 1 other");
const files = wrapper.findAll("[data-test=problems-file]").map((f) => f.text());
expect(files[0]).toContain("a.php");
expect(files[1]).toContain("Service.php");
expect(files[1]).toContain("src");
expect(files[1]).toContain("2");
expect(rowTexts(wrapper)).toEqual([
"Could be finalphpactorline 1, column 3",
"Undefined methodphpactor E12line 2, column 3",
"Unused variablephpactorline 5, column 3",
]);
const rows = wrapper.findAll("[data-test=problems-row]");
expect(rows[1]?.attributes("data-severity")).toBe("error");
expect(rows[1]?.find("[role=img]").attributes("aria-label")).toBe("Error");
});
it("reveals a problem on click and with the keyboard", async () => {
const { wrapper, reveals } = await mountProblems();
await emit({ kind: "diagnosticsChanged", path: "a.php", items: [diag(0, "error", "one"), diag(3, "error", "two")] });
await emit({ kind: "diagnosticsChanged", path: "b.php", items: [diag(7, "warning", "three")] });
await wrapper.findAll("[data-test=problems-row]")[1]?.trigger("click");
await flushPromises();
expect(reveals).toEqual([{ path: "a.php", line: 3, column: 2 }]);
const list = wrapper.get("[data-test=problems-list]");
await list.trigger("keydown", { key: "ArrowDown" });
expect(wrapper.find("[aria-selected=true]").text()).toContain("three");
await list.trigger("keydown", { key: "Home" });
expect(wrapper.find("[aria-selected=true]").text()).toContain("one");
await list.trigger("keydown", { key: "End" });
await list.trigger("keydown", { key: "Enter" });
await flushPromises();
expect(reveals.at(-1)).toEqual({ path: "b.php", line: 7, column: 2 });
expect(list.attributes("aria-activedescendant")).toBe("problem-row-2");
});
});
describe("problems.open", () => {
/** Mounts the main layout with the commands store started. */
async function mountLayout(): Promise<VueWrapper> {
const wrapper = mount(MainLayout, {
attachTo: document.body,
global: { plugins: [pinia], stubs: { ProjectToolWindow: true, StatusBar: true } },
});
mounted.push(wrapper);
await useCommandsStore(pinia).start();
await flushPromises();
return wrapper;
}
it("is registered with its own shortcut and menu path", async () => {
await mountLayout();
const registered = paramsOf("ui.registerCommands")[0]?.commands as { id: string; defaultShortcut?: string; menuPath?: string }[];
const command = registered.find((c) => c.id === "problems.open");
expect(command?.defaultShortcut).toBe("Mod+Alt+P");
expect(command?.menuPath).toBe("View/Problems");
});
it("opens from the shortcut, shares the panel with Find as tabs and closes", async () => {
const wrapper = await mountLayout();
expect(wrapper.find("[data-test=bottom-panel]").exists()).toBe(false);
window.dispatchEvent(new KeyboardEvent("keydown", { key: "p", code: "KeyP", ctrlKey: true, altKey: true, bubbles: true }));
await flushPromises();
expect(wrapper.find("[data-test=bottom-panel]").exists()).toBe(true);
expect(wrapper.get("[data-test=problems]").isVisible()).toBe(true);
expect(document.activeElement).toBe(wrapper.get("[data-test=problems-list]").element);
expect(wrapper.find("[data-test=bottom-tab-problems]").exists()).toBe(false);
await emit({ kind: "uiCommand", id: "find.open", params: {} });
expect(wrapper.get("[data-test=bottom-tab-problems]").attributes("aria-selected")).toBe("false");
expect(wrapper.get("[data-test=bottom-tab-find]").attributes("aria-selected")).toBe("true");
await wrapper.get("[data-test=bottom-tab-problems]").trigger("click");
expect(wrapper.get("[data-test=problems]").isVisible()).toBe(true);
expect(wrapper.get("[data-test=find]").isVisible()).toBe(false);
await wrapper.get("[data-test=bottom-panel-close]").trigger("click");
expect(wrapper.find("[data-test=bottom-tab-problems]").exists()).toBe(false);
expect(wrapper.get("[data-test=find]").isVisible()).toBe(true);
await wrapper.get("[data-test=bottom-panel-close]").trigger("click");
expect(wrapper.find("[data-test=bottom-panel]").exists()).toBe(false);
});
it("opens from an agent's uiCommand", async () => {
const wrapper = await mountLayout();
await emit({ kind: "uiCommand", id: "problems.open", params: {} });
expect(wrapper.find("[data-test=problems]").exists()).toBe(true);
});
});