PM: merge M3.3 LSP wiring and diagnostics
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
a674040797
34 changed files with 3562 additions and 37 deletions
12
ROADMAP.md
12
ROADMAP.md
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
**Stage: pre-alpha (M2 done)** · next: M3 language server, terminal, CLI and MCP (the MVP); alpha when the six core workflows work end to end (see [docs/roadmap.md › Alpha gate](docs/roadmap.md#alpha-gate))
|
||||
|
||||
> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-20 · **Change:** minor (M3.10: autosave; M3.6: integrated terminal) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only
|
||||
> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-21 · **Change:** minor (M3.3: diagnostics from Phpactor) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only
|
||||
|
||||
Lutra is a clean-room, open-source PHP IDE with a Rust core and a Tauri + Vue interface, targeting the PhpStorm workflow. Agents can drive all of it over MCP, the `lutra` CLI and a JSON control channel. This page is the summary; the evidence is in [`docs/target-app-parity.md`](docs/target-app-parity.md) and the work list in [`docs/gaps.md`](docs/gaps.md).
|
||||
|
||||
|
|
@ -12,8 +12,8 @@ Lutra is a clean-room, open-source PHP IDE with a Rust core and a Tauri + Vue in
|
|||
|
||||
| | Value | Kind |
|
||||
|---|---|---|
|
||||
| **Feature breadth** (PhpStorm's actions, tool windows, languages, integrations exist) | **~15%** (23 of 155 feature units of the public PhpStorm help have at least partial support; ~21% after the running cycle C4) | estimated |
|
||||
| **Feature depth** (weighted by use, scored by behaviour) | **~3.8%** (Editor core 11% × weight 12, Navigation 10% × weight 10, Project view 8% × weight 6, Search and replace 8% × weight 6, Terminal 15% × weight 3, Settings 7% × weight 1, of 101) | estimated |
|
||||
| **Feature breadth** (PhpStorm's actions, tool windows, languages, integrations exist) | **~15%** (24 of 155 feature units of the public PhpStorm help have at least partial support; ~21% after the running cycle C4) | estimated |
|
||||
| **Feature depth** (weighted by use, scored by behaviour) | **~4.1%** (Editor core 11% × weight 12, Navigation 10% × weight 10, Inspections 4% × weight 8, Project view 8% × weight 6, Search and replace 8% × weight 6, Terminal 15% × weight 3, Settings 7% × weight 1, of 101) | estimated |
|
||||
| **To MVP (M3)** | **~12 h left** (M3 = 80 h raw × 0.15; done so far: M1 ~5.6 h, M2 ~6.1 h, measured); was ~190 h before calibration | estimated (factor per cycle: C1 0.07, C2 0.10, C3 0.14) |
|
||||
| **To full parity** | **~450 h** at the current factor of ~0.15 (range 300–3,300 h; the factor has risen each cycle, and deep areas such as type inference and inspections have no data yet) | estimated |
|
||||
|
||||
|
|
@ -25,7 +25,7 @@ Dimension hours overlap: language, framework and tooling hours are part of the f
|
|||
|
||||
| Dimension | % | One agent (h) | Doc |
|
||||
|---|---:|---:|---|
|
||||
| Features (depth) | ~3.8% | ~2,892 | [target-app-parity.md](docs/target-app-parity.md) |
|
||||
| Features (depth) | ~4.1% | ~2,882 | [target-app-parity.md](docs/target-app-parity.md) |
|
||||
| UI/UX fidelity | 1% (est.) | ~150 on top of features | [ui-parity.md](docs/ui-parity.md) |
|
||||
| PHP language support | 0% | ~920 (in features) | [language-parity.md](docs/language-parity.md) |
|
||||
| Frameworks (Symfony, Laravel, Shopware, WordPress) | 0% | ~300 (in features) | [framework-parity.md](docs/framework-parity.md) |
|
||||
|
|
@ -46,7 +46,7 @@ Stability 8%: no-panic lints, the engine guard, a fuzzed control protocol and a
|
|||
| Navigation (go to class/file/symbol, recent files, structure) | 10% (est.) | ~102 |
|
||||
| Search and replace (in file, in project, structural) | 8% (est.) | ~70 |
|
||||
| Code completion | 0% | ~250 |
|
||||
| Inspections and quick-fixes | 0% | ~300 |
|
||||
| Inspections and quick-fixes | 4% (est.) | ~290 |
|
||||
| Refactoring | 0% | ~250 |
|
||||
| Code style and formatting | 0% | ~120 |
|
||||
| Version control (Git) | 0% | ~150 |
|
||||
|
|
@ -75,6 +75,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a
|
|||
|
||||
| Date | What landed |
|
||||
|---|---|
|
||||
| 2026-10-21 | M3.3: PHP errors show up while you type. Lutra starts Phpactor for the open project. Problems such as calling a method that does not exist or using an unknown class get a wavy underline, a dot in the gutter and their message on hover, and `Mod+Alt+P` opens a Problems tab that lists them by file; click one to jump there. |
|
||||
| 2026-10-20 | M3.10: autosave. Changed files are saved when you leave the Lutra window, when you switch tabs and after 15 seconds without typing; each can be turned off in Settings › Editor. Files that were changed outside Lutra are left for you to decide. Later features such as deployment save everything first through the same step. |
|
||||
| 2026-10-19 | M3.8: agents can drive Lutra over MCP: `claude mcp add lutra -- lutra mcp`, then Claude can list and run every command, look at the window, read open files including unsaved changes and follow what happens. Closing Lutra needs an explicit confirmation. |
|
||||
| 2026-10-18 | M3.6: an integrated terminal: `Mod+Shift+T` opens a Terminal tab in the bottom panel (next to Find) running PowerShell or cmd on Windows and your shell elsewhere, in the project folder; several terminals as sub-tabs, copy and paste, Lutra's own colours in both themes. Plain Ctrl keys go to the shell; agents can create terminals, type into them and read their output over the control channel. |
|
||||
|
|
@ -98,6 +99,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a
|
|||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-21 | minor | M3.3: Inspections 0% → 4% (est.), feature depth ~3.8% → ~4.1%, breadth 23 → 24 units |
|
||||
| 2026-10-20 | minor | M3.6: Terminal 0% → 15%, feature depth ~3.3% → ~3.8% |
|
||||
| 2026-10-20 | minor | M3.10: autosave; Editor core 10% → 11% (est.), feature depth ~3.2% → ~3.3% |
|
||||
| 2026-10-18 | minor | Feature breadth measured against the full PhpStorm help inventory (155 units); M7–M9 added |
|
||||
|
|
|
|||
192
crates/control/tests/lsp.rs
Normal file
192
crates/control/tests/lsp.rs
Normal file
|
|
@ -0,0 +1,192 @@
|
|||
//! The language server wiring over a real TCP control connection:
|
||||
//! `lspStatus` and `diagnosticsChanged` arrive as events while a buffer is
|
||||
//! edited, and `diagnostics.list` / `lsp.status` answer from the engine.
|
||||
//! The server is M3.2's fake, which publishes each document's text as its
|
||||
//! one diagnostic.
|
||||
|
||||
#![allow(
|
||||
clippy::unwrap_used,
|
||||
clippy::expect_used,
|
||||
clippy::indexing_slicing,
|
||||
clippy::panic
|
||||
)]
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::TcpStream;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use lutra_engine::Engine;
|
||||
use lutra_engine::lsp::{Launch, ServerOptions};
|
||||
use lutra_testkit::EngineBackend;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// A client that keeps responses and event lines apart.
|
||||
struct Client {
|
||||
reader: BufReader<TcpStream>,
|
||||
writer: TcpStream,
|
||||
events: Vec<Value>,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
fn connect(addr: std::net::SocketAddr) -> Self {
|
||||
let stream = TcpStream::connect(addr).unwrap();
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(30)))
|
||||
.unwrap();
|
||||
Self {
|
||||
writer: stream.try_clone().unwrap(),
|
||||
reader: BufReader::new(stream),
|
||||
events: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn line(&mut self) -> Value {
|
||||
let mut line = String::new();
|
||||
self.reader.read_line(&mut line).expect("line within 30 s");
|
||||
serde_json::from_str(&line).unwrap()
|
||||
}
|
||||
|
||||
fn call(&mut self, request: Value) -> Value {
|
||||
self.writer
|
||||
.write_all(format!("{request}\n").as_bytes())
|
||||
.unwrap();
|
||||
loop {
|
||||
let line = self.line();
|
||||
if line.get("event").is_some() {
|
||||
self.events.push(line["event"].clone());
|
||||
} else {
|
||||
return line;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The next event (queued or read) for which `pick` holds.
|
||||
fn event(&mut self, pick: impl Fn(&Value) -> bool) -> Value {
|
||||
if let Some(i) = self.events.iter().position(&pick) {
|
||||
return self.events.remove(i);
|
||||
}
|
||||
loop {
|
||||
let line = self.line();
|
||||
if let Some(event) = line.get("event") {
|
||||
if pick(event) {
|
||||
return event.clone();
|
||||
}
|
||||
self.events.push(event.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn execute(command: &str, params: Value) -> Value {
|
||||
json!({"id": command, "method": "engine.execute", "params": {"command": command, "params": params}})
|
||||
}
|
||||
|
||||
/// Pumps the backend every 20 ms, like the desktop's pump thread, until
|
||||
/// dropped.
|
||||
struct Pump(Arc<AtomicBool>);
|
||||
|
||||
impl Pump {
|
||||
fn start(backend: Arc<EngineBackend>) -> Self {
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let flag = stop.clone();
|
||||
std::thread::spawn(move || {
|
||||
while !flag.load(Ordering::Relaxed) {
|
||||
backend.pump();
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
});
|
||||
Self(stop)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Pump {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// The fake server binary, built on demand when this test runs alone.
|
||||
fn fake_server() -> std::path::PathBuf {
|
||||
let exe = format!("lutra-lsp-fake{}", std::env::consts::EXE_SUFFIX);
|
||||
let deps = std::env::current_exe().unwrap();
|
||||
let path = deps.parent().unwrap().parent().unwrap().join(exe);
|
||||
if !path.exists() {
|
||||
let cargo = std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
|
||||
let status = std::process::Command::new(cargo)
|
||||
.args(["build", "-p", "lutra-lsp", "--bin", "lutra-lsp-fake"])
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success(), "building lutra-lsp-fake failed");
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagnostics_over_tcp() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(
|
||||
dir.path().join("a.php"),
|
||||
"<?php
|
||||
",
|
||||
)
|
||||
.unwrap();
|
||||
let mut engine = Engine::new().unwrap();
|
||||
engine.set_language_server(Some(Launch {
|
||||
command: fake_server().into(),
|
||||
args: Vec::new(),
|
||||
options: ServerOptions::default(),
|
||||
tick: Some(std::time::Duration::from_millis(50)),
|
||||
}));
|
||||
let backend = Arc::new(EngineBackend::with_engine(engine));
|
||||
let server = lutra_control::start(0, backend.clone()).unwrap();
|
||||
let mut client = Client::connect(server.local_addr());
|
||||
client.call(json!({"id": 1, "method": "events.subscribe"}));
|
||||
let _pump = Pump::start(backend.clone());
|
||||
|
||||
let r = client.call(execute("project.open", json!({"path": dir.path()})));
|
||||
assert!(r["error"].is_null(), "{r}");
|
||||
client.event(|e| e["kind"] == "lspStatus" && e["state"] == "starting");
|
||||
client.event(|e| e["kind"] == "lspStatus" && e["state"] == "ready");
|
||||
let r = client.call(execute("lsp.status", Value::Null));
|
||||
assert_eq!(r["result"]["state"], "ready", "{r}");
|
||||
|
||||
let r = client.call(execute("file.open", json!({"path": "a.php"})));
|
||||
let id = r["result"]["id"].as_u64().unwrap();
|
||||
let first = client.event(|e| e["kind"] == "diagnosticsChanged");
|
||||
assert_eq!(first["path"], "a.php");
|
||||
assert_eq!(
|
||||
first["items"][0]["message"],
|
||||
"<?php
|
||||
"
|
||||
);
|
||||
let r = client.call(execute(
|
||||
"buffer.edit",
|
||||
json!({"id": id, "baseVersion": 1, "edits": [{"from": 6, "to": 6, "insert": "echo 1;"}]}),
|
||||
));
|
||||
assert!(r["error"].is_null(), "{r}");
|
||||
let changed = client.event(|e| {
|
||||
e["kind"] == "diagnosticsChanged"
|
||||
&& e["items"][0]["message"]
|
||||
== "<?php
|
||||
echo 1;"
|
||||
});
|
||||
assert_eq!(changed["items"][0]["severity"], "error");
|
||||
assert_eq!(
|
||||
changed["items"][0]["range"],
|
||||
json!({"start": {"line": 0, "column": 0}, "end": {"line": 0, "column": 0}})
|
||||
);
|
||||
|
||||
let r = client.call(execute("diagnostics.list", json!({})));
|
||||
assert_eq!(r["result"]["files"][0]["path"], "a.php", "{r}");
|
||||
assert_eq!(
|
||||
r["result"]["files"][0]["items"][0]["message"],
|
||||
"<?php
|
||||
echo 1;"
|
||||
);
|
||||
|
||||
let r = client.call(execute("project.close", json!({"force": true})));
|
||||
assert!(r["error"].is_null(), "{r}");
|
||||
client.event(|e| e["kind"] == "lspStatus" && e["state"] == "stopped");
|
||||
}
|
||||
|
|
@ -49,6 +49,7 @@ impl Command for Quit {
|
|||
|
||||
fn run(&self, state: &mut State, _params: Value) -> Result<Outcome, EngineError> {
|
||||
crate::cmd::terminal::close_all(state);
|
||||
crate::lsp::shutdown_now(state);
|
||||
Ok(Outcome::effect(Effect::Quit))
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -167,6 +167,7 @@ impl Command for Edit {
|
|||
let (version, dirty) = (open.version, open.dirty());
|
||||
let now = std::time::Instant::now();
|
||||
journal::mark_edited(state, p.id, now);
|
||||
crate::lsp::record_edits(state, p.id, p.base_version, &edits);
|
||||
super::syntax::record_edits(state, p.id, p.base_version, edits, now);
|
||||
state.emit(Event::BufferChanged { id: p.id, version });
|
||||
if dirty != was_dirty {
|
||||
|
|
|
|||
110
crates/engine/src/cmd/lsp_diagnostics.rs
Normal file
110
crates/engine/src/cmd/lsp_diagnostics.rs
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
//! Language server commands of M3.3: `diagnostics.list`, `lsp.status` and
|
||||
//! `lsp.restart`. The wiring itself lives in [`crate::lsp`].
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::params::{parse, project_path};
|
||||
use crate::workspace::path_string;
|
||||
use crate::{Command, CommandSpec, EngineError, Outcome, Registry, State};
|
||||
|
||||
/// Registers the commands of this module.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`EngineError::Internal`] if an id is already taken.
|
||||
pub fn register(registry: &mut Registry) -> Result<(), EngineError> {
|
||||
registry.register(Box::new(List))?;
|
||||
registry.register(Box::new(Status))?;
|
||||
registry.register(Box::new(Restart))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Params of `diagnostics.list`.
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct ListParams {
|
||||
/// Only this file (project-relative or absolute inside the project).
|
||||
#[serde(default)]
|
||||
path: Option<String>,
|
||||
}
|
||||
|
||||
/// `diagnostics.list`: the language server's current diagnostics.
|
||||
pub struct List;
|
||||
|
||||
impl Command for List {
|
||||
fn spec(&self) -> &CommandSpec {
|
||||
&CommandSpec {
|
||||
id: "diagnostics.list",
|
||||
label: "List Diagnostics",
|
||||
menu_path: None,
|
||||
default_shortcut: None,
|
||||
params: "{ path?: string }; returns { files: [{ path, items: [{ range: { start: { line, column }, end }, severity: error|warning|info|hint, message, source?, code? }] }] } sorted by path, only files with diagnostics; columns are UTF-16; empty without a project or language server",
|
||||
}
|
||||
}
|
||||
|
||||
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
||||
let command = self.spec().id;
|
||||
let p: ListParams = parse(command, params)?;
|
||||
let path = match p.path {
|
||||
Some(path) if state.has_project() => {
|
||||
Some(path_string(&project_path(state, command, &path)?))
|
||||
}
|
||||
Some(_) => return Ok(Outcome::value(json!({ "files": [] }))),
|
||||
None => None,
|
||||
};
|
||||
let files = state.lsp.diagnostics(path.as_deref());
|
||||
let files =
|
||||
serde_json::to_value(files).map_err(|e| EngineError::Internal(e.to_string()))?;
|
||||
Ok(Outcome::value(json!({ "files": files })))
|
||||
}
|
||||
}
|
||||
|
||||
/// `lsp.status`: the language server's state, as `lspStatus` last reported
|
||||
/// it.
|
||||
pub struct Status;
|
||||
|
||||
impl Command for Status {
|
||||
fn spec(&self) -> &CommandSpec {
|
||||
&CommandSpec {
|
||||
id: "lsp.status",
|
||||
label: "Language Server Status",
|
||||
menu_path: None,
|
||||
default_shortcut: None,
|
||||
params: "none; returns { state: starting|ready|restarting|failed|stopped, message?, startupMs? } (startupMs: from start to the first ready)",
|
||||
}
|
||||
}
|
||||
|
||||
fn run(&self, state: &mut State, _params: Value) -> Result<Outcome, EngineError> {
|
||||
let mut value = serde_json::to_value(state.lsp.status())
|
||||
.map_err(|e| EngineError::Internal(e.to_string()))?;
|
||||
if let (Some(ms), Some(object)) = (state.lsp.startup_ms(), value.as_object_mut()) {
|
||||
object.insert("startupMs".into(), Value::from(ms));
|
||||
}
|
||||
Ok(Outcome::value(value))
|
||||
}
|
||||
}
|
||||
|
||||
/// `lsp.restart`: stops the language server; the next pump starts a fresh
|
||||
/// one when the project and toolchain allow it.
|
||||
pub struct Restart;
|
||||
|
||||
impl Command for Restart {
|
||||
fn spec(&self) -> &CommandSpec {
|
||||
&CommandSpec {
|
||||
id: "lsp.restart",
|
||||
label: "Restart PHP Language Server",
|
||||
menu_path: Some("Tools/Restart PHP Language Server"),
|
||||
default_shortcut: None,
|
||||
params: "none; returns null; lspStatus reports stopped, then starting and ready",
|
||||
}
|
||||
}
|
||||
|
||||
fn enabled(&self, state: &State) -> bool {
|
||||
state.has_project()
|
||||
}
|
||||
|
||||
fn run(&self, state: &mut State, _params: Value) -> Result<Outcome, EngineError> {
|
||||
crate::lsp::restart(state);
|
||||
Ok(Outcome::value(Value::Null))
|
||||
}
|
||||
}
|
||||
|
|
@ -4,6 +4,7 @@ mod app;
|
|||
mod buffer;
|
||||
mod file;
|
||||
pub mod goto;
|
||||
mod lsp_diagnostics;
|
||||
mod params;
|
||||
mod project;
|
||||
mod recovery;
|
||||
|
|
@ -58,5 +59,6 @@ pub fn register_builtins(registry: &mut Registry) -> Result<(), EngineError> {
|
|||
registry.register(Box::new(terminal::Input))?;
|
||||
registry.register(Box::new(terminal::Resize))?;
|
||||
registry.register(Box::new(terminal::Close))?;
|
||||
lsp_diagnostics::register(registry)?;
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -151,6 +151,7 @@ impl Engine {
|
|||
cmd::syntax::pump(state, std::time::Instant::now());
|
||||
cmd::toolchain::pump(state);
|
||||
cmd::terminal::pump(state);
|
||||
crate::lsp::pump(state);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(state.take_events())
|
||||
|
|
@ -241,6 +242,14 @@ impl Engine {
|
|||
self.state.toolchain.allow_downloads(source);
|
||||
}
|
||||
|
||||
/// Makes the engine run `launch` as the project's language server
|
||||
/// instead of Phpactor from the toolchain; `None` goes back to the
|
||||
/// toolchain. For tests (the fake server) and hosts with their own
|
||||
/// server. See [`crate::lsp`].
|
||||
pub fn set_language_server(&mut self, launch: Option<crate::lsp::Launch>) {
|
||||
self.state.lsp.set_launch(launch);
|
||||
}
|
||||
|
||||
/// Read access to the state.
|
||||
pub fn state(&self) -> &State {
|
||||
&self.state
|
||||
|
|
@ -392,6 +401,7 @@ mod tests {
|
|||
"buffer.edit",
|
||||
"buffer.get",
|
||||
"buffer.list",
|
||||
"diagnostics.list",
|
||||
"file.open",
|
||||
"file.save",
|
||||
"file.saveAll",
|
||||
|
|
@ -399,6 +409,8 @@ mod tests {
|
|||
"goto.file",
|
||||
"goto.symbol",
|
||||
"index.status",
|
||||
"lsp.restart",
|
||||
"lsp.status",
|
||||
"project.children",
|
||||
"project.close",
|
||||
"project.open",
|
||||
|
|
|
|||
|
|
@ -197,6 +197,12 @@ pub enum Event {
|
|||
/// PHP or Phpactor changed: `{php, phpactor}` as `toolchain.status`
|
||||
/// returns it.
|
||||
ToolchainChanged(crate::cmd::toolchain::ToolchainStatus),
|
||||
/// The language server's state changed: `{state, message?}` with state
|
||||
/// `starting`, `ready`, `restarting`, `failed` or `stopped`.
|
||||
LspStatus(crate::lsp::LspStatus),
|
||||
/// The diagnostics of one file changed: `{path, items}`; empty items
|
||||
/// mean the file has none any more. Fetch all with `diagnostics.list`.
|
||||
DiagnosticsChanged(crate::lsp::FileDiagnostics),
|
||||
/// Terminal events (`terminalOutput`, `terminalExited`), see [`crate::cmd::terminal`].
|
||||
#[serde(untagged)]
|
||||
Terminal(crate::cmd::terminal::TerminalEvent),
|
||||
|
|
@ -382,4 +388,40 @@ mod tests {
|
|||
json!({"kind": "outlineChanged", "id": 4})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lsp_shapes() {
|
||||
use crate::lsp::{
|
||||
DiagnosticItem, DiagnosticSeverity, FileDiagnostics, LineRange, LspState, LspStatus,
|
||||
};
|
||||
let e = Event::LspStatus(LspStatus {
|
||||
state: LspState::Restarting,
|
||||
message: Some("exit code 7".into()),
|
||||
});
|
||||
assert_eq!(
|
||||
serde_json::to_value(e).unwrap(),
|
||||
json!({"kind": "lspStatus", "state": "restarting", "message": "exit code 7"})
|
||||
);
|
||||
let range = LineRange {
|
||||
start: lutra_text::Position::new(1, 2).into(),
|
||||
end: lutra_text::Position::new(1, 5).into(),
|
||||
};
|
||||
let e = Event::DiagnosticsChanged(FileDiagnostics {
|
||||
path: "src/a.php".into(),
|
||||
items: vec![DiagnosticItem {
|
||||
range,
|
||||
severity: DiagnosticSeverity::Info,
|
||||
message: "unused".into(),
|
||||
source: None,
|
||||
code: Some("X1".into()),
|
||||
}],
|
||||
});
|
||||
assert_eq!(
|
||||
serde_json::to_value(e).unwrap(),
|
||||
json!({"kind": "diagnosticsChanged", "path": "src/a.php", "items": [{
|
||||
"range": {"start": {"line": 1, "column": 2}, "end": {"line": 1, "column": 5}},
|
||||
"severity": "info", "message": "unused", "code": "X1"
|
||||
}]})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ mod error;
|
|||
mod event;
|
||||
pub mod guard;
|
||||
pub mod journal;
|
||||
pub mod lsp;
|
||||
mod registry;
|
||||
pub mod settings;
|
||||
mod state;
|
||||
|
|
|
|||
868
crates/engine/src/lsp/mod.rs
Normal file
868
crates/engine/src/lsp/mod.rs
Normal file
|
|
@ -0,0 +1,868 @@
|
|||
//! Engine ↔ language server wiring (M3.3): one Phpactor per open project,
|
||||
//! document sync of PHP buffers, `lspStatus` and diagnostics.
|
||||
//!
|
||||
//! Lifecycle, all decided in [`pump`] (called by
|
||||
//! [`crate::Engine::pump_vfs`]):
|
||||
//! - A session starts when a project is open and the toolchain reports a
|
||||
//! usable PHP and a ready Phpactor (`toolchain.status`), or at once when
|
||||
//! the host set its own server ([`Lsp::set_launch`], tests and the fake
|
||||
//! server). The server runs `php <phar> language-server` in the project
|
||||
//! root.
|
||||
//! - It stops when the project closes, when the PHP or Phpactor path
|
||||
//! changes (a new session starts with the new ones), on `lsp.restart`,
|
||||
//! and when the engine is dropped. The stop happens on the session thread
|
||||
//! ([`session`]), never under the engine lock.
|
||||
//!
|
||||
//! Document sync: [`record_edits`] (called by `buffer.edit`) queues the
|
||||
//! edit batch as a `didChange`; the pump opens newly opened PHP buffers,
|
||||
//! closes closed ones, sends `didSave` when a buffer's saved version moves
|
||||
//! and resends the whole text when the version moved without a recorded
|
||||
//! edit (a reload from disk, a restore) or a `didChange` no longer fit.
|
||||
//! Under the lock that is a cheap rope clone and a channel send; the text
|
||||
//! is built on the session thread.
|
||||
//!
|
||||
//! The pump drains the server's events: status changes become `lspStatus`
|
||||
//! (`starting`, `ready`, `restarting`, `failed`, `stopped`), published
|
||||
//! diagnostics of project files become `diagnosticsChanged` and are kept
|
||||
//! for `diagnostics.list`. Diagnostics are dropped when the session ends or
|
||||
//! the server gives up, so stale ones never stay on screen.
|
||||
//!
|
||||
//! Requests (completion, hover, definition, … in M3.4/M3.5) go through
|
||||
//! [`submit`], on the same queue as document sync, so they never overtake
|
||||
//! an edit.
|
||||
|
||||
pub mod session;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::mpsc::Receiver;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use lutra_lsp::{PublishDiagnostics, Server, ServerEvent, Severity, Status};
|
||||
use lutra_text::{Edit, Position};
|
||||
use serde::Serialize;
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
pub use lutra_lsp::{RestartPolicy, ServerOptions};
|
||||
pub use session::Launch;
|
||||
use session::{Job, Report, Session};
|
||||
|
||||
use crate::buffers::BufferId;
|
||||
use crate::cmd::toolchain::PhpactorState;
|
||||
use crate::workspace::path_string;
|
||||
use crate::{Event, NotificationLevel, State};
|
||||
|
||||
/// Most server events handled per pump; the rest wait for the next one,
|
||||
/// so a chatty server cannot hold the engine lock.
|
||||
pub const MAX_EVENTS_PER_PUMP: usize = 2_000;
|
||||
|
||||
/// Most files with diagnostics kept; publications for further files are
|
||||
/// ignored until others clear.
|
||||
pub const MAX_FILES: usize = 10_000;
|
||||
|
||||
/// The state of the language server as `lspStatus` and `lsp.status`
|
||||
/// report it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum LspState {
|
||||
/// The process runs and `initialize` is in flight.
|
||||
Starting,
|
||||
/// Initialized; diagnostics and requests work.
|
||||
Ready,
|
||||
/// The server crashed and is restarted after a delay.
|
||||
Restarting,
|
||||
/// The server could not be started or crashed too often.
|
||||
Failed,
|
||||
/// No server runs (no project, toolchain not ready, or shut down).
|
||||
Stopped,
|
||||
}
|
||||
|
||||
/// The payload of `lspStatus`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
pub struct LspStatus {
|
||||
/// The state.
|
||||
pub state: LspState,
|
||||
/// Why it is restarting or failed.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub message: Option<String>,
|
||||
}
|
||||
|
||||
impl LspStatus {
|
||||
/// No server.
|
||||
fn stopped() -> Self {
|
||||
Self {
|
||||
state: LspState::Stopped,
|
||||
message: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How severe a diagnostic is, as the UI shows it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum DiagnosticSeverity {
|
||||
/// An error (also when the server gave no severity).
|
||||
Error,
|
||||
/// A warning.
|
||||
Warning,
|
||||
/// Information.
|
||||
Info,
|
||||
/// A hint.
|
||||
Hint,
|
||||
}
|
||||
|
||||
impl From<Option<Severity>> for DiagnosticSeverity {
|
||||
fn from(severity: Option<Severity>) -> Self {
|
||||
match severity {
|
||||
Some(Severity::Warning) => Self::Warning,
|
||||
Some(Severity::Information) => Self::Info,
|
||||
Some(Severity::Hint) => Self::Hint,
|
||||
Some(Severity::Error) | None => Self::Error,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A position with a UTF-16 column, as everywhere in Lutra's protocol.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
pub struct LinePosition {
|
||||
/// 0-based line.
|
||||
pub line: usize,
|
||||
/// 0-based column in UTF-16 code units.
|
||||
pub column: usize,
|
||||
}
|
||||
|
||||
impl From<Position> for LinePosition {
|
||||
fn from(p: Position) -> Self {
|
||||
Self {
|
||||
line: p.line,
|
||||
column: p.column,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A range between two positions, end exclusive.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
pub struct LineRange {
|
||||
/// Start.
|
||||
pub start: LinePosition,
|
||||
/// End.
|
||||
pub end: LinePosition,
|
||||
}
|
||||
|
||||
/// One diagnostic of a file.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
pub struct DiagnosticItem {
|
||||
/// Where it applies.
|
||||
pub range: LineRange,
|
||||
/// How severe it is.
|
||||
pub severity: DiagnosticSeverity,
|
||||
/// The message (at most 8 KiB).
|
||||
pub message: String,
|
||||
/// Who produced it (`phpactor`, `php-lint`, …).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub source: Option<String>,
|
||||
/// The diagnostic code.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub code: Option<String>,
|
||||
}
|
||||
|
||||
/// The payload of `diagnosticsChanged`, and one file of
|
||||
/// `diagnostics.list`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
pub struct FileDiagnostics {
|
||||
/// Project-relative path with `/`.
|
||||
pub path: String,
|
||||
/// The diagnostics, in the server's order; empty when they cleared.
|
||||
pub items: Vec<DiagnosticItem>,
|
||||
}
|
||||
|
||||
/// The language server part of the engine state.
|
||||
#[derive(Default)]
|
||||
pub struct Lsp {
|
||||
/// A server the host chose instead of Phpactor from the toolchain.
|
||||
launch: Option<Launch>,
|
||||
/// The running session.
|
||||
active: Option<Active>,
|
||||
/// Status as last reported.
|
||||
status: Option<LspStatus>,
|
||||
/// Diagnostics by project-relative path; files without any are absent.
|
||||
diagnostics: BTreeMap<String, Vec<DiagnosticItem>>,
|
||||
/// Set by [`shutdown_now`] (`app.quit`): no session starts any more.
|
||||
quitting: bool,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Lsp {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Lsp")
|
||||
.field("launch", &self.launch)
|
||||
.field("running", &self.active.is_some())
|
||||
.field("status", &self.status)
|
||||
.field("files_with_diagnostics", &self.diagnostics.len())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Lsp {
|
||||
/// Makes sessions start `launch` instead of Phpactor from the toolchain
|
||||
/// (`None` goes back to the toolchain). A running session is replaced
|
||||
/// at the next pump.
|
||||
pub fn set_launch(&mut self, launch: Option<Launch>) {
|
||||
self.launch = launch;
|
||||
}
|
||||
|
||||
/// The status as last reported; stopped without a session.
|
||||
pub fn status(&self) -> LspStatus {
|
||||
self.status.clone().unwrap_or_else(LspStatus::stopped)
|
||||
}
|
||||
|
||||
/// Milliseconds from the start of the session to the server's first
|
||||
/// `ready`, once it was reached.
|
||||
pub fn startup_ms(&self) -> Option<u64> {
|
||||
self.active.as_ref().and_then(|a| a.ready_ms)
|
||||
}
|
||||
|
||||
/// The diagnostics of one file (project-relative, `/`), or of every
|
||||
/// file, sorted by path.
|
||||
pub fn diagnostics(&self, path: Option<&str>) -> Vec<FileDiagnostics> {
|
||||
self.diagnostics
|
||||
.iter()
|
||||
.filter(|(p, _)| path.is_none_or(|want| want == p.as_str()))
|
||||
.map(|(p, items)| FileDiagnostics {
|
||||
path: p.clone(),
|
||||
items: items.clone(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The server of the running session, once its process started. For
|
||||
/// reading its status and capabilities; send requests with [`submit`].
|
||||
pub fn server(&self) -> Option<&Arc<Server>> {
|
||||
self.active.as_ref().and_then(|a| a.server.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
/// What a session was started for; a change replaces the session.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
struct Key {
|
||||
/// The project root.
|
||||
root: PathBuf,
|
||||
/// The server command line and options.
|
||||
launch: Launch,
|
||||
}
|
||||
|
||||
/// A PHP buffer as the server knows it.
|
||||
#[derive(Debug, Clone)]
|
||||
struct Doc {
|
||||
/// Absolute path.
|
||||
path: PathBuf,
|
||||
/// The buffer version the server has (after the queued jobs).
|
||||
version: u64,
|
||||
/// The buffer's saved version last seen.
|
||||
saved_version: u64,
|
||||
/// The whole text must be resent.
|
||||
stale: bool,
|
||||
}
|
||||
|
||||
/// The running session and what the engine knows about it.
|
||||
struct Active {
|
||||
/// Why it runs.
|
||||
key: Key,
|
||||
/// The session thread.
|
||||
session: Session,
|
||||
/// The server, once started.
|
||||
server: Option<Arc<Server>>,
|
||||
/// Its events, once started.
|
||||
events: Option<Receiver<ServerEvent>>,
|
||||
/// When the session started.
|
||||
started: Instant,
|
||||
/// Milliseconds to the first `ready`.
|
||||
ready_ms: Option<u64>,
|
||||
/// Synced buffers.
|
||||
docs: BTreeMap<BufferId, Doc>,
|
||||
}
|
||||
|
||||
/// Queues `f` on the session thread, after every document change queued
|
||||
/// so far. It runs with the server and must not block (use
|
||||
/// [`Server::request_with`] or keep the [`lutra_lsp::RequestHandle`] and
|
||||
/// poll it from the pump); without a running session it is dropped
|
||||
/// unrun, which a caller notices through a dropped channel sender it
|
||||
/// captured.
|
||||
///
|
||||
/// # Returns
|
||||
/// Whether it was queued.
|
||||
pub fn submit(state: &mut State, f: impl FnOnce(&Server) + Send + 'static) -> bool {
|
||||
state
|
||||
.lsp
|
||||
.active
|
||||
.as_ref()
|
||||
.is_some_and(|a| a.session.send(Job::Run(Box::new(f))))
|
||||
}
|
||||
|
||||
/// Records an edit batch `buffer.edit` applied to buffer `id` (moving it
|
||||
/// from version `base` to `base + 1`) and queues it as a `didChange`. A
|
||||
/// buffer the server does not have yet, or whose synced version is not
|
||||
/// `base`, is resent whole by the next pump instead.
|
||||
pub fn record_edits(state: &mut State, id: BufferId, base: u64, edits: &[Edit]) {
|
||||
let Some(active) = state.lsp.active.as_mut() else {
|
||||
return;
|
||||
};
|
||||
let Some(doc) = active.docs.get_mut(&id) else {
|
||||
return;
|
||||
};
|
||||
if doc.stale || doc.version != base {
|
||||
doc.stale = true;
|
||||
return;
|
||||
}
|
||||
let job = Job::Change {
|
||||
path: doc.path.clone(),
|
||||
edits: edits.to_vec(),
|
||||
};
|
||||
if active.session.send(job) {
|
||||
doc.version = base.saturating_add(1);
|
||||
} else {
|
||||
doc.stale = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts, replaces or stops the session, applies the session thread's
|
||||
/// reports and the server's events, and syncs open PHP buffers. See the
|
||||
/// module docs. Never blocks.
|
||||
pub fn pump(state: &mut State) {
|
||||
let wanted = wanted(state);
|
||||
let current = state.lsp.active.as_ref().map(|a| a.key.clone());
|
||||
if current != wanted {
|
||||
if current.is_some() {
|
||||
stop(state);
|
||||
}
|
||||
if let Some(key) = wanted {
|
||||
start(state, key);
|
||||
}
|
||||
}
|
||||
if state.lsp.active.is_none() {
|
||||
return;
|
||||
}
|
||||
drain_reports(state);
|
||||
drain_events(state);
|
||||
sync_docs(state);
|
||||
}
|
||||
|
||||
/// Stops the running session at the next pump and lets the pump start a
|
||||
/// fresh one if the project and toolchain still allow it.
|
||||
pub fn restart(state: &mut State) {
|
||||
if state.lsp.active.is_some() {
|
||||
stop(state);
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops the language server now and waits for it (at most about 3 s), for
|
||||
/// `app.quit`: the host exits right after, which would cut a background
|
||||
/// shutdown short and leave the Phpactor process running. Clears the
|
||||
/// diagnostics and reports `stopped`.
|
||||
pub fn shutdown_now(state: &mut State) {
|
||||
state.lsp.quitting = true;
|
||||
let Some(active) = state.lsp.active.take() else {
|
||||
return;
|
||||
};
|
||||
let Active {
|
||||
session,
|
||||
server,
|
||||
events,
|
||||
..
|
||||
} = active;
|
||||
drop(server);
|
||||
drop(events);
|
||||
session.join();
|
||||
clear_diagnostics(state);
|
||||
set_status(state, LspState::Stopped, None);
|
||||
}
|
||||
|
||||
/// The session the state calls for: none without a project; the host's
|
||||
/// server if it set one; otherwise Phpactor once the toolchain found PHP
|
||||
/// and has the PHAR ready.
|
||||
fn wanted(state: &State) -> Option<Key> {
|
||||
if state.lsp.quitting {
|
||||
return None;
|
||||
}
|
||||
let root = state.project.as_ref()?.project.root().to_path_buf();
|
||||
if let Some(launch) = &state.lsp.launch {
|
||||
return Some(Key {
|
||||
root,
|
||||
launch: launch.clone(),
|
||||
});
|
||||
}
|
||||
let status = state.toolchain.status();
|
||||
if !status.php.found || status.phpactor.state != PhpactorState::Ready {
|
||||
return None;
|
||||
}
|
||||
let php = status.php.path.as_ref()?;
|
||||
let phar = status.phpactor.path.as_ref()?;
|
||||
Some(Key {
|
||||
root,
|
||||
launch: phpactor_launch(php, phar, cfg!(windows)),
|
||||
})
|
||||
}
|
||||
|
||||
/// How Lutra starts Phpactor: `php <phar> language-server`.
|
||||
///
|
||||
/// On Windows, Phpactor 2026.06.25.0 needs two adjustments (found in the
|
||||
/// M3.3 live check, see `docs/architecture.md` › Engine wiring):
|
||||
/// - Every subprocess it starts through amphp fails there with
|
||||
/// `CreateProcess failed` (outsourced diagnostics, the PHP lint provider,
|
||||
/// the `find` file watcher of the indexer). The `initializationOptions`
|
||||
/// run diagnostics in the server process
|
||||
/// (`language_server.diagnostic_outsource: false`) and let the indexer
|
||||
/// poll in PHP (`indexer.enabled_watchers: ["php"]`). The PHP lint
|
||||
/// provider still fails once and removes itself; its warning arrives as
|
||||
/// `window/showMessage`, which Lutra does not show.
|
||||
/// - Its event loop only runs when a message arrives on stdin, so timers
|
||||
/// (the diagnostics debounce, the watcher) stall while the client is
|
||||
/// quiet. The session thread sends [`TICK_METHOD`] every 25 ms while
|
||||
/// busy; Phpactor's analysis advances one step per message, so the
|
||||
/// interval sets the latency (edit to diagnostics with its 1 s debounce:
|
||||
/// 5.9 s at 200 ms, 2.5 s at 50 ms, 1.5 s at 20 ms, measured). For the
|
||||
/// same reason it rarely answers `shutdown` in time, so the shutdown
|
||||
/// timeout is 500 ms instead of 2 s before the process is killed (quit
|
||||
/// took 3 s otherwise).
|
||||
///
|
||||
/// Nothing is written into the user's project.
|
||||
///
|
||||
/// # Parameters
|
||||
/// - `php`, `phar`: the executables from `toolchain.status`.
|
||||
/// - `windows`: whether to apply the Windows adjustments.
|
||||
pub fn phpactor_launch(php: &str, phar: &str, windows: bool) -> Launch {
|
||||
let options = ServerOptions {
|
||||
initialization_options: windows.then(|| {
|
||||
serde_json::json!({
|
||||
"language_server.diagnostic_outsource": false,
|
||||
"indexer.enabled_watchers": ["php"],
|
||||
})
|
||||
}),
|
||||
shutdown_timeout: if windows {
|
||||
Duration::from_millis(500)
|
||||
} else {
|
||||
ServerOptions::default().shutdown_timeout
|
||||
},
|
||||
..ServerOptions::default()
|
||||
};
|
||||
Launch {
|
||||
command: OsString::from(php),
|
||||
args: vec![OsString::from(phar), OsString::from("language-server")],
|
||||
options,
|
||||
tick: windows.then_some(TICK_INTERVAL),
|
||||
}
|
||||
}
|
||||
|
||||
/// The no-op notification that keeps a server's event loop turning
|
||||
/// ([`Launch::tick`]). Servers ignore `$/` notifications they do not know.
|
||||
pub const TICK_METHOD: &str = "$/lutra/tick";
|
||||
|
||||
/// How often a busy session sends [`TICK_METHOD`] to Phpactor on Windows
|
||||
/// (from its own thread, independent of the host's pump).
|
||||
pub const TICK_INTERVAL: Duration = Duration::from_millis(25);
|
||||
|
||||
/// How long a session counts as busy after its last document change,
|
||||
/// open, save or submitted request. Long enough for Phpactor's first
|
||||
/// analysis of a project on a cold cache (16 s measured in M3.3).
|
||||
pub const TICK_WINDOW: Duration = Duration::from_secs(60);
|
||||
|
||||
/// Whether a session with tick interval `interval` sends a tick at `now`.
|
||||
///
|
||||
/// # Parameters
|
||||
/// - `ready`: whether the server is ready.
|
||||
/// - `last_activity`: the last change, open, save or request, if any.
|
||||
/// - `last_tick`: when the last tick was sent, if any.
|
||||
pub fn tick_due(
|
||||
interval: Option<Duration>,
|
||||
ready: bool,
|
||||
last_activity: Option<Instant>,
|
||||
last_tick: Option<Instant>,
|
||||
now: Instant,
|
||||
) -> bool {
|
||||
let Some(interval) = interval else {
|
||||
return false;
|
||||
};
|
||||
let busy = last_activity.is_some_and(|t| now.saturating_duration_since(t) <= TICK_WINDOW);
|
||||
let due = last_tick.is_none_or(|t| now.saturating_duration_since(t) >= interval);
|
||||
ready && busy && due
|
||||
}
|
||||
|
||||
/// Starts a session for `key` and reports `starting`, or `failed` if the
|
||||
/// thread cannot be started.
|
||||
fn start(state: &mut State, key: Key) {
|
||||
match Session::start(key.launch.clone(), key.root.clone()) {
|
||||
Ok(session) => {
|
||||
state.lsp.active = Some(Active {
|
||||
key,
|
||||
session,
|
||||
server: None,
|
||||
events: None,
|
||||
started: Instant::now(),
|
||||
ready_ms: None,
|
||||
docs: BTreeMap::new(),
|
||||
});
|
||||
set_status(state, LspState::Starting, None);
|
||||
}
|
||||
Err(message) => fail(state, message),
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops the session (its thread shuts the server down), clears the
|
||||
/// diagnostics and reports `stopped`.
|
||||
fn stop(state: &mut State) {
|
||||
state.lsp.active = None;
|
||||
clear_diagnostics(state);
|
||||
set_status(state, LspState::Stopped, None);
|
||||
}
|
||||
|
||||
/// Reports `failed` with `message`, clears the diagnostics and tells the
|
||||
/// user once.
|
||||
fn fail(state: &mut State, message: String) {
|
||||
clear_diagnostics(state);
|
||||
let changed = set_status(state, LspState::Failed, Some(message.clone()));
|
||||
if changed {
|
||||
let mut params = Map::new();
|
||||
params.insert("reason".into(), Value::from(message.clone()));
|
||||
state.notify(
|
||||
NotificationLevel::Error,
|
||||
Some("notification.lsp.failed"),
|
||||
Some(format!(
|
||||
"The PHP language server stopped: {message}. Run \"Restart Language Server\" to try again."
|
||||
)),
|
||||
Some(params),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Stores the status and queues `lspStatus` if it changed.
|
||||
///
|
||||
/// # Returns
|
||||
/// Whether it changed.
|
||||
fn set_status(state: &mut State, lsp_state: LspState, message: Option<String>) -> bool {
|
||||
let status = LspStatus {
|
||||
state: lsp_state,
|
||||
message,
|
||||
};
|
||||
if state.lsp.status.as_ref() == Some(&status) {
|
||||
return false;
|
||||
}
|
||||
state.lsp.status = Some(status.clone());
|
||||
state.emit(Event::LspStatus(status));
|
||||
true
|
||||
}
|
||||
|
||||
/// Applies the session thread's reports.
|
||||
fn drain_reports(state: &mut State) {
|
||||
let mut reports = Vec::new();
|
||||
if let Some(active) = &state.lsp.active {
|
||||
while let Ok(report) = active.session.reports.try_recv() {
|
||||
reports.push(report);
|
||||
}
|
||||
}
|
||||
for report in reports {
|
||||
match report {
|
||||
Report::Started { server, events } => {
|
||||
if let Some(active) = state.lsp.active.as_mut() {
|
||||
active.server = Some(server);
|
||||
active.events = Some(events);
|
||||
}
|
||||
}
|
||||
Report::SpawnFailed(message) => fail(state, message),
|
||||
Report::Desync(path) => {
|
||||
if let Some(active) = state.lsp.active.as_mut() {
|
||||
for doc in active.docs.values_mut().filter(|d| d.path == path) {
|
||||
doc.stale = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles up to [`MAX_EVENTS_PER_PUMP`] server events.
|
||||
fn drain_events(state: &mut State) {
|
||||
let mut events = Vec::new();
|
||||
if let Some(receiver) = state.lsp.active.as_ref().and_then(|a| a.events.as_ref()) {
|
||||
while events.len() < MAX_EVENTS_PER_PUMP {
|
||||
let Ok(event) = receiver.try_recv() else {
|
||||
break;
|
||||
};
|
||||
events.push(event);
|
||||
}
|
||||
}
|
||||
for event in events {
|
||||
match event {
|
||||
ServerEvent::Status(status) => apply_status(state, status),
|
||||
ServerEvent::Diagnostics(published) => publish(state, published),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps a client status onto `lspStatus`.
|
||||
fn apply_status(state: &mut State, status: Status) {
|
||||
match status {
|
||||
Status::Starting => {
|
||||
set_status(state, LspState::Starting, None);
|
||||
}
|
||||
Status::Ready => {
|
||||
if let Some(active) = state.lsp.active.as_mut()
|
||||
&& active.ready_ms.is_none()
|
||||
{
|
||||
active.ready_ms =
|
||||
Some(u64::try_from(active.started.elapsed().as_millis()).unwrap_or(u64::MAX));
|
||||
}
|
||||
set_status(state, LspState::Ready, None);
|
||||
}
|
||||
Status::Restarting { reason, .. } => {
|
||||
set_status(state, LspState::Restarting, Some(reason));
|
||||
}
|
||||
Status::Failed { message } => fail(state, message),
|
||||
Status::Stopped => {
|
||||
clear_diagnostics(state);
|
||||
set_status(state, LspState::Stopped, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stores the diagnostics of one file and queues `diagnosticsChanged`.
|
||||
/// Files outside the project are ignored.
|
||||
fn publish(state: &mut State, published: PublishDiagnostics) {
|
||||
let Some(root) = state.lsp.active.as_ref().map(|a| a.key.root.clone()) else {
|
||||
return;
|
||||
};
|
||||
let Some(relative) = published.path.as_deref().and_then(|p| relative(&root, p)) else {
|
||||
return;
|
||||
};
|
||||
let path = path_string(&relative);
|
||||
let items: Vec<DiagnosticItem> = published
|
||||
.diagnostics
|
||||
.into_iter()
|
||||
.map(|d| DiagnosticItem {
|
||||
range: LineRange {
|
||||
start: d.range.start.into(),
|
||||
end: d.range.end.into(),
|
||||
},
|
||||
severity: d.severity.into(),
|
||||
message: d.message,
|
||||
source: d.source,
|
||||
code: d.code,
|
||||
})
|
||||
.collect();
|
||||
let diagnostics = &mut state.lsp.diagnostics;
|
||||
if items.is_empty() {
|
||||
if diagnostics.remove(&path).is_none() {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
if diagnostics.get(&path) == Some(&items) {
|
||||
return;
|
||||
}
|
||||
if !diagnostics.contains_key(&path) && diagnostics.len() >= MAX_FILES {
|
||||
return;
|
||||
}
|
||||
diagnostics.insert(path.clone(), items.clone());
|
||||
}
|
||||
state.emit(Event::DiagnosticsChanged(FileDiagnostics { path, items }));
|
||||
}
|
||||
|
||||
/// Drops every diagnostic, queuing an empty `diagnosticsChanged` per file
|
||||
/// that had some.
|
||||
fn clear_diagnostics(state: &mut State) {
|
||||
let files = std::mem::take(&mut state.lsp.diagnostics);
|
||||
for path in files.into_keys() {
|
||||
state.emit(Event::DiagnosticsChanged(FileDiagnostics {
|
||||
path,
|
||||
items: Vec::new(),
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
/// `path` relative to `root`; `None` outside it. Windows paths compare
|
||||
/// without regard to case, as the file system does.
|
||||
fn relative(root: &Path, path: &Path) -> Option<PathBuf> {
|
||||
if let Ok(rel) = path.strip_prefix(root) {
|
||||
return Some(rel.to_path_buf());
|
||||
}
|
||||
if !cfg!(windows) {
|
||||
return None;
|
||||
}
|
||||
let root_text = root.to_str()?.trim_end_matches(['\\', '/']);
|
||||
let text = path.to_str()?;
|
||||
let head = text.get(..root_text.len())?;
|
||||
let rest = text.get(root_text.len()..)?;
|
||||
if !head.eq_ignore_ascii_case(root_text) || !rest.starts_with(['\\', '/']) {
|
||||
return None;
|
||||
}
|
||||
Some(PathBuf::from(rest.trim_start_matches(['\\', '/'])))
|
||||
}
|
||||
|
||||
/// Whether a project-relative path is synced as PHP.
|
||||
fn is_php(path: &Path) -> bool {
|
||||
path.extension().and_then(|e| e.to_str()).is_some_and(|e| {
|
||||
["php", "phtml", "inc"]
|
||||
.iter()
|
||||
.any(|x| e.eq_ignore_ascii_case(x))
|
||||
})
|
||||
}
|
||||
|
||||
/// Opens new PHP buffers, closes closed ones, resends stale texts and
|
||||
/// reports saves.
|
||||
fn sync_docs(state: &mut State) {
|
||||
let State { buffers, lsp, .. } = state;
|
||||
let Some(active) = lsp.active.as_mut() else {
|
||||
return;
|
||||
};
|
||||
let gone: Vec<BufferId> = active
|
||||
.docs
|
||||
.keys()
|
||||
.copied()
|
||||
.filter(|id| !buffers.get(*id).is_some_and(|b| is_php(&b.path)))
|
||||
.collect();
|
||||
for id in gone {
|
||||
if let Some(doc) = active.docs.remove(&id) {
|
||||
active.session.send(Job::Close { path: doc.path });
|
||||
}
|
||||
}
|
||||
for id in buffers.ids() {
|
||||
let Some(open) = buffers.get(id) else {
|
||||
continue;
|
||||
};
|
||||
if !is_php(&open.path) {
|
||||
continue;
|
||||
}
|
||||
let path = active.key.root.join(&open.path);
|
||||
let Some(doc) = active.docs.get_mut(&id) else {
|
||||
active.session.send(Job::Open {
|
||||
path: path.clone(),
|
||||
text: open.buffer.clone(),
|
||||
});
|
||||
active.docs.insert(
|
||||
id,
|
||||
Doc {
|
||||
path,
|
||||
version: open.version,
|
||||
saved_version: open.saved_version,
|
||||
stale: false,
|
||||
},
|
||||
);
|
||||
continue;
|
||||
};
|
||||
if doc.path != path {
|
||||
active.session.send(Job::Close {
|
||||
path: std::mem::replace(&mut doc.path, path.clone()),
|
||||
});
|
||||
active.session.send(Job::Open {
|
||||
path,
|
||||
text: open.buffer.clone(),
|
||||
});
|
||||
doc.version = open.version;
|
||||
doc.stale = false;
|
||||
} else if doc.stale || doc.version != open.version {
|
||||
active.session.send(Job::Full {
|
||||
path: doc.path.clone(),
|
||||
text: open.buffer.clone(),
|
||||
});
|
||||
doc.version = open.version;
|
||||
doc.stale = false;
|
||||
}
|
||||
if doc.saved_version != open.saved_version {
|
||||
doc.saved_version = open.saved_version;
|
||||
if !open.dirty() {
|
||||
active.session.send(Job::Save {
|
||||
path: doc.path.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use super::{
|
||||
DiagnosticSeverity, TICK_INTERVAL, TICK_WINDOW, phpactor_launch, relative, tick_due,
|
||||
};
|
||||
use lutra_lsp::Severity;
|
||||
|
||||
#[test]
|
||||
fn severity_defaults_to_error() {
|
||||
assert_eq!(DiagnosticSeverity::from(None), DiagnosticSeverity::Error);
|
||||
assert_eq!(
|
||||
DiagnosticSeverity::from(Some(Severity::Information)),
|
||||
DiagnosticSeverity::Info
|
||||
);
|
||||
assert_eq!(
|
||||
DiagnosticSeverity::from(Some(Severity::Hint)),
|
||||
DiagnosticSeverity::Hint
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_paths_stay_inside_the_root() {
|
||||
let root = if cfg!(windows) {
|
||||
PathBuf::from(r"C:\work\demo")
|
||||
} else {
|
||||
PathBuf::from("/work/demo")
|
||||
};
|
||||
let inside = root.join("src").join("a.php");
|
||||
assert_eq!(
|
||||
relative(&root, &inside),
|
||||
Some(Path::new("src").join("a.php"))
|
||||
);
|
||||
let sibling = if cfg!(windows) {
|
||||
PathBuf::from(r"C:\work\demo2\a.php")
|
||||
} else {
|
||||
PathBuf::from("/work/demo2/a.php")
|
||||
};
|
||||
assert_eq!(relative(&root, &sibling), None);
|
||||
if cfg!(windows) {
|
||||
assert_eq!(
|
||||
relative(&root, Path::new(r"c:\WORK\demo\b.php")),
|
||||
Some(PathBuf::from("b.php"))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn phpactor_gets_the_windows_adjustments_only_there() {
|
||||
let windows = phpactor_launch("php.exe", r"C: \phpactor.phar", true);
|
||||
assert_eq!(windows.tick, Some(TICK_INTERVAL));
|
||||
let options = windows.options.initialization_options.unwrap();
|
||||
assert_eq!(options["language_server.diagnostic_outsource"], false);
|
||||
assert_eq!(
|
||||
options["indexer.enabled_watchers"],
|
||||
serde_json::json!(["php"])
|
||||
);
|
||||
assert_eq!(windows.args.len(), 2);
|
||||
let unix = phpactor_launch("php", "/t/phpactor.phar", false);
|
||||
assert_eq!(unix.tick, None);
|
||||
assert_eq!(unix.options.initialization_options, None);
|
||||
assert_eq!(windows.options.shutdown_timeout, Duration::from_millis(500));
|
||||
assert_eq!(unix.options.shutdown_timeout, Duration::from_secs(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ticks_only_while_ready_and_busy() {
|
||||
let now = Instant::now() + Duration::from_secs(3600);
|
||||
let tick = Some(TICK_INTERVAL);
|
||||
let recent = Some(now - Duration::from_secs(1));
|
||||
assert!(tick_due(tick, true, recent, None, now));
|
||||
assert!(!tick_due(None, true, recent, None, now));
|
||||
assert!(!tick_due(tick, false, recent, None, now));
|
||||
let quiet = Some(now - TICK_WINDOW - Duration::from_secs(1));
|
||||
assert!(!tick_due(tick, true, quiet, None, now));
|
||||
assert!(!tick_due(
|
||||
tick,
|
||||
true,
|
||||
recent,
|
||||
Some(now - TICK_INTERVAL / 2),
|
||||
now
|
||||
));
|
||||
assert!(tick_due(tick, true, recent, Some(now - TICK_INTERVAL), now));
|
||||
}
|
||||
}
|
||||
247
crates/engine/src/lsp/session.rs
Normal file
247
crates/engine/src/lsp/session.rs
Normal file
|
|
@ -0,0 +1,247 @@
|
|||
//! One language server session: the thread that owns the
|
||||
//! [`lutra_lsp::Server`] of the open project.
|
||||
//!
|
||||
//! The engine lock only ever enqueues [`Job`]s. The session thread starts
|
||||
//! the server (spawning a process can take tens of milliseconds on Windows
|
||||
//! with a virus scanner), turns buffer snapshots into text, sends document
|
||||
//! sync and runs the closures of [`super::submit`], strictly in the order
|
||||
//! they were queued. A request queued after an edit therefore reaches the
|
||||
//! server after that edit's `didChange`. What the thread learns goes back
|
||||
//! to the next pump as a [`Report`].
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use lutra_lsp::{LspError, Server, ServerEvent, ServerOptions, Status};
|
||||
use lutra_text::{Buffer, Edit};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
/// How a session starts its server.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Launch {
|
||||
/// The executable (PHP for Phpactor).
|
||||
pub command: OsString,
|
||||
/// Its arguments (the PHAR and `language-server` for Phpactor).
|
||||
pub args: Vec<OsString>,
|
||||
/// Client options (timeouts, restart policy, `initializationOptions`).
|
||||
pub options: ServerOptions,
|
||||
/// Send the no-op notification [`super::TICK_METHOD`] at this interval
|
||||
/// while the session is busy (see [`super::TICK_WINDOW`]); `None` for
|
||||
/// servers that need no nudge. Phpactor on Windows needs it, see
|
||||
/// [`super::phpactor_launch`].
|
||||
pub tick: Option<Duration>,
|
||||
}
|
||||
|
||||
/// Work for the session thread, run in queue order.
|
||||
pub enum Job {
|
||||
/// Open a document with the text of a buffer snapshot.
|
||||
Open {
|
||||
/// Absolute path.
|
||||
path: PathBuf,
|
||||
/// The buffer at the version the engine recorded.
|
||||
text: Buffer,
|
||||
},
|
||||
/// Apply the edits `buffer.edit` applied (byte ranges into the previous
|
||||
/// text).
|
||||
Change {
|
||||
/// Absolute path.
|
||||
path: PathBuf,
|
||||
/// The edit batch.
|
||||
edits: Vec<Edit>,
|
||||
},
|
||||
/// Replace the whole text (a reload from disk, a restore, a resync).
|
||||
Full {
|
||||
/// Absolute path.
|
||||
path: PathBuf,
|
||||
/// The buffer snapshot.
|
||||
text: Buffer,
|
||||
},
|
||||
/// The buffer was saved.
|
||||
Save {
|
||||
/// Absolute path.
|
||||
path: PathBuf,
|
||||
},
|
||||
/// The buffer was closed.
|
||||
Close {
|
||||
/// Absolute path.
|
||||
path: PathBuf,
|
||||
},
|
||||
/// A closure from [`super::submit`]: requests of M3.4/M3.5.
|
||||
Run(Box<dyn FnOnce(&Server) + Send>),
|
||||
}
|
||||
|
||||
/// What the session thread reports to the pump.
|
||||
pub enum Report {
|
||||
/// The server process started; its events arrive on `events`.
|
||||
Started {
|
||||
/// The server, shared so the engine can read its status.
|
||||
server: Arc<Server>,
|
||||
/// Its event channel.
|
||||
events: Receiver<ServerEvent>,
|
||||
},
|
||||
/// The server could not be started.
|
||||
SpawnFailed(String),
|
||||
/// A `didChange` did not fit the client's copy of the document; the
|
||||
/// pump resends the whole text.
|
||||
Desync(PathBuf),
|
||||
}
|
||||
|
||||
/// The engine's handle on a running session thread.
|
||||
pub struct Session {
|
||||
/// Jobs to the thread. Dropping it ends the thread, which shuts the
|
||||
/// server down.
|
||||
jobs: Sender<Job>,
|
||||
/// Reports from the thread.
|
||||
pub reports: Receiver<Report>,
|
||||
/// The thread, joined by [`Session::join`].
|
||||
thread: Option<std::thread::JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Starts the session thread, which starts `launch` in `root`.
|
||||
///
|
||||
/// # Errors
|
||||
/// The thread could not be started.
|
||||
pub fn start(launch: Launch, root: PathBuf) -> Result<Self, String> {
|
||||
let (jobs, queue) = mpsc::channel::<Job>();
|
||||
let (reporter, reports) = mpsc::channel::<Report>();
|
||||
let thread = std::thread::Builder::new()
|
||||
.name("lsp-session".into())
|
||||
.spawn(move || run(launch, &root, &queue, &reporter))
|
||||
.map_err(|e| format!("cannot start the language server thread: {e}"))?;
|
||||
Ok(Self {
|
||||
jobs,
|
||||
reports,
|
||||
thread: Some(thread),
|
||||
})
|
||||
}
|
||||
|
||||
/// Queues a job.
|
||||
///
|
||||
/// # Returns
|
||||
/// `false` when the thread is gone.
|
||||
pub fn send(&self, job: Job) -> bool {
|
||||
self.jobs.send(job).is_ok()
|
||||
}
|
||||
|
||||
/// Ends the queue and waits until the thread has shut the server down
|
||||
/// (`shutdown`, `exit`, kill if needed: at most about 3 s). For a host
|
||||
/// that is about to exit, where a background shutdown would be cut
|
||||
/// short and leave the server process running. The caller must have
|
||||
/// dropped its own handles on the server first, or the thread cannot
|
||||
/// take sole ownership and the server is only stopped in the
|
||||
/// background. A thread that panicked is ignored: there is nothing
|
||||
/// left to stop.
|
||||
pub fn join(self) {
|
||||
let Self {
|
||||
jobs,
|
||||
reports,
|
||||
thread,
|
||||
} = self;
|
||||
drop(jobs);
|
||||
drop(reports);
|
||||
if let Some(thread) = thread {
|
||||
let _ = thread.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The session thread: starts the server, works off the queue until the
|
||||
/// engine drops its sender, then shuts the server down (`shutdown`, `exit`,
|
||||
/// kill), here and never under the engine lock. Reports that cannot be
|
||||
/// delivered are dropped because the engine has stopped listening.
|
||||
fn run(launch: Launch, root: &Path, queue: &Receiver<Job>, reporter: &Sender<Report>) {
|
||||
let Launch {
|
||||
command,
|
||||
args,
|
||||
options,
|
||||
tick,
|
||||
} = launch;
|
||||
let server = match Server::spawn(&command, &args, root, options) {
|
||||
Ok((server, events)) => {
|
||||
let server = Arc::new(server);
|
||||
let _ = reporter.send(Report::Started {
|
||||
server: Arc::clone(&server),
|
||||
events,
|
||||
});
|
||||
server
|
||||
}
|
||||
Err(error) => {
|
||||
let _ = reporter.send(Report::SpawnFailed(error.to_string()));
|
||||
while queue.recv().is_ok() {}
|
||||
return;
|
||||
}
|
||||
};
|
||||
work(&server, tick, queue, reporter);
|
||||
match Arc::try_unwrap(server) {
|
||||
Ok(server) => server.shutdown(),
|
||||
Err(shared) => drop(shared),
|
||||
}
|
||||
}
|
||||
|
||||
/// Works off the queue until the engine drops its sender. With a tick
|
||||
/// interval, also sends [`super::TICK_METHOD`] whenever one is due
|
||||
/// ([`super::tick_due`]): the thread wakes at least once per interval, so
|
||||
/// ticks do not depend on how often the host pumps.
|
||||
fn work(server: &Server, tick: Option<Duration>, queue: &Receiver<Job>, reporter: &Sender<Report>) {
|
||||
let mut last_job = Instant::now();
|
||||
let mut last_tick = None;
|
||||
loop {
|
||||
let next = match tick {
|
||||
Some(interval) => queue.recv_timeout(interval),
|
||||
None => queue.recv().map_err(|_| RecvTimeoutError::Disconnected),
|
||||
};
|
||||
match next {
|
||||
Ok(job) => {
|
||||
last_job = Instant::now();
|
||||
handle(server, job, reporter);
|
||||
}
|
||||
Err(RecvTimeoutError::Timeout) => {}
|
||||
Err(RecvTimeoutError::Disconnected) => return,
|
||||
}
|
||||
let now = Instant::now();
|
||||
let ready = server.status() == Status::Ready;
|
||||
if super::tick_due(tick, ready, Some(last_job), last_tick, now) {
|
||||
last_tick = Some(now);
|
||||
server.notify(super::TICK_METHOD, Value::Object(Map::new()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs one job against the server. Sync failures are expected races
|
||||
/// (a buffer closed twice, a document already open after a restart of the
|
||||
/// session) and change nothing, except a `didChange` that no longer fits,
|
||||
/// which asks the pump for a full resync.
|
||||
fn handle(server: &Server, job: Job, reporter: &Sender<Report>) {
|
||||
match job {
|
||||
Job::Open { path, text } => {
|
||||
let text = text.text();
|
||||
if let Err(LspError::AlreadyOpen { .. }) = server.did_open(&path, "php", &text) {
|
||||
let _ = server.did_change_full(&path, &text);
|
||||
}
|
||||
}
|
||||
Job::Change { path, edits } => {
|
||||
if let Err(LspError::Text(_) | LspError::NotOpen { .. }) =
|
||||
server.did_change(&path, &edits)
|
||||
{
|
||||
let _ = reporter.send(Report::Desync(path));
|
||||
}
|
||||
}
|
||||
Job::Full { path, text } => {
|
||||
let text = text.text();
|
||||
if let Err(LspError::NotOpen { .. }) = server.did_change_full(&path, &text) {
|
||||
let _ = server.did_open(&path, "php", &text);
|
||||
}
|
||||
}
|
||||
Job::Save { path } => {
|
||||
let _ = server.did_save(&path);
|
||||
}
|
||||
Job::Close { path } => {
|
||||
let _ = server.did_close(&path);
|
||||
}
|
||||
Job::Run(f) => f(server),
|
||||
}
|
||||
}
|
||||
|
|
@ -45,6 +45,8 @@ pub struct State {
|
|||
pub toolchain: crate::cmd::toolchain::Toolchain,
|
||||
/// Open integrated terminals (`terminal.*`).
|
||||
pub terminals: crate::cmd::terminal::Terminals,
|
||||
/// The language server session and its diagnostics (M3.3).
|
||||
pub lsp: crate::lsp::Lsp,
|
||||
/// Number of notifications emitted, for their ids.
|
||||
notifications: u64,
|
||||
/// Events queued for the host, oldest first.
|
||||
|
|
|
|||
529
crates/engine/tests/lsp.rs
Normal file
529
crates/engine/tests/lsp.rs
Normal file
|
|
@ -0,0 +1,529 @@
|
|||
//! The engine ↔ language server wiring (M3.3) against `lutra-lsp-fake`,
|
||||
//! M3.2's scripted server, which publishes every document's whole text as
|
||||
//! its one diagnostic. That makes the document sync visible: after any
|
||||
//! sequence of `buffer.edit`s the diagnostic must equal the buffer's text.
|
||||
|
||||
#![allow(
|
||||
clippy::unwrap_used,
|
||||
clippy::expect_used,
|
||||
clippy::panic,
|
||||
clippy::indexing_slicing,
|
||||
clippy::string_slice
|
||||
)]
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Mutex, mpsc};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use lutra_engine::lsp::Launch;
|
||||
use lutra_engine::{Command, CommandSpec, Engine, EngineError, Event, Outcome, State};
|
||||
use lutra_lsp::{RestartPolicy, ServerOptions};
|
||||
use proptest::prelude::*;
|
||||
use serde_json::{Value, json};
|
||||
use tempfile::TempDir;
|
||||
|
||||
/// The fake server binary, built on demand when this test runs without
|
||||
/// the rest of the workspace (`cargo test -p lutra-engine`).
|
||||
fn fake_server() -> PathBuf {
|
||||
let exe = format!("lutra-lsp-fake{}", std::env::consts::EXE_SUFFIX);
|
||||
let deps = std::env::current_exe().unwrap();
|
||||
let path = deps.parent().unwrap().parent().unwrap().join(exe);
|
||||
if !path.exists() {
|
||||
let cargo = std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
|
||||
let status = std::process::Command::new(cargo)
|
||||
.args(["build", "-p", "lutra-lsp", "--bin", "lutra-lsp-fake"])
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success(), "building lutra-lsp-fake failed");
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
/// Starting the fake server with `args`.
|
||||
fn launch(args: &[&str], options: ServerOptions) -> Launch {
|
||||
Launch {
|
||||
command: fake_server().into(),
|
||||
args: args.iter().map(OsString::from).collect(),
|
||||
options,
|
||||
tick: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A temp project with `files`, opened in an engine that runs the fake
|
||||
/// server.
|
||||
fn project(files: &[(&str, &str)], launch: Launch) -> (TempDir, Engine) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for (name, text) in files {
|
||||
fs::write(dir.path().join(name), text).unwrap();
|
||||
}
|
||||
let mut engine = Engine::new().unwrap();
|
||||
engine.set_language_server(Some(launch));
|
||||
engine
|
||||
.execute("project.open", json!({"path": dir.path()}))
|
||||
.unwrap();
|
||||
(dir, engine)
|
||||
}
|
||||
|
||||
/// Pumps until `done` holds for an event; returns every event seen, up to
|
||||
/// the end of that pump's batch.
|
||||
fn pump_until(engine: &mut Engine, done: impl Fn(&Value) -> bool) -> Vec<Value> {
|
||||
let deadline = Instant::now() + Duration::from_secs(20);
|
||||
let mut seen = Vec::new();
|
||||
while Instant::now() < deadline {
|
||||
let mut hit = false;
|
||||
for event in engine.pump_vfs().unwrap() {
|
||||
let value = serde_json::to_value(&event).unwrap();
|
||||
hit |= done(&value);
|
||||
seen.push(value);
|
||||
}
|
||||
if hit {
|
||||
return seen;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
panic!("condition not met within 20 s; events: {seen:#?}");
|
||||
}
|
||||
|
||||
/// Whether `e` is `lspStatus` with `state`.
|
||||
fn status_is(e: &Value, state: &str) -> bool {
|
||||
e["kind"] == "lspStatus" && e["state"] == state
|
||||
}
|
||||
|
||||
/// Pumps until the diagnostic of `path` says `text`.
|
||||
fn wait_for_text(engine: &mut Engine, path: &str, text: &str) {
|
||||
pump_until(engine, |e| {
|
||||
e["kind"] == "diagnosticsChanged" && e["path"] == path && e["items"][0]["message"] == text
|
||||
});
|
||||
}
|
||||
|
||||
/// Applies one UTF-16 edit to buffer `id`; returns the new version.
|
||||
fn edit(engine: &mut Engine, id: u64, base: u64, from: usize, to: usize, insert: &str) -> u64 {
|
||||
let out = engine
|
||||
.execute(
|
||||
"buffer.edit",
|
||||
json!({"id": id, "baseVersion": base, "edits": [{"from": from, "to": to, "insert": insert}]}),
|
||||
)
|
||||
.unwrap();
|
||||
out.value["version"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
/// The text of buffer `id`.
|
||||
fn text(engine: &mut Engine, id: u64) -> String {
|
||||
let out = engine.execute("buffer.get", json!({"id": id})).unwrap();
|
||||
out.value["text"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn syncs_buffers_and_reports_diagnostics() {
|
||||
let (_dir, mut engine) = project(
|
||||
&[("a.php", "<?php\necho 1;\n"), ("notes.txt", "plain")],
|
||||
launch(&[], ServerOptions::default()),
|
||||
);
|
||||
let seen = pump_until(&mut engine, |e| status_is(e, "ready"));
|
||||
assert!(seen.iter().any(|e| status_is(e, "starting")), "{seen:?}");
|
||||
let status = engine.execute("lsp.status", Value::Null).unwrap().value;
|
||||
assert_eq!(status["state"], "ready");
|
||||
assert!(status["startupMs"].as_u64().is_some(), "{status}");
|
||||
|
||||
let id = engine
|
||||
.execute("file.open", json!({"path": "a.php"}))
|
||||
.unwrap()
|
||||
.value["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
wait_for_text(&mut engine, "a.php", "<?php\necho 1;\n");
|
||||
|
||||
let v = edit(&mut engine, id, 1, 11, 12, "\u{1F9A6} 2");
|
||||
let v = edit(&mut engine, id, v, 0, 0, "\r\n");
|
||||
let _ = edit(&mut engine, id, v, 2, 2, "// é\n");
|
||||
let expected = text(&mut engine, id);
|
||||
assert_eq!(expected, "\r\n// é\n<?php\necho \u{1F9A6} 2;\n");
|
||||
wait_for_text(&mut engine, "a.php", &expected);
|
||||
|
||||
let list = engine
|
||||
.execute("diagnostics.list", json!({"path": "a.php"}))
|
||||
.unwrap()
|
||||
.value;
|
||||
let item = &list["files"][0]["items"][0];
|
||||
assert_eq!(list["files"][0]["path"], "a.php");
|
||||
assert_eq!(item["severity"], "error");
|
||||
assert_eq!(item["source"], "fake");
|
||||
assert_eq!(item["message"], expected.as_str());
|
||||
assert_eq!(
|
||||
item["range"],
|
||||
json!({"start": {"line": 0, "column": 0}, "end": {"line": 0, "column": 0}})
|
||||
);
|
||||
|
||||
let txt = engine
|
||||
.execute("file.open", json!({"path": "notes.txt"}))
|
||||
.unwrap()
|
||||
.value["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
edit(&mut engine, txt, 1, 0, 0, "x");
|
||||
let all = engine
|
||||
.execute("diagnostics.list", Value::Null)
|
||||
.unwrap()
|
||||
.value;
|
||||
assert_eq!(all["files"].as_array().unwrap().len(), 1, "{all}");
|
||||
|
||||
engine
|
||||
.execute("buffer.close", json!({"id": id, "force": true}))
|
||||
.unwrap();
|
||||
pump_until(&mut engine, |e| {
|
||||
e["kind"] == "diagnosticsChanged" && e["path"] == "a.php" && e["items"] == json!([])
|
||||
});
|
||||
let all = engine
|
||||
.execute("diagnostics.list", Value::Null)
|
||||
.unwrap()
|
||||
.value;
|
||||
assert_eq!(all, json!({"files": []}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reload_from_disk_resends_the_whole_text() {
|
||||
let (dir, mut engine) = project(
|
||||
&[("a.php", "<?php\n")],
|
||||
launch(&["--sync-full"], ServerOptions::default()),
|
||||
);
|
||||
engine
|
||||
.execute("file.open", json!({"path": "a.php"}))
|
||||
.unwrap();
|
||||
wait_for_text(&mut engine, "a.php", "<?php\n");
|
||||
fs::write(dir.path().join("a.php"), "<?php\n// changed on disk\n").unwrap();
|
||||
wait_for_text(&mut engine, "a.php", "<?php\n// changed on disk\n");
|
||||
}
|
||||
|
||||
/// `test.probe {path}`: submits a closure that reports the server's copy
|
||||
/// of `path`, the way M3.4/M3.5 commands send requests.
|
||||
struct Probe(Mutex<Option<mpsc::Sender<Option<String>>>>);
|
||||
|
||||
impl Command for Probe {
|
||||
fn spec(&self) -> &CommandSpec {
|
||||
&CommandSpec {
|
||||
id: "test.probe",
|
||||
label: "Probe",
|
||||
menu_path: None,
|
||||
default_shortcut: None,
|
||||
params: "path",
|
||||
}
|
||||
}
|
||||
|
||||
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
||||
let root = state.project.as_ref().unwrap().project.root().to_path_buf();
|
||||
let path = root.join(params.as_str().unwrap());
|
||||
let tx = self.0.lock().unwrap().take().unwrap();
|
||||
let queued = lutra_engine::lsp::submit(state, move |server| {
|
||||
let _ = tx.send(server.document_text(&path));
|
||||
});
|
||||
assert!(queued);
|
||||
Ok(Outcome::default())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requests_never_overtake_edits() {
|
||||
let (_dir, mut engine) = project(
|
||||
&[("a.php", "<?php\n")],
|
||||
launch(&[], ServerOptions::default()),
|
||||
);
|
||||
let id = engine
|
||||
.execute("file.open", json!({"path": "a.php"}))
|
||||
.unwrap()
|
||||
.value["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
engine.pump_vfs().unwrap();
|
||||
let mut version = 1;
|
||||
for i in 0..50 {
|
||||
version = edit(&mut engine, id, version, 0, 0, &format!("{i},"));
|
||||
}
|
||||
let expected = text(&mut engine, id);
|
||||
let (tx, rx) = mpsc::channel();
|
||||
engine
|
||||
.register(Box::new(Probe(Mutex::new(Some(tx)))))
|
||||
.unwrap();
|
||||
engine.execute("test.probe", json!("a.php")).unwrap();
|
||||
let seen = rx.recv_timeout(Duration::from_secs(20)).unwrap();
|
||||
assert_eq!(seen.as_deref(), Some(expected.as_str()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_close_stops_the_server_and_clears_diagnostics() {
|
||||
let (_dir, mut engine) = project(
|
||||
&[("a.php", "<?php\n")],
|
||||
launch(&[], ServerOptions::default()),
|
||||
);
|
||||
engine
|
||||
.execute("file.open", json!({"path": "a.php"}))
|
||||
.unwrap();
|
||||
wait_for_text(&mut engine, "a.php", "<?php\n");
|
||||
let out = engine
|
||||
.execute("project.close", json!({"force": true}))
|
||||
.unwrap();
|
||||
let mut seen: Vec<Value> = out
|
||||
.events
|
||||
.iter()
|
||||
.map(|e| serde_json::to_value(e).unwrap())
|
||||
.collect();
|
||||
seen.extend(pump_until(&mut engine, |e| status_is(e, "stopped")));
|
||||
assert!(
|
||||
seen.iter()
|
||||
.any(|e| e["kind"] == "diagnosticsChanged" && e["items"] == json!([])),
|
||||
"{seen:#?}"
|
||||
);
|
||||
let all = engine
|
||||
.execute("diagnostics.list", Value::Null)
|
||||
.unwrap()
|
||||
.value;
|
||||
assert_eq!(all, json!({"files": []}));
|
||||
assert_eq!(
|
||||
engine.execute("lsp.status", Value::Null).unwrap().value["state"],
|
||||
"stopped"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quit_stops_the_server_and_keeps_it_stopped() {
|
||||
let (_dir, mut engine) = project(
|
||||
&[(
|
||||
"a.php", "<?php
|
||||
",
|
||||
)],
|
||||
launch(&[], ServerOptions::default()),
|
||||
);
|
||||
engine
|
||||
.execute("file.open", json!({"path": "a.php"}))
|
||||
.unwrap();
|
||||
wait_for_text(
|
||||
&mut engine,
|
||||
"a.php",
|
||||
"<?php
|
||||
",
|
||||
);
|
||||
let started = Instant::now();
|
||||
let out = engine.execute("app.quit", json!({})).unwrap();
|
||||
assert!(started.elapsed() < Duration::from_secs(5));
|
||||
let events: Vec<Value> = out
|
||||
.events
|
||||
.iter()
|
||||
.map(|e| serde_json::to_value(e).unwrap())
|
||||
.collect();
|
||||
assert!(
|
||||
events.iter().any(|e| status_is(e, "stopped")),
|
||||
"{events:#?}"
|
||||
);
|
||||
for _ in 0..10 {
|
||||
let events = engine.pump_vfs().unwrap();
|
||||
assert!(
|
||||
!events.iter().any(|e| matches!(e, Event::LspStatus(_))),
|
||||
"{events:?}"
|
||||
);
|
||||
}
|
||||
assert!(engine.state().lsp.server().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restart_starts_a_fresh_server() {
|
||||
let (_dir, mut engine) = project(
|
||||
&[("a.php", "<?php\n")],
|
||||
launch(&[], ServerOptions::default()),
|
||||
);
|
||||
pump_until(&mut engine, |e| status_is(e, "ready"));
|
||||
let out = engine.execute("lsp.restart", Value::Null).unwrap();
|
||||
let mut seen: Vec<Value> = out
|
||||
.events
|
||||
.iter()
|
||||
.map(|e| serde_json::to_value(e).unwrap())
|
||||
.collect();
|
||||
seen.extend(pump_until(&mut engine, |e| status_is(e, "ready")));
|
||||
let states: Vec<&str> = seen
|
||||
.iter()
|
||||
.filter(|e| e["kind"] == "lspStatus")
|
||||
.map(|e| e["state"].as_str().unwrap())
|
||||
.collect();
|
||||
assert_eq!(states, ["stopped", "starting", "ready"], "{seen:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_server_fails_with_a_notification() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut engine = Engine::new().unwrap();
|
||||
engine.set_language_server(Some(Launch {
|
||||
command: dir.path().join("no-such-server").into(),
|
||||
args: Vec::new(),
|
||||
options: ServerOptions::default(),
|
||||
tick: None,
|
||||
}));
|
||||
engine
|
||||
.execute("project.open", json!({"path": dir.path()}))
|
||||
.unwrap();
|
||||
let seen = pump_until(&mut engine, |e| status_is(e, "failed"));
|
||||
let failed = seen.iter().find(|e| status_is(e, "failed")).unwrap();
|
||||
assert!(
|
||||
failed["message"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("no-such-server"),
|
||||
"{failed}"
|
||||
);
|
||||
let note = seen.iter().find(|e| e["kind"] == "notification").unwrap();
|
||||
assert_eq!(note["messageKey"], "notification.lsp.failed");
|
||||
assert_eq!(note["level"], "error");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crashing_server_restarts_then_gives_up() {
|
||||
let options = ServerOptions {
|
||||
restart: RestartPolicy {
|
||||
first_delay: Duration::from_millis(10),
|
||||
max_delay: Duration::from_millis(20),
|
||||
max_crashes: 2,
|
||||
window: Duration::from_secs(60),
|
||||
},
|
||||
..ServerOptions::default()
|
||||
};
|
||||
let (_dir, mut engine) = project(
|
||||
&[("a.php", "<?php\n")],
|
||||
launch(&["--exit-immediately"], options),
|
||||
);
|
||||
let seen = pump_until(&mut engine, |e| status_is(e, "failed"));
|
||||
assert!(seen.iter().any(|e| status_is(e, "restarting")), "{seen:#?}");
|
||||
assert_eq!(
|
||||
engine.execute("lsp.status", Value::Null).unwrap().value["state"],
|
||||
"failed"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_server_without_a_project_or_toolchain() {
|
||||
let mut engine = Engine::new().unwrap();
|
||||
engine.set_language_server(Some(launch(&[], ServerOptions::default())));
|
||||
assert!(engine.pump_vfs().unwrap().is_empty());
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut engine = Engine::new().unwrap();
|
||||
engine
|
||||
.execute("project.open", json!({"path": dir.path()}))
|
||||
.unwrap();
|
||||
for _ in 0..5 {
|
||||
let events = engine.pump_vfs().unwrap();
|
||||
assert!(
|
||||
!events.iter().any(|e| matches!(e, Event::LspStatus(_))),
|
||||
"{events:?}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
engine.execute("lsp.status", Value::Null).unwrap().value,
|
||||
json!({"state": "stopped"})
|
||||
);
|
||||
let err = engine
|
||||
.execute("diagnostics.list", json!({"bogus": 1}))
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "invalid_params");
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig { cases: 12, ..ProptestConfig::default() })]
|
||||
|
||||
/// Any sequence of edits, incremental or full sync, ends with the
|
||||
/// server's copy equal to the buffer.
|
||||
#[test]
|
||||
fn random_edits_stay_in_sync(
|
||||
full in any::<bool>(),
|
||||
edits in prop::collection::vec((0usize..64, 0usize..8, "[a-zé\u{1F9A6}\n\r ]{0,6}"), 1..25),
|
||||
) {
|
||||
let args: &[&str] = if full { &["--sync-full"] } else { &[] };
|
||||
let (_dir, mut engine) = project(&[("a.php", "<?php\n$x = 'ä';\n")], launch(args, ServerOptions::default()));
|
||||
let id = engine
|
||||
.execute("file.open", json!({"path": "a.php"}))
|
||||
.unwrap()
|
||||
.value["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
let mut version = 1;
|
||||
for (at, len, insert) in edits {
|
||||
let current = text(&mut engine, id);
|
||||
let units: Vec<usize> = std::iter::once(0)
|
||||
.chain(current.char_indices().map(|(i, c)| current[..i].encode_utf16().count() + c.len_utf16()))
|
||||
.collect();
|
||||
let from = units[at % units.len()];
|
||||
let to = units[(at + len).min(units.len() - 1)].max(from);
|
||||
let result = engine.execute(
|
||||
"buffer.edit",
|
||||
json!({"id": id, "baseVersion": version, "edits": [{"from": from, "to": to, "insert": insert}]}),
|
||||
);
|
||||
if let Ok(out) = result {
|
||||
version = out.value["version"].as_u64().unwrap();
|
||||
}
|
||||
if at % 5 == 0 {
|
||||
engine.pump_vfs().unwrap();
|
||||
}
|
||||
}
|
||||
let expected = text(&mut engine, id);
|
||||
wait_for_text(&mut engine, "a.php", &expected);
|
||||
}
|
||||
}
|
||||
|
||||
/// The real Phpactor (ignored; needs PHP and a PHAR): a file with two
|
||||
/// errors gets its diagnostics after `file.open`, and an edit that adds a
|
||||
/// third gets them again. Prints the startup and diagnostics latencies.
|
||||
///
|
||||
/// `LUTRA_PHPACTOR=<phar> [LUTRA_PHP=php] cargo test -p lutra-engine --test lsp real_phpactor -- --ignored --nocapture`
|
||||
#[test]
|
||||
#[ignore = "needs PHP and Phpactor (LUTRA_PHPACTOR)"]
|
||||
fn real_phpactor_reports_diagnostics() {
|
||||
let phar = std::env::var("LUTRA_PHPACTOR").expect("LUTRA_PHPACTOR");
|
||||
let php = std::env::var("LUTRA_PHP").unwrap_or_else(|_| "php".into());
|
||||
let text = "<?php\n\nnamespace App;\n\nfinal class Greeter\n{\n public function greet(): string\n {\n return 'hi';\n }\n}\n\n$g = new Greeter();\n$g->wave();\n";
|
||||
let launch = lutra_engine::lsp::phpactor_launch(&php, &phar, cfg!(windows));
|
||||
let (_dir, mut engine) = project(&[("Broken.php", text)], launch);
|
||||
let started = Instant::now();
|
||||
let seen = pump_until(&mut engine, |e| {
|
||||
status_is(e, "ready") || status_is(e, "failed")
|
||||
});
|
||||
println!("ready after {:?}: {:?}", started.elapsed(), seen.last());
|
||||
let id = engine
|
||||
.execute("file.open", json!({"path": "Broken.php"}))
|
||||
.unwrap()
|
||||
.value["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
let opened = Instant::now();
|
||||
let has = |e: &Value, word: &str| {
|
||||
e["kind"] == "diagnosticsChanged"
|
||||
&& e["items"].as_array().is_some_and(|items| {
|
||||
items
|
||||
.iter()
|
||||
.any(|i| i["message"].as_str().unwrap_or("").contains(word))
|
||||
})
|
||||
};
|
||||
let deadline = Instant::now() + Duration::from_secs(120);
|
||||
let mut found = false;
|
||||
while Instant::now() < deadline && !found {
|
||||
for event in engine.pump_vfs().unwrap() {
|
||||
let value = serde_json::to_value(&event).unwrap();
|
||||
if value["kind"] != "notification" {
|
||||
println!("{:?} {value}", opened.elapsed());
|
||||
}
|
||||
found |= has(&value, "wave");
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
assert!(found, "no diagnostics for wave() within 120 s");
|
||||
println!("first diagnostics after {:?}", opened.elapsed());
|
||||
let end = text.encode_utf16().count();
|
||||
edit(&mut engine, id, 1, end, end, "$g->dance();\n");
|
||||
let edited = Instant::now();
|
||||
let deadline = Instant::now() + Duration::from_secs(60);
|
||||
let mut found = false;
|
||||
while Instant::now() < deadline && !found {
|
||||
for event in engine.pump_vfs().unwrap() {
|
||||
found |= has(&serde_json::to_value(&event).unwrap(), "dance");
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
assert!(found, "no diagnostics for dance() within 60 s");
|
||||
println!("diagnostics after edit {:?}", edited.elapsed());
|
||||
}
|
||||
|
|
@ -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 · **Last updated:** 2026-10-20
|
||||
> **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) · **Last updated:** 2026-10-21
|
||||
|
||||
## Overview
|
||||
|
||||
|
|
@ -343,6 +343,65 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
|
|||
- **Bottom panel tabs:** `BottomPanel.vue` takes `tabs` and `v-model:active`; with tabs the header shows a tab list instead of the title. `MainLayout.vue` shows Find and Terminal as tabs while both are visible; `find.open` and `terminal.open` make their tool window the active tab, the close button hides the active one, and expansion is kept per tool window.
|
||||
- **`terminal.open`** (UI command, `Mod+Shift+T`, Lutra's own; enabled with a project): shows the Terminal tab, creates a terminal if none is running (always with `{new: true}`) and focuses it.
|
||||
|
||||
### Engine wiring and diagnostics (M3.3)
|
||||
|
||||
- **Where:** `crates/engine/src/lsp/` (`mod.rs`: state, pump, sync, diagnostics; `session.rs`: the session thread), commands in `crates/engine/src/cmd/lsp_diagnostics.rs`. One-line hooks in `buffer.edit` (`lsp::record_edits`), the pump (`lsp::pump`), `app.quit` (`lsp::shutdown_now`), `State`, `Event` and the registry.
|
||||
- **Lifecycle:** one session per open project.
|
||||
- It starts at the first pump where a project is open and `toolchain.status` reports a usable PHP and a ready Phpactor (`php <phar> language-server` in the project root). With a host-set server (`Engine::set_language_server`, the fake server in tests) it starts at once.
|
||||
- A change of root, PHP or PHAR replaces the session. Closing the project, `lsp.restart` and dropping the engine stop it.
|
||||
- `app.quit` stops it synchronously (`shutdown`, `exit`, kill; quit measured at 1.55 s on Windows). The host exits right after, which would cut a background shutdown short and leave `php.exe` running.
|
||||
- **Nothing heavy under the lock:** each session has one thread (`lsp-session`) that owns the `lutra_lsp::Server`, and it also spawns the process. The engine lock only enqueues jobs on the thread's FIFO:
|
||||
- `Open`/`Full` carry an O(1) rope clone of the buffer; the text is built on the thread.
|
||||
- `Change` carries the edit batch that `buffer.edit` applied.
|
||||
- `Save`, `Close`, and `Run(closure)` for requests.
|
||||
|
||||
Requests from M3.4/M3.5 go through `lsp::submit` on the same queue, so a request never overtakes an edit's `didChange` (tested).
|
||||
- **Document sync:** PHP buffers (`.php`, `.phtml`, `.inc`) are opened when the pump first sees them and closed when they close.
|
||||
- `buffer.edit` queues its batch as `didChange` when the server's copy is at the edit's base version.
|
||||
- Otherwise the next pump resends the whole text: after a reload from disk, a restore, or a `didChange` the client copy rejected.
|
||||
- When the saved version of a clean buffer moves, the pump sends `didSave`.
|
||||
- Property-tested with random edits (incremental and full sync): the fake server's copy always ends equal to the buffer.
|
||||
- **Events and commands:**
|
||||
- `lspStatus {state: starting|ready|restarting|failed|stopped, message?}` follows the client's status. `failed` (spawn error, too many crashes) also raises `notification.lsp.failed`.
|
||||
- `diagnosticsChanged {path, items: [{range: {start: {line, column}, end}, severity: error|warning|info|hint, message, source?, code?}]}` per project file.
|
||||
- Columns are UTF-16, and files outside the project are ignored.
|
||||
- A missing severity counts as error.
|
||||
- Caps: at most 10,000 files, and 10,000 items each from the client.
|
||||
- `diagnostics.list {path?}` returns `{files: [{path, items}]}` sorted by path. `lsp.status` returns `{state, message?, startupMs?}`. `lsp.restart` is in the Tools menu.
|
||||
- Diagnostics are cleared (an empty `diagnosticsChanged` per file) when the session ends or the server fails, so stale ones never stay. The pump handles at most 2,000 server events per call.
|
||||
- **UI:**
|
||||
- **Editor:** `ui/src/components/editor/lint.ts` feeds CodeMirror's lint extension (`@codemirror/lint`, MIT) with wavy underlines, a gutter dot, and the message with source and code on hover.
|
||||
- Colours come only from tokens: error `--lt-error`, warning `--lt-accent`, info/hint `--lt-fg-muted`. Dedicated diagnostic tokens are a design follow-up.
|
||||
- A view plugin per editor state applies its path's list when the view shows the state and on every change. CodeMirror maps ranges through edits until the next publication.
|
||||
- **Problems:** `ui/src/components/problems/` holds the store and the tab.
|
||||
- The store loads `diagnostics.list` and `lsp.status` on start and on project open, follows the events, and hands each file to `lint.ts`.
|
||||
- The Problems tab in the bottom panel groups by file, errors first; click or Enter runs `editor.reveal`.
|
||||
- `problems.open` is `Mod+Alt+P`, menu View/Problems.
|
||||
- **Phpactor 2026.06.25.0 on Windows:** the live check found two problems, worked around without touching the user's project.
|
||||
- **The event loop stalls.** Its amphp event loop only runs when a message arrives on stdin, so timers stall while the client is quiet: the diagnostics debounce (`language_server.diagnostic_sleep_time`) and the file watcher.
|
||||
- Seen: the server answered `initialize` in 0.8 s, but published nothing after `didOpen` and only a clearing empty list after `didChange`.
|
||||
- Fix: while busy (a job in the last 60 s and the server ready), the session thread sends the no-op notification `$/lutra/tick`. It comes from the thread's own `recv_timeout` loop, so it does not depend on the host's pump.
|
||||
- The interval sets the latency, because Phpactor's analysis advances one step per message. Edit to diagnostics (engine test with the real PHAR, measured): 5.9 s at 200 ms, 2.5 s at 50 ms, 1.5 s at 20 ms. Lutra uses 25 ms.
|
||||
- The same stall means Phpactor rarely answers `shutdown` in time, so the shutdown timeout is 500 ms before the kill.
|
||||
- **Subprocesses fail.** Every subprocess it starts through amphp fails with `CreateProcess failed`: outsourced diagnostics, the PHP lint provider, the indexer's `find` watcher.
|
||||
- Fix: `initializationOptions` set `language_server.diagnostic_outsource: false` (diagnostics run in the server process) and `indexer.enabled_watchers: ["php"]` (a polling watcher).
|
||||
- The PHP lint provider still fails once and removes itself; its `window/showMessage` warning is not shown.
|
||||
- So Lutra has no `php -l` syntax errors on Windows yet. The worse-reflection diagnostics (missing members, unknown classes, …) work.
|
||||
- These adjustments (tick, initialization options, short shutdown timeout) apply on Windows only (`lsp::phpactor_launch`). macOS and Linux are untested.
|
||||
- **Measured** (Windows 11, PHP 8.4.24, debug build, 16-line file):
|
||||
- Phpactor is ready 0.8–0.9 s after the session starts (`startupMs`).
|
||||
- First diagnostics after `file.open`: 1.7 s in the engine test, 2.7 s in the app over the control channel.
|
||||
- After an edit: 1.8 s and 2.7–2.9 s, including Phpactor's 1 s debounce.
|
||||
- Without the adjustments: no diagnostics within 180 s.
|
||||
- **Known gaps:**
|
||||
- A Phpactor process outlives Lutra when Lutra is killed, or when a test process exits right after dropping the engine. There is no job object or kill-on-close yet; that is a `lutra-lsp` follow-up.
|
||||
- `window/showMessage` and `logMessage` are dropped, and server-initiated progress is not shown.
|
||||
- **Tests:**
|
||||
- `crates/engine/tests/lsp.rs` has 10 tests against `lutra-lsp-fake`: sync incl. UTF-16 and CRLF edits, diagnostics list/clear, reload resync, requests after edits, project close, restart, quit, missing server, crash and give-up, no server without a project, and a proptest of random edits. The ignored `real_phpactor_reports_diagnostics` runs with `LUTRA_PHPACTOR=<phar>`.
|
||||
- Unit tests cover severity, paths, the Phpactor launch and the tick rule.
|
||||
- `crates/control/tests/lsp.rs` runs over TCP with ticks on.
|
||||
- Vitest: `ui/tests/editor/lint.test.ts` and `ui/tests/problems/ProblemsToolWindow.test.ts`.
|
||||
|
||||
### Toolchain (M3.1)
|
||||
|
||||
- **Owner decision D15:** Lutra downloads the Phpactor PHAR itself; PHP is the user's (found through `php.executable` or `PATH`). Library code lives in `crates/lsp/src/toolchain/` (L3), the engine side in `crates/engine/src/cmd/toolchain.rs`.
|
||||
|
|
@ -386,6 +445,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
|
|||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-20 | minor | M3.10: autosave (blur, tab switch, idle), `flushDirty`, `file.saveAll {skipConflicts}`, disk conflicts and own-write hashes in `Buffers` |
|
||||
| 2026-10-21 | minor | M3.3: engine ↔ Phpactor wiring (session thread, ordered sync, `lspStatus`, `diagnosticsChanged`, `diagnostics.list`, `lsp.status`, `lsp.restart`), Phpactor-on-Windows workarounds, lint extension, Problems tab |
|
||||
| 2026-10-19 | minor | M3.8: MCP server (`lutra mcp`, dual era 2026-07-28 + legacy `initialize`), tools, resources, event buffer; `buffer.list` |
|
||||
| 2026-10-19 | minor | M3.9: app menu (header bar, `menu.open`, grouping by `menuPath`, launcher under the modal rule); menu paths for user commands |
|
||||
| 2026-10-18 | minor | M3.6: integrated terminal (`crates/terminal` sessions, backpressure, `terminal.*`, `terminalOutput`/`terminalExited` via the pump, lifecycle, xterm.js views, terminal tokens, focus rule, bottom panel tabs) |
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Gaps
|
||||
|
||||
> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal, autosave); G3 M1 part done (project tree, palette, settings dialog, themes) plus the app menu (M3.9); G4 under way (tree-sitter outline and folding library, Lezer highlighting, Structure tool window); G5 under way (search backend, Find tool window, symbol index, go-to popup); G6 under way (LSP client library, PHP detection, Phpactor download); G7 under way (`lutra` CLI and single instance, MCP server, integrated terminal); G14 English UI catalog in place · **Last updated:** 2026-10-20
|
||||
> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal, autosave); G3 M1 part done (project tree, palette, settings dialog, themes) plus the app menu (M3.9); G4 under way (tree-sitter outline and folding library, Lezer highlighting, Structure tool window); G5 under way (search backend, Find tool window, symbol index, go-to popup); G6 under way (LSP client library, PHP detection, Phpactor download, engine wiring and diagnostics); G7 under way (`lutra` CLI and single instance, MCP server, integrated terminal); G14 English UI catalog in place · **Last updated:** 2026-10-21
|
||||
|
||||
Every known shortfall, ranked. This is the work list: unless the owner gives a task, take the highest open gap. Hours are agent wall-clock hours for one agent, all estimated.
|
||||
|
||||
|
|
@ -11,7 +11,7 @@ Every known shortfall, ranked. This is the work list: unless the owner gives a t
|
|||
| G3 | Project model: ~~VFS~~ (M1.2: listing, ignore rules, native file watching with polling fallback, safe file IO), ~~project tree wiring~~ (M1.5 UI, M1.3 engine, M1.4 bridge: folder picker, live tree), tree toolbar and options, ~~showing truncated listings~~ (M1.13), ~~error notifications for the folder picker~~ (M1.12), ~~tabs~~ (M1.6), ~~command palette~~ (M1.8: commands only, global keymap, UI commands over the control channel); ~~settings~~ (backend: M1.9a; dialog with search: M1.9b), ~~theme switching~~ (M1.10: light/dark, live, system mode; picker in the dialog, M1.9b), ~~main menu~~ (M3.9: hamburger dropdown from `menuPath`s; native macOS menu bar and display modes open) | M1 | ~24 h |
|
||||
| G4 | Syntax and structure: tree-sitter PHP, ~~Lezer highlighting~~ (M2.2: PHP with embedded HTML plus HTML, CSS, JS/TS, JSON, YAML, Markdown; `--lt-syntax-*` tokens; `editor.reveal`), ~~file structure~~ (M2.7: Structure tool window, `syntax.outline`), semantic highlighting, folding in the editor | M2 | ~8 h |
|
||||
| G5 | Search and navigation: find in files, go to file/class/symbol, first index | M2 | ~35 h |
|
||||
| G6 | Language server: completion, diagnostics, definition, hover, rename via Phpactor (~~PHP detection and Phpactor download~~, M3.1) | M3 | ~43 h |
|
||||
| G6 | Language server: completion, definition, hover, rename via Phpactor (~~PHP detection and Phpactor download~~, M3.1; ~~engine wiring and diagnostics~~, M3.3) | M3 | ~33 h |
|
||||
| G7 | ~~Terminal~~ (M3.6: PTY sessions, xterm.js sub-tabs in the bottom panel; settings, persistence, links and search still open), ~~`lutra` CLI and single instance~~ (M3.7: open folders and files at a line, `--wait`, forwarding a second start, token-protected rendezvous), ~~MCP server~~ (M3.8: `lutra mcp` with list/execute every command, screenshot, read buffer, recent events, open buffers as resources; still missing: resource and tool change notifications, progress for long commands), files outside the open project (the CLI refuses them; needs out-of-project buffers or a second window), `lutra diff` | M3 | ~16 h |
|
||||
| G8 | Git integration | M4 | ~150 h |
|
||||
| G9 | Debugger, test runner, Composer, run configurations | M5 | ~300 h |
|
||||
|
|
@ -44,12 +44,13 @@ Known smaller items from M0:
|
|||
- `ui.screenshot` captures the screen region of the window, so covering windows appear in the image; a webview-native capture would avoid that.
|
||||
- `cargo xtask fixtures` needs Composer, which the M0 machine does not have.
|
||||
|
||||
G6 progress: M3.2 landed the LSP client library in `crates/lsp`: JSON-RPC framing over stdio (32 MiB cap, malformed messages dropped and logged, fuzzed), `initialize` with UTF-16 positions, typed requests with timeouts and `$/cancelRequest`, answers to server requests, supervision with backoff restarts (give up after 5 crashes in 2 min) and reopening of documents, incremental document sync from `lutra_text` edits, all tested against a fake server. Not yet wired into the engine (M3.3) and not yet run against a real Phpactor; diagnostics, completion, hover, navigation and rename are still open (M3.3 to M3.5).
|
||||
G6 progress: M3.2 landed the LSP client library in `crates/lsp`: JSON-RPC framing over stdio (32 MiB cap, malformed messages dropped and logged, fuzzed), `initialize` with UTF-16 positions, typed requests with timeouts and `$/cancelRequest`, answers to server requests, supervision with backoff restarts (give up after 5 crashes in 2 min) and reopening of documents, incremental document sync from `lutra_text` edits, all tested against a fake server. M3.3 wired it into the engine (one Phpactor per project on its own thread, ordered document sync, `lspStatus`) and shows Phpactor's diagnostics as editor underlines and in a Problems tab. It was checked against the real Phpactor on Windows, which needed three workarounds: a keep-alive tick, in-process diagnostics and a polling watcher (see `docs/architecture.md`). Still open: completion and hover (M3.4), navigation and rename (M3.5), PHP lint syntax errors on Windows, quick-fixes, and killing a Phpactor process left behind when Lutra itself is killed.
|
||||
|
||||
## Revision history
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-21 | minor | G6 shrunk: engine wiring and diagnostics (M3.3) |
|
||||
| 2026-10-20 | minor | G2 shrunk: autosave and `flushDirty` (M3.10) |
|
||||
| 2026-10-19 | minor | G7: MCP server (M3.8) |
|
||||
| 2026-10-19 | minor | G3: app menu (M3.9) |
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Milestones
|
||||
|
||||
> **Status:** M0 done, M1 done, M2 in progress · **Last updated:** 2026-10-20
|
||||
> **Status:** M0 done, M1 done, M2 in progress · **Last updated:** 2026-10-21
|
||||
|
||||
Hours are agent wall-clock hours for one agent; M0 and M1 so far are measured, the rest estimated. Since cycle C1 (factor 0.07) M1–M3 are scaled ×0.1; M4–M6 keep their first raw estimates (multiply by ~0.1 for the calibrated value).
|
||||
|
||||
|
|
@ -9,7 +9,7 @@ Hours are agent wall-clock hours for one agent; M0 and M1 so far are measured, t
|
|||
| M0 | Foundation: workspace, lints, quality gate, command registry, control channel, empty window | done 2026-10-14 (CI workflow written, not yet run: hosted on Forgejo, runners unknown) | ~2 (measured) |
|
||||
| M1 | Editor and project: open folder, tree, tabs, editor, save, recovery, palette, settings, themes | done 2026-10-16 (M1.1 text, M1.2 VFS, M1.5 tree UI, M1.3 engine workspace, M1.4 desktop bridge, M1.6 tabs and editor, M1.11 message catalog, M1.9a settings backend, M1.10 themes, M1.7 recovery journal, M1.12 notifications, M1.13 C1 follow-ups, M1.8 command palette and keymap, M1.14 app icon, M1.9b settings dialog; C2 live checks pending, gaming mode) | ~5.6 (measured: C1 2.5, C2 3.1) |
|
||||
| M2 | Syntax and search: highlighting, structure, find in files, go to file/class/symbol | done 2026-10-17 (C3: M2.1 tree-sitter syntax, M2.2 highlighting + `editor.reveal`, M2.3 search backend, M2.4 Find tool window, M2.5 symbol index + go-to commands, M2.6 go-to popup, M2.7 Structure tool window) | ~6.1 (measured) |
|
||||
| M3 | LSP, terminal, CLI: completion, diagnostics, go to definition, hover, rename; terminal; `lutra` CLI and MCP — **MVP** | in progress (M3.7 CLI and single instance, M3.8 MCP server, M3.10 autosave, M3.6 integrated terminal done) | ~12 |
|
||||
| M3 | LSP, terminal, CLI: completion, diagnostics, go to definition, hover, rename; terminal; `lutra` CLI and MCP — **MVP** | in progress (M3.7 CLI and single instance, M3.8 MCP server, M3.10 autosave, M3.6 integrated terminal, M3.3 engine wiring and diagnostics done) | ~12 |
|
||||
| M4 | Git: status, diff, commit, branches, log, blame, conflicts | not started | ~150 |
|
||||
| M5 | Debugger (Xdebug via DAP), PHPUnit/Pest runner, Composer, run configurations | not started | ~300 |
|
||||
| M6 | Own indexer and inspections; Symfony, Laravel, Shopware, WordPress support | not started | ~1,100 |
|
||||
|
|
@ -34,6 +34,7 @@ By the raw estimates the alpha gate needs M1–M4 plus cross-platform verificati
|
|||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-21 | minor | M3.3 engine wiring and diagnostics |
|
||||
| 2026-10-20 | minor | M3.10 autosave |
|
||||
| 2026-10-18 | minor | M3.6 integrated terminal |
|
||||
| 2026-10-18 | minor | M7–M9 added from the full PhpStorm help inventory (155 feature units); raw hours, calibrate ×0.15 |
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Target-app parity
|
||||
|
||||
> **Status:** M1 done (text buffer, VFS, engine workspace, project tree, tabs and a plain-text editor, recovery, palette, settings and themes in the app); M2 started: PHP syntax highlighting, find in files with its tool window, the symbol index and the go-to popup, the Structure tool window; M3 started: the integrated terminal · **Last updated:** 2026-10-20 · **Target:** PhpStorm 2026.x
|
||||
> **Status:** M1 done (text buffer, VFS, engine workspace, project tree, tabs and a plain-text editor, recovery, palette, settings and themes in the app); M2 started: PHP syntax highlighting, find in files with its tool window, the symbol index and the go-to popup, the Structure tool window; M3 started: the integrated terminal · **Last updated:** 2026-10-21 · **Target:** PhpStorm 2026.x
|
||||
|
||||
## How this is measured
|
||||
|
||||
|
|
@ -19,7 +19,7 @@ Hours are the estimated agent wall-clock hours for one agent to reach behaviour
|
|||
| Navigation | 10 | 10% (est.) | go-to: recent files on an empty query, a non-project toggle (library items always show), file-type filter, `:line` suffixes, actions and text tabs, sending the list to Find; find usages, go to declaration, recent files and locations, navigation history, File Structure popup, Structure speed search, sorting and filters (visibility, inherited members), autoscroll from the caret, navigation bar, bookmarks (M1.8: a command palette over commands only) | ~102 (est.) | M2.6: go-to popup `ui/src/components/goto/` with Files / Classes / Symbols tabs (Tab and Shift+Tab or a click switch, the text stays), UI commands `goto.fileOpen` `Mod+P`, `goto.classOpen` `Mod+Alt+C`, `goto.symbolOpen` `Mod+T` (optional `{query}` for agents), live query against `goto.*` (60 ms debounce, stale answers dropped), matched characters marked, directory / namespace / container column, library rows dimmed and labelled (`goto.file` items now carry `library`), an indexing hint with progress and a re-query on `indexReady`, Enter or a click opens through `editor.reveal`, Escape closes, one modal at a time; Vitest `ui/tests/goto/`, live-checked in the app (port 7826). M2.7: Structure tool window (`ui/src/components/structure/`) in a new left stripe with Project | Structure: the active tab's outline as a tree with Lucide kind icons and signatures, follows the active tab and edits (`outlineChanged`), click or Enter jumps through `editor.reveal`, arrows fold, `view.toggleStructure` `Mod+2`; engine `syntax.outline {id}` from a per-buffer tree-sitter tree reparsed off the engine lock on a worker thread (200 ms debounce). Tests: 11 engine unit tests, engine integration tests with a proptest of random edit sequences (end at a fresh parse's outline), a control-channel test (`crates/control/tests/syntax.rs`), 13 Vitest tests (`ui/tests/structure/`). Checked in the app on Windows 11 (bundled UI, control port 7827): a class file with namespace, interface, enum, trait, class with promoted property and a function; `outlineChanged` 149 ms after `file.open`, `view.toggleStructure` shows the tree, a jump to `find` centres line 62, an added method appears about 0.3 s after `buffer.edit` (debug build). Rows were not clicked in the app (the control channel has no input method); click and Enter are covered by Vitest. 1 MB file: `buffer.edit` ≤ 0.25 ms and `pump_vfs` ≤ 3.8 ms under the lock, edit to `outlineChanged` 0.43–0.76 s, `syntax.outline` 82 ms (release, measured). Graded against `plan/phpstorm/09-structure.md`. M2.5: symbol index in `crates/index` (every project file listed, `.php` parsed in parallel from tree-sitter outlines, vendor marked library, incremental on disk and buffer changes, capped at 200,000 files) and the engine commands `index.status`, `goto.file`, `goto.class`, `goto.symbol` (fuzzy, file names weighted, `Class::member`, project before library, partial results with `indexing: true`), events `indexProgress`/`indexReady`; 20k-file / 88 MB generated project indexed in 3.9–4.2 s (release, measured), queries 2–12 ms; tests `crates/index/tests/`, `crates/engine/tests/goto.rs`, `crates/control/tests/goto.rs`; reached from the UI by M2.6. M2.1: file outline in `crates/syntax` (namespaces braced and unbraced, classes, interfaces, traits, enums with cases, functions, methods, properties incl. promoted ones, constants; UTF-16 ranges and short signatures), the base for the Structure window (M2.7) and the symbol index (M2.5); not reachable from the UI yet, score unchanged. M1.8: `ui/src/components/palette/`, `ui/src/commands/` (fuzzy ranking, recent commands, global keymap), Vitest `ui/tests/palette/`, `ui/tests/commands/` |
|
||||
| Search and replace | 6 | 8% (est.) | find in the current file, replace in files and in a file, scopes (module, directory, open files, custom), comment/string filters, search history, a tab per search, grouping options, merging matches on one line, find in path from the tree, structural search | ~70 (est.) | M2.4 Find tool window in a new resizable, collapsible bottom panel: query with case / whole word / regex toggles, include and exclude globs, streamed results grouped by file (sorted) with the match highlighted in the line preview, counts and elapsed time, cancel, a truncated hint, a refused regex or glob shown in place; Enter or click opens the match through `editor.reveal`, arrow keys / Page / Home / End walk the results; `find.open` (`Mod+Alt+F`, Lutra's own) prefills the selection or the word at the cursor, `find.open {query}` from an agent searches at once; a new search cancels the running one. Tests: 26 Vitest store and component tests (`ui/tests/find/FindToolWindow.test.ts`). Live check (bundled-ui debug build, control port 7824, 3-file temp project): `find.open {query}` over `uiCommand` showed 14 matches in 3 files (vendor included) grouped and highlighted in 17 ms; with `*.php` include 2 matches; revealing a result's position opened the file at the match; `find.open` without params prefilled the word at the cursor; a bad regex showed the engine's message in place (screenshots read, measured). Opening a result by mouse or Enter is covered by Vitest only (the control channel cannot click). M2.3 backend: `crates/search` (parallel `ignore` walk + `grep-searcher`: literal/regex, case, whole word, include/exclude globs, project ignore rules with `vendor/` searched and `node_modules` skipped, binary and > 8 MiB files skipped, match cap, cancel) and engine `search.find` / `search.cancel` with `searchResults` / `searchDone` events through the pump; dirty buffers are searched in their buffer text. Tests: 9 library tests incl. a property test of random queries and file bytes (`crates/search/tests/search.rs`), 3 preview/column unit tests, 4 engine tests (`crates/engine/tests/search.rs`), a TCP control-channel test (find → results → done, invalid regex, cancel; `crates/control/tests/search.rs`). 20k-file generated tree, release: first result 10–43 ms, full walk 0.66–1.43 s (measured); live over the control channel against the running app: first result 55 ms, done 386 ms on a 5,900-file project (debug build, measured) |
|
||||
| Code completion | 10 | 0% | everything | ~250 (est.) | — |
|
||||
| Inspections and quick-fixes | 8 | 0% | everything | ~300 (est.) | — |
|
||||
| Inspections and quick-fixes | 8 | 4% (est.) | Lutra's own inspections and their settings, severities per inspection, quick-fixes (LSP code actions), suppression, inspection profiles, running inspections on a scope, PHP lint syntax errors on Windows, the editor's problem counter and scrollbar marks, next/previous problem, a current-file Problems view and severity filters, external tools (PHPStan, Psalm, PHP_CodeSniffer) | ~290 (est.) | M3.3: diagnostics from Phpactor (worse reflection: missing members, unknown classes, …) as wavy underlines, gutter markers and hover messages in the editor (`ui/src/components/editor/lint.ts`, tokens only), and a Problems tab in the bottom panel grouped by file with click to reveal (`ui/src/components/problems/`, `problems.open` `Mod+Alt+P`); engine `diagnosticsChanged`, `diagnostics.list`, `lspStatus` (`crates/engine/src/lsp/`). Tests: 10 engine tests against a fake server incl. a sync proptest, a TCP test, 16 Vitest tests, an ignored test against the real PHAR. Checked in the app on Windows 11 with the real Phpactor (port 7933): five errors underlined and listed; first diagnostics 2.7 s after `file.open`, 2.7–2.9 s after an edit (debug build, measured, incl. Phpactor's 1 s debounce). Graded against `plan/phpstorm/11-problems.md`: the depth comes from Phpactor, Lutra has no inspections of its own |
|
||||
| Refactoring | 7 | 0% | everything | ~250 (est.) | — |
|
||||
| Code style and formatting | 4 | 0% | everything | ~120 (est.) | — |
|
||||
| Git | 8 | 0% | everything | ~150 (est.) | — |
|
||||
|
|
@ -65,6 +65,7 @@ The project tree is the first user-visible feature (Project view 8%, estimated);
|
|||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-21 | minor | M3.3: Inspections and quick-fixes 0% → 4% (est.), diagnostics from Phpactor and the Problems tab; hours 300 → 290 |
|
||||
| 2026-10-20 | minor | M3.10: Editor core 10% → 11% (est.), autosave and `flushDirty`; hours 104 → 100 |
|
||||
| 2026-10-18 | minor | M3.6: Terminal 0% → 15% (est.), integrated terminal with xterm.js sub-tabs |
|
||||
| 2026-10-18 | minor | Breadth inventory: 155 units from the public help, 23 partially supported |
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# UI parity checklist
|
||||
|
||||
> **Status:** main window layout (M1.5), project tree running against the engine (M1.4), editor tabs with a CodeMirror editor (M1.6), light and dark themes (M1.10), restore dialog for unsaved changes (M1.7), notification toasts (M1.12), command palette and global keymap (M1.8), settings dialog with search (M1.9b), syntax highlighting and `editor.reveal` (M2.2), Find tool window in the bottom panel (M2.4), go-to popup (M2.6), left stripe and Structure tool window (M2.7), app menu (M3.9), Terminal tool window and bottom panel tabs (M3.6) · **Last updated:** 2026-10-20
|
||||
> **Status:** main window layout (M1.5), project tree running against the engine (M1.4), editor tabs with a CodeMirror editor (M1.6), light and dark themes (M1.10), restore dialog for unsaved changes (M1.7), notification toasts (M1.12), command palette and global keymap (M1.8), settings dialog with search (M1.9b), syntax highlighting and `editor.reveal` (M2.2), Find tool window in the bottom panel (M2.4), go-to popup (M2.6), left stripe and Structure tool window (M2.7), app menu (M3.9), Terminal tool window and bottom panel tabs (M3.6), Problems tool window and editor diagnostics (M3.3) · **Last updated:** 2026-10-21
|
||||
|
||||
- [ ] Main window: tool window stripes, editor area, status bar, navigation bar
|
||||
- M2.7 (2026-10-17): a left stripe with one tab per left tool window (Project, Structure); the shown one is marked, clicking it again hides the window. Still missing: right docking, several bottom tool windows, drag to rearrange, navigation bar, layout persistence.
|
||||
|
|
@ -29,6 +29,7 @@
|
|||
- [ ] Structure tool window
|
||||
- M2.7 (2026-10-17): in the left tool window, chosen from the new stripe (Project | Structure); the active tab's declarations (namespaces, class-likes, functions, methods, properties, constants, enum cases) as a WAI-ARIA tree with Lucide kind icons in syntax colours and the short signature; follows the active tab and edits; click or Enter jumps to the name (`editor.reveal`), arrows walk and fold, collapsed nodes kept per file; empty states for no file, no declarations, still reading, too large. `view.toggleStructure` `Mod+2`. Checked in the app on Windows 11 over the control channel (tree, jump to a method, tree updated after an edit; no clicks, the control channel cannot send input). Missing: speed search, sorting and filters, visibility markers, inherited members, autoscroll from the caret, the File Structure popup, VCS colours, running tests from an entry.
|
||||
- [ ] Problems tool window
|
||||
- M3.3 (2026-10-21): a Problems tab in the bottom panel (next to Find and Terminal): the language server's diagnostics of every reported file, grouped by file (name, directory, count), errors first, then by position; each row with a Lucide severity icon in a token colour (error `--lt-error`, warning `--lt-accent`, info and hint `--lt-fg-muted`), the message, source and code, and the 1-based position; a status line with totals or the server state (starting, restarting, failed, not running). Click or Enter reveals the position (`editor.reveal`), arrows / Page / Home / End move. `problems.open` `Mod+Alt+P` (Lutra's own), menu View/Problems. In the editor: wavy underlines per severity, a gutter dot and the message with source and code on hover (CodeMirror lint, tokens only), mapped through edits until the next publication. Diagnostics come from Phpactor, not from Lutra's own inspections. Vitest; live check with the real Phpactor on Windows 11. Missing: a current-file tab or filter, severity filters, sort and group options, quick-fixes (code actions), the editor's problem counter, scrollbar marks, next/previous problem. Behaviour notes: `plan/phpstorm/11-problems.md`.
|
||||
- [ ] Go to file / class / symbol popup
|
||||
- M2.6 (2026-10-17): one popup with Files / Classes / Symbols tabs (Tab / Shift+Tab or a click; the text stays), opened by `goto.fileOpen` `Mod+P`, `goto.classOpen` `Mod+Alt+C`, `goto.symbolOpen` `Mod+T` (Lutra's own keys) or by an agent with `{query}`; live fuzzy results (60 ms debounce, stale answers dropped) with matched characters marked, a Lucide icon per kind, the directory, namespace or container beside the name, library (vendor) rows dimmed with a label; an indexing hint with progress, re-queried on `indexReady`; arrows / Page keys move, Enter or a click opens through `editor.reveal`, Escape or a click outside closes; an exclusive modal. Checked in the running app. Missing: recent files on an empty query, a non-project toggle, file-type filter, `:line` suffixes, preview, more tabs (actions, text), sending results to Find.
|
||||
- [ ] Find tool window
|
||||
|
|
@ -41,6 +42,7 @@
|
|||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-21 | minor | Problems tool window partial, editor diagnostics (M3.3) |
|
||||
| 2026-10-19 | minor | Main menu partial (M3.9) |
|
||||
| 2026-10-18 | minor | Terminal tool window partial, bottom panel tabs (M3.6) |
|
||||
| 2026-10-17 | minor | Go-to popup partial (M2.6) |
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@
|
|||
"@codemirror/lang-php": "^6.0.2",
|
||||
"@codemirror/lang-yaml": "^6.1.3",
|
||||
"@codemirror/language": "^6.13.1",
|
||||
"@codemirror/lint": "^6.9.7",
|
||||
"@codemirror/state": "^6.7.6",
|
||||
"@codemirror/view": "^6.43.14",
|
||||
"@lezer/highlight": "^1.2.5",
|
||||
|
|
|
|||
3
ui/pnpm-lock.yaml
generated
3
ui/pnpm-lock.yaml
generated
|
|
@ -32,6 +32,9 @@ importers:
|
|||
'@codemirror/language':
|
||||
specifier: ^6.13.1
|
||||
version: 6.13.1
|
||||
'@codemirror/lint':
|
||||
specifier: ^6.9.7
|
||||
version: 6.9.7
|
||||
'@codemirror/state':
|
||||
specifier: ^6.7.6
|
||||
version: 6.7.6
|
||||
|
|
|
|||
|
|
@ -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" },
|
||||
|
|
|
|||
|
|
@ -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)];
|
||||
}
|
||||
|
|
|
|||
212
ui/src/components/editor/lint.ts
Normal file
212
ui/src/components/editor/lint.ts
Normal 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)];
|
||||
}
|
||||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -53,6 +53,7 @@ const ITEM_ORDER = [
|
|||
"view.toggleStructure",
|
||||
"find.open",
|
||||
"terminal.open",
|
||||
"problems.open",
|
||||
"settings.open",
|
||||
"goto.fileOpen",
|
||||
"goto.classOpen",
|
||||
|
|
|
|||
374
ui/src/components/problems/ProblemsToolWindow.vue
Normal file
374
ui/src/components/problems/ProblemsToolWindow.vue
Normal 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>
|
||||
341
ui/src/components/problems/problems.ts
Normal file
341
ui/src/components/problems/problems.ts
Normal 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,
|
||||
};
|
||||
});
|
||||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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. */
|
||||
|
|
|
|||
173
ui/tests/editor/lint.test.ts
Normal file
173
ui/tests/editor/lint.test.ts
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
/**
|
||||
* Tests of the editor's diagnostics (M3.3, `lint.ts`): conversion to
|
||||
* CodeMirror positions (CRLF, clamping, order, source and code), the view
|
||||
* plugin applying a path's diagnostics when a view shows the state and on
|
||||
* every publication, clearing, and colours from tokens only.
|
||||
*/
|
||||
import { diagnosticCount, forEachDiagnostic, type Diagnostic } from "@codemirror/lint";
|
||||
import { EditorState, Text } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
clearDiagnostics,
|
||||
diagnosticsOf,
|
||||
lintExtensions,
|
||||
publishDiagnostics,
|
||||
toCodeMirror,
|
||||
type DiagnosticItem,
|
||||
} from "../../src/components/editor/lint";
|
||||
|
||||
/** Views created by a test, destroyed after it. */
|
||||
let views: EditorView[] = [];
|
||||
|
||||
/**
|
||||
* A diagnostic on one line.
|
||||
*
|
||||
* @param line - 0-based line.
|
||||
* @param from - start column.
|
||||
* @param to - end column.
|
||||
* @param extra - fields to override.
|
||||
*/
|
||||
function item(line: number, from: number, to: number, extra: Partial<DiagnosticItem> = {}): DiagnosticItem {
|
||||
return {
|
||||
range: { start: { line, column: from }, end: { line, column: to } },
|
||||
severity: "error",
|
||||
message: `problem at ${String(line)}:${String(from)}`,
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
/** Lets the plugin's microtask run. */
|
||||
async function settle(): Promise<void> {
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
}
|
||||
|
||||
/**
|
||||
* A view showing `doc` as `path`.
|
||||
*
|
||||
* @param path - project-relative path.
|
||||
* @param doc - the text.
|
||||
*/
|
||||
function viewOf(path: string, doc: string): EditorView {
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({ doc, extensions: lintExtensions(path) }),
|
||||
parent: document.body,
|
||||
});
|
||||
views.push(view);
|
||||
return view;
|
||||
}
|
||||
|
||||
/**
|
||||
* The diagnostics in a state.
|
||||
*
|
||||
* @param state - the editor state.
|
||||
*/
|
||||
function shown(state: EditorState): Diagnostic[] {
|
||||
const out: Diagnostic[] = [];
|
||||
forEachDiagnostic(state, (d, from, to) => out.push({ ...d, from, to }));
|
||||
return out;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const view of views) {
|
||||
view.destroy();
|
||||
}
|
||||
views = [];
|
||||
clearDiagnostics();
|
||||
});
|
||||
|
||||
describe("toCodeMirror", () => {
|
||||
it("converts lines and UTF-16 columns, CRLF-safe and clamped", () => {
|
||||
const doc = Text.of(["<?php", "echo 🦦 $x;", "end"]);
|
||||
const out = toCodeMirror(doc, [
|
||||
item(1, 8, 10, { severity: "warning", source: "phpactor", code: "W1" }),
|
||||
item(0, 0, 3),
|
||||
item(9, 0, 99, { severity: "hint" }),
|
||||
item(2, 2, 1, { severity: "info" }),
|
||||
]);
|
||||
expect(out.map((d) => [d.from, d.to, d.severity])).toEqual([
|
||||
[0, 3, "error"],
|
||||
[14, 16, "warning"],
|
||||
[18, 21, "hint"],
|
||||
[20, 20, "info"],
|
||||
]);
|
||||
expect(out[1]?.source).toBe("phpactor W1");
|
||||
expect(out[0]?.source).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("lintExtensions", () => {
|
||||
it("shows a file's diagnostics and follows every publication", async () => {
|
||||
publishDiagnostics("a.php", [item(1, 0, 4)]);
|
||||
const view = viewOf("a.php", "<?php\necho 1;\n");
|
||||
await settle();
|
||||
expect(shown(view.state).map((d) => [d.from, d.to, d.message])).toEqual([[6, 10, "problem at 1:0"]]);
|
||||
expect(view.dom.querySelector(".cm-lintRange-error")).not.toBeNull();
|
||||
expect(view.dom.querySelector(".cm-gutter-lint .cm-lint-marker-error")).not.toBeNull();
|
||||
|
||||
publishDiagnostics("a.php", [item(0, 0, 5, { severity: "warning" }), item(1, 5, 6)]);
|
||||
expect(diagnosticCount(view.state)).toBe(2);
|
||||
expect(view.dom.querySelector(".cm-lintRange-warning")).not.toBeNull();
|
||||
|
||||
publishDiagnostics("other.php", [item(0, 0, 1)]);
|
||||
expect(diagnosticCount(view.state)).toBe(2);
|
||||
|
||||
publishDiagnostics("a.php", []);
|
||||
expect(diagnosticCount(view.state)).toBe(0);
|
||||
expect(diagnosticsOf("a.php")).toEqual([]);
|
||||
});
|
||||
|
||||
it("brings a background state up to date when it is shown again", async () => {
|
||||
const view = viewOf("a.php", "<?php\n");
|
||||
await settle();
|
||||
const background = view.state;
|
||||
view.setState(EditorState.create({ doc: "x", extensions: lintExtensions("b.php") }));
|
||||
publishDiagnostics("a.php", [item(0, 0, 5)]);
|
||||
expect(diagnosticCount(view.state)).toBe(0);
|
||||
view.setState(background);
|
||||
await settle();
|
||||
expect(diagnosticCount(view.state)).toBe(1);
|
||||
});
|
||||
|
||||
it("maps diagnostics through edits until the next publication", async () => {
|
||||
publishDiagnostics("a.php", [item(0, 6, 10)]);
|
||||
const view = viewOf("a.php", "<?php echo;");
|
||||
await settle();
|
||||
view.dispatch({ changes: { from: 0, insert: "\n\n" } });
|
||||
expect(shown(view.state).map((d) => [d.from, d.to])).toEqual([[8, 12]]);
|
||||
});
|
||||
|
||||
it("clears every file on clearDiagnostics", async () => {
|
||||
publishDiagnostics("a.php", [item(0, 0, 1)]);
|
||||
const view = viewOf("a.php", "<?php");
|
||||
await settle();
|
||||
expect(diagnosticCount(view.state)).toBe(1);
|
||||
clearDiagnostics();
|
||||
expect(diagnosticCount(view.state)).toBe(0);
|
||||
});
|
||||
|
||||
it("stops listening when the view is destroyed", async () => {
|
||||
const view = viewOf("a.php", "<?php");
|
||||
await settle();
|
||||
view.destroy();
|
||||
views = [];
|
||||
expect(() => {
|
||||
publishDiagnostics("a.php", [item(0, 0, 1)]);
|
||||
}).not.toThrow();
|
||||
});
|
||||
|
||||
it("adds nothing without a path", () => {
|
||||
expect(lintExtensions("")).toEqual([]);
|
||||
});
|
||||
|
||||
it("takes its colours from tokens only", () => {
|
||||
const source = readFileSync(join(import.meta.dirname, "..", "..", "src", "components", "editor", "lint.ts"), "utf8");
|
||||
expect(source).not.toMatch(/#[0-9a-fA-F]{3,8}\b|rgba?\(|hsla?\(/);
|
||||
for (const colour of source.matchAll(/var\((--[a-z0-9-]+)\)/g)) {
|
||||
expect(colour[1]).toMatch(/^--lt-/);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
@ -48,6 +48,7 @@ const usedKeys = sourceFiles(SRC).flatMap((file) =>
|
|||
*/
|
||||
const RUNTIME_KEYS = new Set([
|
||||
"notification.command.failed",
|
||||
"notification.lsp.failed",
|
||||
"notification.project.notLocal",
|
||||
"notification.project.openFailed",
|
||||
"notification.project.unsavedChanges",
|
||||
|
|
@ -140,7 +141,7 @@ describe("en.json", () => {
|
|||
it("uses flat dotted keys of known areas with string values", () => {
|
||||
for (const [key, value] of Object.entries(en)) {
|
||||
expect(key).toMatch(
|
||||
/^(app|command|project|editor|common|palette|theme|recovery|notification|settings|find|goto|structure|menu|terminal)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/,
|
||||
/^(app|command|project|editor|common|palette|theme|recovery|notification|settings|find|goto|structure|menu|terminal|problems)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/,
|
||||
);
|
||||
expect(typeof value).toBe("string");
|
||||
expect(value.trim()).not.toBe("");
|
||||
|
|
|
|||
|
|
@ -267,6 +267,7 @@ describe("AppMenu", () => {
|
|||
"view.toggleStructure",
|
||||
"find.open",
|
||||
"terminal.open",
|
||||
"problems.open",
|
||||
"settings.open",
|
||||
"goto.fileOpen",
|
||||
"goto.classOpen",
|
||||
|
|
|
|||
|
|
@ -266,6 +266,7 @@ describe("CommandPalette", () => {
|
|||
"goto.symbolOpen",
|
||||
"project.openDialog",
|
||||
"menu.open",
|
||||
"problems.open",
|
||||
"app.quit",
|
||||
"editor.reveal",
|
||||
"settings.open",
|
||||
|
|
|
|||
300
ui/tests/problems/ProblemsToolWindow.test.ts
Normal file
300
ui/tests/problems/ProblemsToolWindow.test.ts
Normal file
|
|
@ -0,0 +1,300 @@
|
|||
/**
|
||||
* 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);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue