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>
This commit is contained in:
danny 2026-10-21 18:58:32 +02:00
parent 65c6966588
commit 13c76d3046
34 changed files with 3562 additions and 37 deletions

View file

@ -0,0 +1,341 @@
/**
* The Problems tool window's state (M3.3): the language server's
* diagnostics of the project, grouped by file, and the server's state.
*
* - **Source:** `diagnosticsChanged {path, items}` replaces one file's
* list (empty items remove the file); `diagnostics.list` loads every
* file on start and when a project opens, and `lsp.status` the server's
* state, which then follows `lspStatus`. A project close clears both.
* - **Editor:** every change is handed to the editor's lint extension
* ({@link publishDiagnostics}), which draws the underlines and gutter
* markers.
* - **Rows:** files sorted by path; inside a file errors first, then
* warnings, information and hints, each by position. One flat row list
* drives keyboard navigation; Enter or a click reveals the position
* (`editor.reveal`).
* - **Untrusted input:** event fields come from the engine and, through
* it, from Phpactor; malformed items are dropped and the counts capped
* ({@link MAX_ITEMS_PER_FILE}, {@link MAX_FILES}).
*/
import { defineStore } from "pinia";
import { computed, ref, shallowRef } from "vue";
import { onEngineEvent, run, type EngineEventPayload } from "../../ipc";
import {
clearDiagnostics,
publishDiagnostics,
type DiagnosticItem,
type DiagnosticPosition,
type DiagnosticSeverity,
} from "../editor/lint";
/** Most diagnostics kept per file. */
export const MAX_ITEMS_PER_FILE = 10_000;
/** Most files kept. */
export const MAX_FILES = 10_000;
/** States of the language server, as `lspStatus` names them. */
export const LSP_STATES = ["starting", "ready", "restarting", "failed", "stopped"] as const;
/** State of the language server. */
export type LspState = (typeof LSP_STATES)[number];
/** The language server's state and why it is in it. */
export interface LspStatus {
/** The state. */
state: LspState;
/** Why it restarts or failed. */
message: string | null;
}
/** The diagnostics of one file. */
export interface ProblemFile {
/** Project-relative path with `/`. */
path: string;
/** Its diagnostics in display order. */
items: DiagnosticItem[];
}
/** A diagnostic in the flat display order. */
export interface ProblemRow {
/** Stable key: path and index. */
key: string;
/** Path of the file. */
path: string;
/** The diagnostic. */
item: DiagnosticItem;
}
/** Severities in display order. */
const SEVERITY_ORDER: Record<DiagnosticSeverity, number> = { error: 0, warning: 1, info: 2, hint: 3 };
/**
* Reads a position.
*
* @param raw - an untrusted `{line, column}`.
*/
function toPosition(raw: unknown): DiagnosticPosition | null {
if (typeof raw !== "object" || raw === null) {
return null;
}
const { line, column } = raw as Record<string, unknown>;
const ok = (n: unknown): n is number => typeof n === "number" && Number.isInteger(n) && n >= 0;
return ok(line) && ok(column) ? { line, column } : null;
}
/**
* Reads one diagnostic; null if malformed.
*
* @param raw - an untrusted item of `diagnosticsChanged`.
*/
export function toItem(raw: unknown): DiagnosticItem | null {
if (typeof raw !== "object" || raw === null) {
return null;
}
const i = raw as Record<string, unknown>;
const range = typeof i.range === "object" && i.range !== null ? (i.range as Record<string, unknown>) : null;
const start = toPosition(range?.start);
const end = toPosition(range?.end);
const severity = i.severity;
if (
!start ||
!end ||
typeof i.message !== "string" ||
(severity !== "error" && severity !== "warning" && severity !== "info" && severity !== "hint")
) {
return null;
}
const item: DiagnosticItem = { range: { start, end }, severity, message: i.message };
if (typeof i.source === "string" && i.source !== "") {
item.source = i.source;
}
if (typeof i.code === "string" && i.code !== "") {
item.code = i.code;
}
return item;
}
/**
* Reads and orders a file's diagnostics: errors first, then by position.
*
* @param raw - the untrusted `items` field.
*/
export function toItems(raw: unknown): DiagnosticItem[] {
if (!Array.isArray(raw)) {
return [];
}
const items: DiagnosticItem[] = [];
for (const entry of raw as unknown[]) {
if (items.length >= MAX_ITEMS_PER_FILE) {
break;
}
const item = toItem(entry);
if (item) {
items.push(item);
}
}
return items.sort(
(a, b) =>
SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity] ||
a.range.start.line - b.range.start.line ||
a.range.start.column - b.range.start.column,
);
}
/**
* Reads the payload of `lspStatus` or the result of `lsp.status`.
*
* @param raw - untrusted.
* @returns the status, or null if the state is unknown.
*/
export function toStatus(raw: unknown): LspStatus | null {
if (typeof raw !== "object" || raw === null) {
return null;
}
const { state, message } = raw as Record<string, unknown>;
const known = LSP_STATES.find((s) => s === state);
if (!known) {
return null;
}
return { state: known, message: typeof message === "string" ? message : null };
}
/** The Problems store. */
export const useProblemsStore = defineStore("problems", () => {
/** Whether the tool window is shown in the bottom panel. */
const visible = ref(false);
/** Whether the panel is expanded while Problems is shown. */
const expanded = ref(true);
/** Files with diagnostics, sorted by path. */
const files = shallowRef<ProblemFile[]>([]);
/** The language server's state; null before the first report. */
const lsp = ref<LspStatus | null>(null);
/** Key of the selected row. */
const selectedKey = ref<string | null>(null);
/** Bumped when the window should take the keyboard focus. */
const focusRequest = ref(0);
/** Whether a focus request waits for the window (it may mount later). */
const focusPending = ref(false);
/** Every diagnostic in display order. */
const rows = computed<ProblemRow[]>(() =>
files.value.flatMap((file) =>
file.items.map((item, index) => ({ key: `${file.path}#${String(index)}`, path: file.path, item })),
),
);
/** Index of the selected row, -1 if none. */
const selectedIndex = computed(() => rows.value.findIndex((row) => row.key === selectedKey.value));
/** Counts by severity over all files. */
const counts = computed(() => {
const out: Record<DiagnosticSeverity, number> = { error: 0, warning: 0, info: 0, hint: 0 };
for (const file of files.value) {
for (const item of file.items) {
out[item.severity] += 1;
}
}
return out;
});
/**
* Replaces one file's diagnostics.
*
* @param path - project-relative path.
* @param items - its diagnostics, already read; empty removes the file.
*/
function setFile(path: string, items: DiagnosticItem[]): void {
const rest = files.value.filter((file) => file.path !== path);
if (items.length > 0 && (rest.length < files.value.length || rest.length < MAX_FILES)) {
rest.push({ path, items });
rest.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
}
files.value = rest;
publishDiagnostics(path, items);
}
/** Drops every file's diagnostics. */
function clear(): void {
files.value = [];
selectedKey.value = null;
clearDiagnostics();
}
/** Loads every file's diagnostics and the server's state from the engine. */
async function load(): Promise<void> {
const [list, status] = await Promise.all([run("diagnostics.list"), run("lsp.status")]);
if (status.ok) {
lsp.value = toStatus(status.value) ?? lsp.value;
}
if (!list.ok) {
return;
}
const value = list.value;
const raw = typeof value === "object" && value !== null && !Array.isArray(value) ? value.files : null;
if (!Array.isArray(raw)) {
return;
}
clear();
for (const entry of raw) {
if (typeof entry === "object" && entry !== null && !Array.isArray(entry) && typeof entry.path === "string") {
setFile(entry.path, toItems(entry.items));
}
}
}
/**
* Applies one engine event.
*
* @param event - the event.
*/
function onEvent(event: EngineEventPayload): void {
if (event.kind === "diagnosticsChanged") {
if (typeof event.path === "string" && event.path !== "") {
setFile(event.path, toItems(event.items));
}
} else if (event.kind === "lspStatus") {
lsp.value = toStatus(event) ?? lsp.value;
} else if (event.kind === "projectClosed") {
clear();
lsp.value = null;
} else if (event.kind === "projectOpened") {
void load();
}
}
/** Ends the event subscription; set while started. */
let unsubscribe: (() => void) | null = null;
/** Subscribes to engine events and loads the current state. */
function start(): void {
if (unsubscribe) {
return;
}
unsubscribe = onEngineEvent(onEvent);
void load();
}
/** Ends the subscription. */
function stop(): void {
unsubscribe?.();
unsubscribe = null;
}
/** Shows the tool window and asks it to take the focus: `problems.open`. */
function open(): void {
visible.value = true;
expanded.value = true;
focusPending.value = true;
focusRequest.value += 1;
}
/** Hides the tool window; the diagnostics stay. */
function hide(): void {
visible.value = false;
}
/**
* Selects a row.
*
* @param key - the row key, or null for none.
*/
function select(key: string | null): void {
selectedKey.value = key;
}
/**
* Moves the selection by `delta` rows, clamped to the list.
*
* @param delta - rows to move; positive is down.
*/
function move(delta: number): void {
const list = rows.value;
if (list.length === 0) {
return;
}
const from = selectedIndex.value < 0 ? (delta > 0 ? -1 : list.length) : selectedIndex.value;
const index = Math.min(list.length - 1, Math.max(0, from + delta));
selectedKey.value = list[index]?.key ?? null;
}
return {
visible,
expanded,
files,
lsp,
rows,
counts,
selectedKey,
selectedIndex,
focusRequest,
focusPending,
onEvent,
load,
start,
stop,
open,
hide,
select,
move,
};
});