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

@ -28,6 +28,7 @@ export const UI_COMMANDS: readonly UiCommandSpec[] = [
{ id: "goto.symbolOpen", labelKey: "command.goto.symbolOpen", menuPath: "Go/Symbol…", defaultShortcut: "Mod+T" },
{ id: "menu.open", labelKey: "command.menu.open", defaultShortcut: "Alt+M" },
{ id: "palette.open", labelKey: "command.palette.open", menuPath: "View/Command Palette", defaultShortcut: "Mod+Shift+P" },
{ id: "problems.open", labelKey: "command.problems.open", menuPath: "View/Problems", defaultShortcut: "Mod+Alt+P" },
{ id: "settings.open", labelKey: "command.settings.open", menuPath: "View/Settings…", defaultShortcut: "Mod+," },
{ id: "terminal.open", labelKey: "command.terminal.open", menuPath: "View/Terminal", defaultShortcut: "Mod+Shift+T" },
{ id: "view.toggleProjectTree", labelKey: "command.view.toggleProjectTree", menuPath: "View/Project", defaultShortcut: "Mod+1" },

View file

@ -11,6 +11,7 @@ import { EditorView } from "@codemirror/view";
import type { Extension } from "@codemirror/state";
import { basicSetup } from "codemirror";
import { languageExtensions, type SYNTAX_CLASS, type SyntaxToken } from "./language";
import { lintExtensions } from "./lint";
/**
* Colours of the highlight classes (`language.ts`), one `--lt-syntax-*`
@ -110,5 +111,5 @@ export const lutraEditorTheme: Extension = EditorView.theme({
* omitted or unknown.
*/
export function editorExtensions(path = ""): Extension {
return [basicSetup, lutraEditorTheme, languageExtensions(path)];
return [basicSetup, lutraEditorTheme, languageExtensions(path), lintExtensions(path)];
}

View file

@ -0,0 +1,212 @@
/**
* Diagnostics in the editor (M3.3): wavy underlines, gutter markers and
* the message on hover, from the language server's `diagnosticsChanged`
* events, through CodeMirror's lint extension.
*
* The Problems store ({@link useProblemsStore}) owns the diagnostics and
* hands every file's list to {@link publishDiagnostics}. This module keeps
* them by path; each editor state built for a path carries a view plugin
* that applies the file's list when the view shows the state and whenever
* it changes. Editor states of tabs in the background are brought up to
* date when they are shown again. Between two publications CodeMirror maps
* the ranges through the user's edits.
*
* Positions are 0-based lines with UTF-16 columns, converted with
* {@link positionOf} (CRLF-safe, clamped to the document). Colours come
* from tokens: errors `--lt-error`, warnings `--lt-accent`, information and
* hints `--lt-fg-muted`.
*
* @see useProblemsStore in `../problems/problems.ts`.
*/
import { lintGutter, setDiagnostics, type Diagnostic } from "@codemirror/lint";
import type { Extension, Text } from "@codemirror/state";
import { EditorView, ViewPlugin, type PluginValue } from "@codemirror/view";
import { positionOf } from "./engineText";
/** Severity of a diagnostic, as the engine names it. */
export type DiagnosticSeverity = "error" | "warning" | "info" | "hint";
/** A 0-based position; the column counts UTF-16 code units. */
export interface DiagnosticPosition {
/** Line. */
line: number;
/** Column. */
column: number;
}
/** One diagnostic of a file, as `diagnosticsChanged` carries it. */
export interface DiagnosticItem {
/** Where it applies; the end is exclusive. */
range: { start: DiagnosticPosition; end: DiagnosticPosition };
/** How severe it is. */
severity: DiagnosticSeverity;
/** The message. */
message: string;
/** Who reported it (`phpactor`, …). */
source?: string;
/** The diagnostic code. */
code?: string;
}
/** Diagnostics by project-relative path. */
const byPath = new Map<string, readonly DiagnosticItem[]>();
/** Plugins listening for changes, by path. */
const listeners = new Map<string, Set<() => void>>();
/**
* Stores the diagnostics of a file and updates the editors showing it.
*
* @param path - project-relative path with `/`.
* @param items - the file's diagnostics; empty clears them.
*/
export function publishDiagnostics(path: string, items: readonly DiagnosticItem[]): void {
if (items.length === 0) {
byPath.delete(path);
} else {
byPath.set(path, items);
}
for (const listener of listeners.get(path) ?? []) {
listener();
}
}
/** Drops every file's diagnostics (project closed) and updates the editors. */
export function clearDiagnostics(): void {
const paths = [...byPath.keys()];
byPath.clear();
for (const path of paths) {
for (const listener of listeners.get(path) ?? []) {
listener();
}
}
}
/**
* The diagnostics stored for a file.
*
* @param path - project-relative path.
*/
export function diagnosticsOf(path: string): readonly DiagnosticItem[] {
return byPath.get(path) ?? [];
}
/**
* Converts a file's diagnostics into CodeMirror's, against `doc`.
*
* @param doc - the document they apply to.
* @param items - the diagnostics.
* @returns CodeMirror diagnostics, sorted by start as the lint state needs.
*/
export function toCodeMirror(doc: Text, items: readonly DiagnosticItem[]): Diagnostic[] {
const out: Diagnostic[] = items.map((item) => {
const from = positionOf(doc, item.range.start.line, item.range.start.column);
const to = Math.max(from, positionOf(doc, item.range.end.line, item.range.end.column));
const source = [item.source, item.code].filter((part) => part !== undefined && part !== "").join(" ");
const diagnostic: Diagnostic = { from, to, severity: item.severity, message: item.message };
if (source !== "") {
diagnostic.source = source;
}
return diagnostic;
});
return out.sort((a, b) => a.from - b.from || a.to - b.to);
}
/**
* A view plugin that keeps the lint state of a path's editor in step with
* {@link publishDiagnostics}. It applies the current list right after the
* view shows the state (the dispatch waits a microtask: a plugin may not
* dispatch while the view is updating) and on every change.
*
* @param path - project-relative path of the editor's file.
*/
function diagnosticsPlugin(path: string): Extension {
return ViewPlugin.define((view): PluginValue => {
let alive = true;
const apply = (): void => {
if (!alive) {
return;
}
view.dispatch(setDiagnostics(view.state, toCodeMirror(view.state.doc, diagnosticsOf(path))));
};
let set = listeners.get(path);
if (!set) {
set = new Set();
listeners.set(path, set);
}
set.add(apply);
queueMicrotask(apply);
return {
destroy(): void {
alive = false;
const current = listeners.get(path);
current?.delete(apply);
if (current?.size === 0) {
listeners.delete(path);
}
},
};
});
}
/** Wavy underline of one severity in a token colour. */
function underline(colour: string): Record<string, string> {
return {
backgroundImage: "none",
textDecoration: `underline wavy ${colour}`,
textDecorationSkipInk: "none",
textUnderlineOffset: "3px",
};
}
/** Gutter dot of one severity in a token colour. */
function marker(colour: string): Record<string, string> {
return {
content: "none",
width: "8px",
height: "8px",
margin: "0 auto",
borderRadius: "50%",
backgroundColor: colour,
};
}
/** Lint colours from tokens, replacing CodeMirror's built-in ones. */
const lintTheme: Extension = EditorView.theme({
".cm-lintRange-error": underline("var(--lt-error)"),
".cm-lintRange-warning": underline("var(--lt-accent)"),
".cm-lintRange-info, .cm-lintRange-hint": underline("var(--lt-fg-muted)"),
".cm-lintRange-active": { backgroundColor: "var(--lt-editor-match-bg)" },
".cm-lintPoint:after": { borderBottomColor: "var(--lt-error)" },
".cm-lintPoint-warning:after": { borderBottomColor: "var(--lt-accent)" },
".cm-lintPoint-info:after, .cm-lintPoint-hint:after": { borderBottomColor: "var(--lt-fg-muted)" },
".cm-gutter-lint": { width: "14px" },
".cm-gutter-lint .cm-gutterElement": { display: "flex", alignItems: "center", padding: "0" },
".cm-lint-marker": { width: "8px", height: "8px" },
".cm-lint-marker-error": marker("var(--lt-error)"),
".cm-lint-marker-warning": marker("var(--lt-accent)"),
".cm-lint-marker-info, .cm-lint-marker-hint": marker("var(--lt-fg-muted)"),
".cm-diagnostic": { padding: "4px 8px", color: "var(--lt-fg)", whiteSpace: "pre-wrap" },
".cm-diagnostic-error": { borderLeft: "3px solid var(--lt-error)" },
".cm-diagnostic-warning": { borderLeft: "3px solid var(--lt-accent)" },
".cm-diagnostic-info, .cm-diagnostic-hint": { borderLeft: "3px solid var(--lt-fg-muted)" },
".cm-diagnosticSource": { color: "var(--lt-fg-muted)", opacity: "1" },
".cm-tooltip-lint": { maxWidth: "640px" },
".cm-panel.cm-panel-lint": { backgroundColor: "var(--lt-bg)", color: "var(--lt-fg)" },
".cm-panel.cm-panel-lint ul [aria-selected]": { backgroundColor: "var(--lt-editor-selection-bg)" },
});
/**
* The lint extensions of an editor for `path`: the lint state with its
* hover tooltips, the gutter column, the token theme and the plugin that
* feeds them. Files without diagnostics get them too, so a first
* publication shows at once.
*
* @param path - project-relative path of the file; empty for none.
*/
export function lintExtensions(path: string): Extension {
if (path === "") {
return [];
}
return [lintGutter(), lintTheme, diagnosticsPlugin(path)];
}

View file

@ -15,14 +15,16 @@
* `view.toggleStructure` (`Mod+2`): each shows its tool window, or hides
* the left window when that tool window is already shown.
*
* The bottom panel ({@link BottomPanel}) holds the Find and Terminal tool
* windows, as tabs in its header while both are shown. Find appears with
* the UI command `find.open` (`Mod+Alt+F`), Terminal with `terminal.open`
* (`Mod+Shift+T`, M3.6); both are supplied here so they work before the
* panel exists, and each makes its tool window the active tab. The panel
* collapses to its header; closing it hides the active tool window (the
* other one, if shown, becomes active). The Find store keeps the results
* and the Terminal store the running terminals while they are hidden.
* The bottom panel ({@link BottomPanel}) holds the Find, Terminal and
* Problems tool windows, as tabs in its header while more than one is
* shown. Find appears with the UI command `find.open` (`Mod+Alt+F`),
* Terminal with `terminal.open` (`Mod+Shift+T`, M3.6), Problems with
* `problems.open` (`Mod+Alt+P`, M3.3); all are supplied here so they work
* before the panel exists, and each makes its tool window the active tab.
* The panel collapses to its header; closing it hides the active tool
* window (another shown one becomes active). The Find store keeps the
* results, the Terminal store the running terminals and the Problems store
* the diagnostics while they are hidden.
*
* A slim header bar along the top (M3.9) holds the app menu
* ({@link AppMenu}); its `header` slot can replace it.
@ -35,6 +37,8 @@ import { useFindStore } from "../../stores/find";
import { useTerminalStore } from "../../stores/terminal";
import FindToolWindow from "../find/FindToolWindow.vue";
import TerminalToolWindow from "../terminal/TerminalToolWindow.vue";
import ProblemsToolWindow from "../problems/ProblemsToolWindow.vue";
import { useProblemsStore } from "../problems/problems";
import ProjectToolWindow from "../project/ProjectToolWindow.vue";
import StatusBar from "../StatusBar.vue";
import StructureToolWindow from "../structure/StructureToolWindow.vue";
@ -79,9 +83,10 @@ function toggleLeft(tool: LeftTool): void {
const commands = useCommandsStore();
const find = useFindStore();
const terminal = useTerminalStore();
const problems = useProblemsStore();
/** Tool windows of the bottom panel. */
type BottomTool = "find" | "terminal";
type BottomTool = "find" | "terminal" | "problems";
/** The bottom tool window last chosen. */
const bottomTool = ref<BottomTool>("find");
/** Bottom tool windows that are shown, in tab order. */
@ -89,6 +94,7 @@ const bottomTools = computed(() => {
const tools: { id: BottomTool; title: string }[] = [];
if (find.visible) tools.push({ id: "find", title: t("find.toolWindow.title") });
if (terminal.visible) tools.push({ id: "terminal", title: t("terminal.toolWindow.title") });
if (problems.visible) tools.push({ id: "problems", title: t("problems.toolWindow.title") });
return tools;
});
/** The active bottom tool window: the chosen one if shown, else the first. */
@ -96,15 +102,15 @@ const bottomActive = computed<BottomTool | null>(() => {
const tools = bottomTools.value;
return tools.some((tool) => tool.id === bottomTool.value) ? bottomTool.value : (tools[0]?.id ?? null);
});
/** The store of the active bottom tool window. */
const bottomStore = computed(() =>
bottomActive.value === "terminal" ? terminal : bottomActive.value === "problems" ? problems : find,
);
/** Expansion of the panel, kept per tool window by its store. */
const bottomOpen = computed({
get: () => (bottomActive.value === "terminal" ? terminal.expanded : find.expanded),
get: () => bottomStore.value.expanded,
set: (open: boolean) => {
if (bottomActive.value === "terminal") {
terminal.expanded = open;
} else {
find.expanded = open;
}
bottomStore.value.expanded = open;
},
});
@ -114,18 +120,14 @@ const bottomOpen = computed({
* @param id - the tool window id from the panel.
*/
function chooseBottom(id: string): void {
if (id === "find" || id === "terminal") {
if (id === "find" || id === "terminal" || id === "problems") {
bottomTool.value = id;
}
}
/** Hides the active bottom tool window. */
function closeBottom(): void {
if (bottomActive.value === "terminal") {
terminal.hide();
} else {
find.hide();
}
bottomStore.value.hide();
}
/** Withdraws the command handlers; filled while mounted. */
@ -134,6 +136,7 @@ let withdraw: (() => void)[] = [];
onMounted(() => {
find.start();
terminal.start();
problems.start();
withdraw = [
commands.provide("view.toggleProjectTree", {
run: () => {
@ -153,6 +156,12 @@ onMounted(() => {
},
enabled: () => commands.isEnabled("terminal.create"),
}),
commands.provide("problems.open", {
run: () => {
bottomTool.value = "problems";
problems.open();
},
}),
commands.provide("view.toggleStructure", {
run: () => {
toggleLeft("structure");
@ -168,6 +177,7 @@ onBeforeUnmount(() => {
withdraw = [];
find.stop();
terminal.stop();
problems.stop();
});
</script>
@ -239,6 +249,7 @@ onBeforeUnmount(() => {
v-if="terminal.visible"
v-show="bottomActive === 'terminal'"
/>
<ProblemsToolWindow v-show="bottomActive === 'problems'" />
</BottomPanel>
<StatusBar />
</div>

View file

@ -53,6 +53,7 @@ const ITEM_ORDER = [
"view.toggleStructure",
"find.open",
"terminal.open",
"problems.open",
"settings.open",
"goto.fileOpen",
"goto.classOpen",

View file

@ -0,0 +1,374 @@
<script setup lang="ts">
/**
* The Problems tool window (M3.3), shown in the bottom panel: the
* language server's diagnostics of the project, grouped by file.
*
* - **Header line:** the totals by severity, or the server's state while
* it starts, restarts, failed or is not running.
* - **List:** one group per file (name, directory, count), then its
* diagnostics with a severity icon, the message, the source and code,
* and the position. Up/Down, Page Up/Down, Home and End move the
* selection; Enter or a click reveals the position through the command
* `editor.reveal`.
* - State lives in the Problems store (`problems.ts`), so it is kept while
* the window is hidden. Icons are Lucide's; colours are tokens.
*/
import { CircleAlert, Info, Lightbulb, TriangleAlert } from "@lucide/vue";
import { computed, nextTick, onMounted, ref, watch } from "vue";
import { useCommandsStore } from "../../commands/store";
import { t } from "../../i18n";
import { baseName } from "../../stores/editor";
import type { DiagnosticSeverity } from "../editor/lint";
import { useProblemsStore, type ProblemRow } from "./problems";
const problems = useProblemsStore();
const commands = useCommandsStore();
/** The list element. */
const list = ref<HTMLElement | null>(null);
/** Rows moved by Page Up and Page Down. */
const PAGE = 10;
/** Icons by severity. */
const ICONS = { error: CircleAlert, warning: TriangleAlert, info: Info, hint: Lightbulb } as const;
/**
* The accessible name of a severity.
*
* @param severity - the severity.
*/
function severityLabel(severity: DiagnosticSeverity): string {
const labels: Record<DiagnosticSeverity, () => string> = {
error: () => t("problems.severity.error"),
warning: () => t("problems.severity.warning"),
info: () => t("problems.severity.info"),
hint: () => t("problems.severity.hint"),
};
return labels[severity]();
}
/** The line above the list: the server's state, or the totals. */
const status = computed(() => {
const lsp = problems.lsp;
const message = lsp?.message ?? "";
if (lsp?.state === "starting") {
return t("problems.lsp.starting");
}
if (lsp?.state === "restarting") {
return t("problems.lsp.restarting", { message });
}
if (lsp?.state === "failed") {
return t("problems.lsp.failed", { message });
}
if ((lsp === null || lsp.state === "stopped") && problems.rows.length === 0) {
return t("problems.lsp.stopped");
}
if (problems.rows.length === 0) {
return t("problems.empty");
}
const c = problems.counts;
return t("problems.summary", {
errors: String(c.error),
warnings: String(c.warning),
infos: String(c.info + c.hint),
});
});
/** A file with its rows and their indexes in the flat list. */
interface ProblemGroup {
/** Project-relative path. */
path: string;
/** The rows with their flat index. */
rows: { row: ProblemRow; index: number }[];
}
/** The rows grouped by file, in display order. */
const groups = computed<ProblemGroup[]>(() => {
const out: ProblemGroup[] = [];
problems.rows.forEach((row, index) => {
const last = out[out.length - 1];
if (last?.path === row.path) {
last.rows.push({ row, index });
} else {
out.push({ path: row.path, rows: [{ row, index }] });
}
});
return out;
});
/**
* The DOM id of a row.
*
* @param index - the row's index in the flat list.
*/
function optionId(index: number): string {
return `problem-row-${String(index)}`;
}
/**
* The directory part of a path, empty at the root.
*
* @param path - project-relative path.
*/
function dirName(path: string): string {
const slash = path.lastIndexOf("/");
return slash < 0 ? "" : path.slice(0, slash);
}
/**
* Source and code of a diagnostic, for the muted suffix.
*
* @param row - the row.
*/
function origin(row: ProblemRow): string {
return [row.item.source, row.item.code].filter((part) => part !== undefined && part !== "").join(" ");
}
/**
* The position of a row, 1-based for people.
*
* @param row - the row.
*/
function position(row: ProblemRow): string {
const start = row.item.range.start;
return t("problems.position", { line: String(start.line + 1), column: String(start.column + 1) });
}
/**
* Reveals a diagnostic in the editor.
*
* @param row - the row.
*/
function openRow(row: ProblemRow): void {
problems.select(row.key);
const start = row.item.range.start;
void commands.execute("editor.reveal", { path: row.path, line: start.line, column: start.column });
}
/**
* Keyboard navigation in the list.
*
* @param event - the key event.
*/
function onListKey(event: KeyboardEvent): void {
const count = problems.rows.length;
const moves: Record<string, number> = {
ArrowDown: 1,
ArrowUp: -1,
PageDown: PAGE,
PageUp: -PAGE,
Home: -count,
End: count,
};
const delta = moves[event.key];
if (delta !== undefined) {
event.preventDefault();
problems.move(delta);
} else if (event.key === "Enter") {
const row = problems.rows[problems.selectedIndex];
if (row) {
event.preventDefault();
openRow(row);
}
}
}
/** Takes the focus `problems.open` asked for, once. */
async function takeFocus(): Promise<void> {
if (!problems.focusPending) {
return;
}
problems.focusPending = false;
await nextTick();
list.value?.focus();
}
watch(() => problems.focusRequest, takeFocus);
onMounted(() => {
void takeFocus();
});
watch(
() => problems.selectedIndex,
async (index) => {
await nextTick();
const element = index < 0 ? null : document.getElementById(optionId(index));
if (element && typeof element.scrollIntoView === "function") {
element.scrollIntoView({ block: "nearest" });
}
},
);
</script>
<template>
<div
class="problems"
data-test="problems"
>
<div
class="problems__status"
role="status"
data-test="problems-status"
>
{{ status }}
</div>
<div
ref="list"
class="problems__list"
role="listbox"
tabindex="0"
:aria-label="t('problems.list.label')"
:aria-activedescendant="problems.selectedIndex >= 0 ? optionId(problems.selectedIndex) : undefined"
data-test="problems-list"
@keydown="onListKey"
>
<div
v-for="group in groups"
:key="group.path"
role="group"
:aria-label="group.path"
>
<div
class="problems__file"
data-test="problems-file"
>
<span class="problems__file-name">{{ baseName(group.path) }}</span>
<span class="problems__file-dir">{{ dirName(group.path) }}</span>
<span
class="problems__file-count"
:title="t('problems.file.count', { count: String(group.rows.length) })"
>{{ group.rows.length }}</span>
</div>
<div
v-for="{ row, index } in group.rows"
:id="optionId(index)"
:key="row.key"
role="option"
class="problems__row"
:class="{ 'problems__row--selected': problems.selectedKey === row.key }"
:aria-selected="problems.selectedKey === row.key"
:data-severity="row.item.severity"
data-test="problems-row"
@click="openRow(row)"
>
<component
:is="ICONS[row.item.severity]"
:size="14"
class="problems__icon"
:class="`problems__icon--${row.item.severity}`"
role="img"
:aria-label="severityLabel(row.item.severity)"
/>
<span class="problems__message">{{ row.item.message }}</span>
<span
v-if="origin(row) !== ''"
class="problems__origin"
>{{ origin(row) }}</span>
<span class="problems__position">{{ position(row) }}</span>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.problems {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
}
.problems__status {
padding: var(--lt-space-xs, 2px) var(--lt-space-m, 8px);
color: var(--lt-fg-muted);
}
.problems__list {
flex: 1;
min-height: 0;
overflow: auto;
border-top: 1px solid var(--lt-border);
outline: none;
}
.problems__list:focus-visible {
box-shadow: inset 0 0 0 1px var(--lt-accent);
}
.problems__file {
display: flex;
align-items: baseline;
gap: var(--lt-space-m, 8px);
padding: var(--lt-space-xs, 2px) var(--lt-space-m, 8px);
white-space: nowrap;
}
.problems__file-name {
font-weight: 600;
}
.problems__file-dir {
overflow: hidden;
text-overflow: ellipsis;
color: var(--lt-fg-muted);
}
.problems__file-count {
margin-left: auto;
color: var(--lt-fg-muted);
}
.problems__row {
display: flex;
align-items: center;
gap: var(--lt-space-m, 8px);
padding: 0 var(--lt-space-m, 8px) 0 var(--lt-space-l, 24px);
white-space: nowrap;
cursor: pointer;
}
.problems__row:hover {
background: color-mix(in srgb, var(--lt-fg) 6%, transparent);
}
.problems__row--selected,
.problems__row--selected:hover {
background: var(--lt-editor-selection-bg);
}
.problems__icon {
flex: none;
}
.problems__icon--error {
color: var(--lt-error);
}
.problems__icon--warning {
color: var(--lt-accent);
}
.problems__icon--info,
.problems__icon--hint {
color: var(--lt-fg-muted);
}
.problems__message {
overflow: hidden;
text-overflow: ellipsis;
}
.problems__origin,
.problems__position {
flex: none;
color: var(--lt-fg-muted);
}
.problems__row--selected .problems__origin,
.problems__row--selected .problems__position {
color: var(--lt-fg);
}
</style>

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,
};
});

View file

@ -12,6 +12,7 @@
"command.key.shift": "Shift",
"command.menu.open": "Open Main Menu",
"command.palette.open": "Command Palette",
"command.problems.open": "Problems",
"command.settings.open": "Settings…",
"command.terminal.open": "Terminal",
"command.unavailable": "{command} cannot run right now",
@ -80,6 +81,7 @@
"menu.label": "Main menu",
"notification.close": "Close notification",
"notification.command.failed": "{command} failed: {message}",
"notification.lsp.failed": "The PHP language server stopped: {reason}. Run Restart PHP Language Server to try again.",
"notification.project.notLocal": "The chosen folder is not on this computer: {reason}",
"notification.project.openFailed": "Cannot open {path}: {reason}",
"notification.project.unsavedChanges": "Cannot open {path} while {what} has unsaved changes. Save or close it first.",
@ -101,6 +103,20 @@
"palette.label": "Command palette",
"palette.noMatches": "No matching commands",
"palette.placeholder": "Type a command name",
"problems.empty": "No problems found in open files",
"problems.file.count": "{count} problems",
"problems.list.label": "Problems of the project",
"problems.lsp.failed": "Phpactor stopped: {message}",
"problems.lsp.restarting": "Phpactor is restarting: {message}",
"problems.lsp.starting": "Phpactor is starting…",
"problems.lsp.stopped": "No PHP language server is running. It starts when PHP and Phpactor are available.",
"problems.position": "line {line}, column {column}",
"problems.severity.error": "Error",
"problems.severity.hint": "Hint",
"problems.severity.info": "Information",
"problems.severity.warning": "Warning",
"problems.summary": "{errors} errors, {warnings} warnings, {infos} other",
"problems.toolWindow.title": "Problems",
"project.empty.noFolder": "No folder is open.",
"project.openFolder": "Open Folder…",
"project.toolWindow.title": "Project",

View file

@ -120,6 +120,20 @@ export type EngineEventPayload =
terminalId: unknown;
/** Exit code, null when Lutra closed it; unchecked. */
code: unknown;
}
| {
kind: "lspStatus";
/** `starting`, `ready`, `restarting`, `failed` or `stopped`; unchecked. */
state: unknown;
/** Why it restarts or failed; unchecked. */
message?: unknown;
}
| {
kind: "diagnosticsChanged";
/** Project-relative path of the file; unchecked, it comes from the engine. */
path: unknown;
/** `[{range, severity, message, source?, code?}]`, empty when cleared; unchecked. */
items: unknown;
};
/** Callback receiving engine events. */