PM: merge H3 Phpactor UX: fast indexing tick, progress, messages, php -l
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
ac007a7d59
21 changed files with 1752 additions and 48 deletions
1
Cargo.lock
generated
1
Cargo.lock
generated
|
|
@ -2629,6 +2629,7 @@ version = "0.0.0"
|
|||
dependencies = [
|
||||
"lutra-index",
|
||||
"lutra-lsp",
|
||||
"lutra-proc",
|
||||
"lutra-search",
|
||||
"lutra-syntax",
|
||||
"lutra-terminal",
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ layer = 4
|
|||
[dependencies]
|
||||
lutra-index.workspace = true
|
||||
lutra-lsp.workspace = true
|
||||
lutra-proc.workspace = true
|
||||
lutra-search.workspace = true
|
||||
lutra-syntax.workspace = true
|
||||
lutra-terminal.workspace = true
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
//! Language server commands of M3.3: `diagnostics.list`, `lsp.status` and
|
||||
//! `lsp.restart`. The wiring itself lives in [`crate::lsp`].
|
||||
//! `lsp.restart`, and `lsp.log` (H3). The wiring itself lives in
|
||||
//! [`crate::lsp`].
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
|
|
@ -16,6 +17,7 @@ pub fn register(registry: &mut Registry) -> Result<(), EngineError> {
|
|||
registry.register(Box::new(List))?;
|
||||
registry.register(Box::new(Status))?;
|
||||
registry.register(Box::new(Restart))?;
|
||||
registry.register(Box::new(Log))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -70,15 +72,20 @@ impl Command for 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)",
|
||||
params: "none; returns { state: starting|ready|restarting|failed|stopped, message?, startupMs?, progress: { active, title?, message?, percentage? } } (startupMs: from start to the first ready; progress: the newest running work-done progress task, as lspProgress reports it)",
|
||||
}
|
||||
}
|
||||
|
||||
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));
|
||||
let progress = serde_json::to_value(state.lsp.progress())
|
||||
.map_err(|e| EngineError::Internal(e.to_string()))?;
|
||||
if let Some(object) = value.as_object_mut() {
|
||||
if let Some(ms) = state.lsp.startup_ms() {
|
||||
object.insert("startupMs".into(), Value::from(ms));
|
||||
}
|
||||
object.insert("progress".into(), progress);
|
||||
}
|
||||
Ok(Outcome::value(value))
|
||||
}
|
||||
|
|
@ -108,3 +115,23 @@ impl Command for Restart {
|
|||
Ok(Outcome::value(Value::Null))
|
||||
}
|
||||
}
|
||||
|
||||
/// `lsp.log`: the language server's recent messages, log messages and
|
||||
/// stderr lines, oldest first.
|
||||
pub struct Log;
|
||||
|
||||
impl Command for Log {
|
||||
fn spec(&self) -> &CommandSpec {
|
||||
&CommandSpec {
|
||||
id: "lsp.log",
|
||||
label: "Show PHP Language Server Log",
|
||||
menu_path: None,
|
||||
default_shortcut: None,
|
||||
params: "none; returns { lines: string[] }, oldest first, at most 1000: \"[level] text\" for window/logMessage, \"[show level] text\" for window/showMessage, \"[stderr] text\" for stderr lines",
|
||||
}
|
||||
}
|
||||
|
||||
fn run(&self, state: &mut State, _params: Value) -> Result<Outcome, EngineError> {
|
||||
Ok(Outcome::value(json!({ "lines": state.lsp.log() })))
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -260,6 +260,13 @@ impl Engine {
|
|||
self.state.lsp.set_launch(launch);
|
||||
}
|
||||
|
||||
/// Runs `php -l` with `php` on every platform, or never with `None`,
|
||||
/// instead of the default (the toolchain's PHP on Windows only); see
|
||||
/// [`crate::lsp::php_lint`].
|
||||
pub fn set_php_lint(&mut self, php: Option<std::path::PathBuf>) {
|
||||
self.state.lsp.set_php_lint(php);
|
||||
}
|
||||
|
||||
/// Read access to the state.
|
||||
pub fn state(&self) -> &State {
|
||||
&self.state
|
||||
|
|
@ -488,6 +495,7 @@ mod tests {
|
|||
"lsp.completion",
|
||||
"lsp.definition",
|
||||
"lsp.hover",
|
||||
"lsp.log",
|
||||
"lsp.prepareRename",
|
||||
"lsp.references",
|
||||
"lsp.rename",
|
||||
|
|
|
|||
|
|
@ -205,6 +205,8 @@ pub enum Event {
|
|||
DiagnosticsChanged(crate::lsp::FileDiagnostics),
|
||||
/// The Git repository may have changed: `{available, repo, filesChanged}`; refetch `git.status` (M4.1).
|
||||
GitChanged(crate::cmd::git::GitChanged),
|
||||
/// The language server's newest work-done progress task: `{active, title?, message?, percentage?}`; `active: false` when none runs.
|
||||
LspProgress(crate::lsp::LspProgress),
|
||||
/// Terminal events (`terminalOutput`, `terminalExited`), see [`crate::cmd::terminal`].
|
||||
#[serde(untagged)]
|
||||
Terminal(crate::cmd::terminal::TerminalEvent),
|
||||
|
|
|
|||
|
|
@ -30,17 +30,31 @@
|
|||
//! 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.
|
||||
//!
|
||||
//! Phpactor UX (H3):
|
||||
//! - `$/progress` (work-done progress) becomes `lspProgress` with the
|
||||
//! newest running task, and while any task runs the session ticks fast
|
||||
//! ([`tick_interval`]).
|
||||
//! - `window/showMessage` becomes a notification (`notification.lsp.message`,
|
||||
//! a repeated text at most once per [`MESSAGE_REPEAT`]); it,
|
||||
//! `window/logMessage` and the server's stderr go to a bounded log
|
||||
//! (`lsp.log`).
|
||||
//! - [`php_lint`] runs `php -l` on open and save where Phpactor's own lint
|
||||
//! cannot (Windows); its diagnostics are merged into `diagnosticsChanged`
|
||||
//! with `source: "php -l"`.
|
||||
|
||||
pub mod php_lint;
|
||||
pub mod session;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, VecDeque};
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::Receiver;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use lutra_lsp::{PublishDiagnostics, Server, ServerEvent, Severity, Status};
|
||||
use lutra_lsp::{MessageLevel, PublishDiagnostics, Server, ServerEvent, Severity, Status};
|
||||
use lutra_text::{Edit, Position};
|
||||
use serde::Serialize;
|
||||
use serde_json::{Map, Value};
|
||||
|
|
@ -62,6 +76,17 @@ pub const MAX_EVENTS_PER_PUMP: usize = 2_000;
|
|||
/// ignored until others clear.
|
||||
pub const MAX_FILES: usize = 10_000;
|
||||
|
||||
/// Most lines kept in the language server log (`lsp.log`); older lines
|
||||
/// are dropped.
|
||||
pub const MAX_LOG_LINES: usize = 1_000;
|
||||
|
||||
/// Most work-done progress tasks tracked at once; further `begin`s are
|
||||
/// ignored until others end.
|
||||
pub const MAX_PROGRESS_TASKS: usize = 32;
|
||||
|
||||
/// How long the same `window/showMessage` text is not shown again.
|
||||
pub const MESSAGE_REPEAT: Duration = Duration::from_secs(30);
|
||||
|
||||
/// The state of the language server as `lspStatus` and `lsp.status`
|
||||
/// report it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
|
|
@ -168,6 +193,33 @@ pub struct DiagnosticItem {
|
|||
pub code: Option<String>,
|
||||
}
|
||||
|
||||
/// The payload of `lspProgress`: the newest running work-done progress
|
||||
/// task of the language server, or none.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
|
||||
pub struct LspProgress {
|
||||
/// Whether a task runs; the other fields are absent when not.
|
||||
pub active: bool,
|
||||
/// Its title (`Indexing workspace`), at most 200 characters.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub title: Option<String>,
|
||||
/// Its latest message (`500/2000 (25.00%, 60MB)`), at most 500
|
||||
/// characters.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub message: Option<String>,
|
||||
/// Its percentage, 0–100, when the server gives one.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub percentage: Option<u32>,
|
||||
}
|
||||
|
||||
/// One running work-done progress task.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct ProgressTask {
|
||||
/// The token, as JSON text.
|
||||
token: String,
|
||||
/// Title, message and percentage as last reported.
|
||||
progress: LspProgress,
|
||||
}
|
||||
|
||||
/// The payload of `diagnosticsChanged`, and one file of
|
||||
/// `diagnostics.list`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
|
|
@ -191,6 +243,14 @@ pub struct Lsp {
|
|||
diagnostics: BTreeMap<String, Vec<DiagnosticItem>>,
|
||||
/// Set by [`shutdown_now`] (`app.quit`): no session starts any more.
|
||||
quitting: bool,
|
||||
/// Running work-done progress tasks, oldest first.
|
||||
progress: Vec<ProgressTask>,
|
||||
/// The server's log: messages, log messages and stderr lines.
|
||||
log: VecDeque<String>,
|
||||
/// The last `window/showMessage` text shown, and when.
|
||||
last_message: Option<(String, Instant)>,
|
||||
/// Lutra's own `php -l`.
|
||||
lint: php_lint::PhpLint,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Lsp {
|
||||
|
|
@ -200,6 +260,8 @@ impl std::fmt::Debug for Lsp {
|
|||
.field("running", &self.active.is_some())
|
||||
.field("status", &self.status)
|
||||
.field("files_with_diagnostics", &self.diagnostics.len())
|
||||
.field("progress", &self.progress.len())
|
||||
.field("lint", &self.lint)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
|
@ -223,19 +285,53 @@ impl Lsp {
|
|||
self.active.as_ref().and_then(|a| a.ready_ms)
|
||||
}
|
||||
|
||||
/// Uses `php` for [`php_lint`] on every platform (tests), `None` to
|
||||
/// turn it off, instead of the default: on Windows the toolchain's PHP,
|
||||
/// elsewhere off (Phpactor lints there itself).
|
||||
pub fn set_php_lint(&mut self, php: Option<PathBuf>) {
|
||||
self.lint.set_php(php);
|
||||
}
|
||||
|
||||
/// The diagnostics of one file (project-relative, `/`), or of every
|
||||
/// file, sorted by path.
|
||||
/// file, sorted by path: the server's, then those of `php -l`.
|
||||
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 {
|
||||
let mut paths: Vec<&String> = self
|
||||
.diagnostics
|
||||
.keys()
|
||||
.chain(self.lint.paths())
|
||||
.filter(|p| path.is_none_or(|want| want == p.as_str()))
|
||||
.collect();
|
||||
paths.sort();
|
||||
paths.dedup();
|
||||
paths
|
||||
.into_iter()
|
||||
.map(|p| FileDiagnostics {
|
||||
path: p.clone(),
|
||||
items: items.clone(),
|
||||
items: self.merged(p),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The server's diagnostics of `path` followed by those of `php -l`.
|
||||
fn merged(&self, path: &str) -> Vec<DiagnosticItem> {
|
||||
let mut items = self.diagnostics.get(path).cloned().unwrap_or_default();
|
||||
items.extend(self.lint.items(path).iter().cloned());
|
||||
items
|
||||
}
|
||||
|
||||
/// The newest running work-done progress task, or an inactive value.
|
||||
pub fn progress(&self) -> LspProgress {
|
||||
self.progress
|
||||
.last()
|
||||
.map(|t| t.progress.clone())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The server's log, oldest line first (at most [`MAX_LOG_LINES`]).
|
||||
pub fn log(&self) -> Vec<String> {
|
||||
self.log.iter().cloned().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>> {
|
||||
|
|
@ -281,6 +377,9 @@ struct Active {
|
|||
ready_ms: Option<u64>,
|
||||
/// Synced buffers.
|
||||
docs: BTreeMap<BufferId, Doc>,
|
||||
/// Set while the server reports work-done progress; the session
|
||||
/// thread ticks fast then.
|
||||
indexing: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
/// Queues `f` on the session thread, after every document change queued
|
||||
|
|
@ -340,6 +439,7 @@ pub fn pump(state: &mut State) {
|
|||
start(state, key);
|
||||
}
|
||||
}
|
||||
php_lint::pump(state);
|
||||
if state.lsp.active.is_none() {
|
||||
return;
|
||||
}
|
||||
|
|
@ -375,6 +475,7 @@ pub fn shutdown_now(state: &mut State) {
|
|||
drop(events);
|
||||
session.join();
|
||||
clear_diagnostics(state);
|
||||
clear_progress(state);
|
||||
set_status(state, LspState::Stopped, None);
|
||||
}
|
||||
|
||||
|
|
@ -462,6 +563,39 @@ pub const TICK_METHOD: &str = "$/lutra/tick";
|
|||
/// (from its own thread, independent of the host's pump).
|
||||
pub const TICK_INTERVAL: Duration = Duration::from_millis(25);
|
||||
|
||||
/// The tick while the server indexes or the session is young
|
||||
/// ([`tick_interval`]). Phpactor's indexer waits for a 1 ms timer after
|
||||
/// every file, which only fires when a message arrives, so it indexes one
|
||||
/// file per tick. Measured on 2,000 classes (Windows 11, debug build),
|
||||
/// project open to the first useful completion: 71.6 s with the 25 ms
|
||||
/// tick, 29.9 s at 5 ms, 23.8–26.9 s at 2 ms, 20.7–22.6 s at 1 ms. The
|
||||
/// price while the window runs and Phpactor is idle: about 10% of a core
|
||||
/// for Phpactor and 4.5% for Lutra's session thread at 1 ms (9% and 3% at
|
||||
/// 2 ms).
|
||||
pub const FAST_TICK_INTERVAL: Duration = Duration::from_millis(1);
|
||||
|
||||
/// How long after its start a session ticks fast even without progress
|
||||
/// reports: Phpactor's first indexing and analysis run then.
|
||||
pub const STARTUP_WINDOW: Duration = Duration::from_secs(120);
|
||||
|
||||
/// The tick interval of a session whose normal interval is `base`: fast
|
||||
/// ([`FAST_TICK_INTERVAL`], or `base` if that is shorter) while the server
|
||||
/// reports work-done progress (`indexing`) or during the first
|
||||
/// [`STARTUP_WINDOW`]; `base` otherwise. A session without ticks (`base`
|
||||
/// is `None`) gets none.
|
||||
pub fn tick_interval(
|
||||
base: Option<Duration>,
|
||||
indexing: bool,
|
||||
since_start: Duration,
|
||||
) -> Option<Duration> {
|
||||
let base = base?;
|
||||
if indexing || since_start < STARTUP_WINDOW {
|
||||
Some(base.min(FAST_TICK_INTERVAL))
|
||||
} else {
|
||||
Some(base)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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).
|
||||
|
|
@ -491,7 +625,8 @@ pub fn tick_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()) {
|
||||
let indexing = Arc::new(AtomicBool::new(false));
|
||||
match Session::start(key.launch.clone(), key.root.clone(), Arc::clone(&indexing)) {
|
||||
Ok(session) => {
|
||||
state.lsp.active = Some(Active {
|
||||
key,
|
||||
|
|
@ -501,6 +636,7 @@ fn start(state: &mut State, key: Key) {
|
|||
started: Instant::now(),
|
||||
ready_ms: None,
|
||||
docs: BTreeMap::new(),
|
||||
indexing,
|
||||
});
|
||||
set_status(state, LspState::Starting, None);
|
||||
}
|
||||
|
|
@ -513,6 +649,7 @@ fn start(state: &mut State, key: Key) {
|
|||
fn stop(state: &mut State) {
|
||||
state.lsp.active = None;
|
||||
clear_diagnostics(state);
|
||||
clear_progress(state);
|
||||
set_status(state, LspState::Stopped, None);
|
||||
}
|
||||
|
||||
|
|
@ -520,6 +657,7 @@ fn stop(state: &mut State) {
|
|||
/// user once.
|
||||
fn fail(state: &mut State, message: String) {
|
||||
clear_diagnostics(state);
|
||||
clear_progress(state);
|
||||
let changed = set_status(state, LspState::Failed, Some(message.clone()));
|
||||
if changed {
|
||||
let mut params = Map::new();
|
||||
|
|
@ -595,11 +733,159 @@ fn drain_events(state: &mut State) {
|
|||
match event {
|
||||
ServerEvent::Status(status) => apply_status(state, status),
|
||||
ServerEvent::Diagnostics(published) => publish(state, published),
|
||||
ServerEvent::ShowMessage { level, message } => show_message(state, level, message),
|
||||
ServerEvent::LogMessage { level, message } => {
|
||||
log(state, &format!("[{}] {message}", level_name(level)));
|
||||
}
|
||||
ServerEvent::Stderr(line) => log(state, &format!("[stderr] {line}")),
|
||||
ServerEvent::Progress { token, value } => progress(state, &token, &value),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The name of a message level in the log.
|
||||
fn level_name(level: MessageLevel) -> &'static str {
|
||||
match level {
|
||||
MessageLevel::Error => "error",
|
||||
MessageLevel::Warning => "warning",
|
||||
MessageLevel::Info => "info",
|
||||
MessageLevel::Log => "log",
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends a line to the server log, dropping the oldest beyond
|
||||
/// [`MAX_LOG_LINES`].
|
||||
fn log(state: &mut State, line: &str) {
|
||||
let log = &mut state.lsp.log;
|
||||
while log.len() >= MAX_LOG_LINES {
|
||||
log.pop_front();
|
||||
}
|
||||
log.push_back(line.to_string());
|
||||
}
|
||||
|
||||
/// Whether a `window/showMessage` text is a known, expected complaint that
|
||||
/// is logged but not shown: Phpactor on Windows reports once per session
|
||||
/// that its PHP lint provider cannot start `php` (`CreateProcess failed`)
|
||||
/// and removes it. Lutra runs `php -l` itself there ([`php_lint`]).
|
||||
pub fn is_hidden_message(message: &str) -> bool {
|
||||
message.contains("Diagnostic provider") && message.contains("CreateProcess failed")
|
||||
}
|
||||
|
||||
/// Shows a `window/showMessage` as a notification of the same level
|
||||
/// (`notification.lsp.message {message}`) and logs it. Hidden texts
|
||||
/// ([`is_hidden_message`]) and a text shown less than [`MESSAGE_REPEAT`]
|
||||
/// ago are only logged.
|
||||
fn show_message(state: &mut State, level: MessageLevel, message: String) {
|
||||
log(state, &format!("[show {}] {message}", level_name(level)));
|
||||
if is_hidden_message(&message) {
|
||||
return;
|
||||
}
|
||||
let now = Instant::now();
|
||||
if let Some((last, at)) = &state.lsp.last_message
|
||||
&& *last == message
|
||||
&& now.saturating_duration_since(*at) < MESSAGE_REPEAT
|
||||
{
|
||||
return;
|
||||
}
|
||||
state.lsp.last_message = Some((message.clone(), now));
|
||||
let level = match level {
|
||||
MessageLevel::Error => NotificationLevel::Error,
|
||||
MessageLevel::Warning => NotificationLevel::Warning,
|
||||
MessageLevel::Info | MessageLevel::Log => NotificationLevel::Info,
|
||||
};
|
||||
let mut params = Map::new();
|
||||
params.insert("message".into(), Value::from(message.clone()));
|
||||
state.notify(
|
||||
level,
|
||||
Some("notification.lsp.message"),
|
||||
Some(format!("PHP language server: {message}")),
|
||||
Some(params),
|
||||
);
|
||||
}
|
||||
|
||||
/// At most `max` characters of `text`.
|
||||
fn capped(text: &str, max: usize) -> String {
|
||||
text.chars().take(max).collect()
|
||||
}
|
||||
|
||||
/// Applies one `$/progress` notification (`begin`, `report` or `end` of
|
||||
/// work-done progress) and queues `lspProgress` when the shown task
|
||||
/// changed. Values of other shapes are ignored.
|
||||
fn progress(state: &mut State, token: &Value, value: &Value) {
|
||||
let token = token.to_string();
|
||||
let text = |key: &str, max: usize| {
|
||||
value
|
||||
.get(key)
|
||||
.and_then(Value::as_str)
|
||||
.map(|t| capped(t, max))
|
||||
};
|
||||
let percentage = value
|
||||
.get("percentage")
|
||||
.and_then(Value::as_u64)
|
||||
.map(|p| u32::try_from(p.min(100)).unwrap_or(100));
|
||||
let before = state.lsp.progress();
|
||||
let tasks = &mut state.lsp.progress;
|
||||
let existing = tasks.iter().position(|t| t.token == token);
|
||||
match value.get("kind").and_then(Value::as_str) {
|
||||
Some("begin") => {
|
||||
if let Some(i) = existing {
|
||||
tasks.remove(i);
|
||||
} else if tasks.len() >= MAX_PROGRESS_TASKS {
|
||||
return;
|
||||
}
|
||||
tasks.push(ProgressTask {
|
||||
token,
|
||||
progress: LspProgress {
|
||||
active: true,
|
||||
title: Some(text("title", 200).unwrap_or_default()),
|
||||
message: text("message", 500),
|
||||
percentage,
|
||||
},
|
||||
});
|
||||
}
|
||||
Some("report") => {
|
||||
let Some(task) = existing.and_then(|i| tasks.get_mut(i)) else {
|
||||
return;
|
||||
};
|
||||
if let Some(message) = text("message", 500) {
|
||||
task.progress.message = Some(message);
|
||||
}
|
||||
if percentage.is_some() {
|
||||
task.progress.percentage = percentage;
|
||||
}
|
||||
}
|
||||
Some("end") => {
|
||||
if let Some(i) = existing {
|
||||
tasks.remove(i);
|
||||
}
|
||||
}
|
||||
_ => return,
|
||||
}
|
||||
progress_changed(state, before);
|
||||
}
|
||||
|
||||
/// Updates the session's fast-tick flag and queues `lspProgress` if the
|
||||
/// shown task differs from `before`.
|
||||
fn progress_changed(state: &mut State, before: LspProgress) {
|
||||
let running = !state.lsp.progress.is_empty();
|
||||
if let Some(active) = &state.lsp.active {
|
||||
active.indexing.store(running, Ordering::Relaxed);
|
||||
}
|
||||
let now = state.lsp.progress();
|
||||
if now != before {
|
||||
state.emit(Event::LspProgress(now));
|
||||
}
|
||||
}
|
||||
|
||||
/// Forgets every progress task (the session ended or restarts), queuing
|
||||
/// an inactive `lspProgress` if one was shown.
|
||||
fn clear_progress(state: &mut State) {
|
||||
let before = state.lsp.progress();
|
||||
state.lsp.progress.clear();
|
||||
progress_changed(state, before);
|
||||
}
|
||||
|
||||
/// Maps a client status onto `lspStatus`.
|
||||
fn apply_status(state: &mut State, status: Status) {
|
||||
match status {
|
||||
|
|
@ -616,11 +902,13 @@ fn apply_status(state: &mut State, status: Status) {
|
|||
set_status(state, LspState::Ready, None);
|
||||
}
|
||||
Status::Restarting { reason, .. } => {
|
||||
clear_progress(state);
|
||||
set_status(state, LspState::Restarting, Some(reason));
|
||||
}
|
||||
Status::Failed { message } => fail(state, message),
|
||||
Status::Stopped => {
|
||||
clear_diagnostics(state);
|
||||
clear_progress(state);
|
||||
set_status(state, LspState::Stopped, None);
|
||||
}
|
||||
}
|
||||
|
|
@ -662,20 +950,24 @@ fn publish(state: &mut State, published: PublishDiagnostics) {
|
|||
if !diagnostics.contains_key(&path) && diagnostics.len() >= MAX_FILES {
|
||||
return;
|
||||
}
|
||||
diagnostics.insert(path.clone(), items.clone());
|
||||
diagnostics.insert(path.clone(), items);
|
||||
}
|
||||
emit_diagnostics(state, path);
|
||||
}
|
||||
|
||||
/// Queues `diagnosticsChanged` for `path` with the merged list of the
|
||||
/// server and `php -l` (empty when neither has any).
|
||||
fn emit_diagnostics(state: &mut State, path: String) {
|
||||
let items = state.lsp.merged(&path);
|
||||
state.emit(Event::DiagnosticsChanged(FileDiagnostics { path, items }));
|
||||
}
|
||||
|
||||
/// Drops every diagnostic, queuing an empty `diagnosticsChanged` per file
|
||||
/// that had some.
|
||||
/// Drops every diagnostic of the server, queuing a `diagnosticsChanged`
|
||||
/// per file that had some (empty, or only those of `php -l`).
|
||||
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(),
|
||||
}));
|
||||
emit_diagnostics(state, path);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -785,7 +1077,8 @@ mod tests {
|
|||
use std::time::{Duration, Instant};
|
||||
|
||||
use super::{
|
||||
DiagnosticSeverity, TICK_INTERVAL, TICK_WINDOW, phpactor_launch, relative, tick_due,
|
||||
DiagnosticSeverity, FAST_TICK_INTERVAL, STARTUP_WINDOW, TICK_INTERVAL, TICK_WINDOW,
|
||||
is_hidden_message, phpactor_launch, relative, tick_due, tick_interval,
|
||||
};
|
||||
use lutra_lsp::Severity;
|
||||
|
||||
|
|
@ -865,4 +1158,30 @@ mod tests {
|
|||
));
|
||||
assert!(tick_due(tick, true, recent, Some(now - TICK_INTERVAL), now));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ticks_fast_while_indexing_or_young() {
|
||||
let base = Some(TICK_INTERVAL);
|
||||
let young = Duration::from_secs(5);
|
||||
let old = STARTUP_WINDOW + Duration::from_secs(1);
|
||||
assert_eq!(tick_interval(base, false, young), Some(FAST_TICK_INTERVAL));
|
||||
assert_eq!(tick_interval(base, true, old), Some(FAST_TICK_INTERVAL));
|
||||
assert_eq!(tick_interval(base, false, old), base);
|
||||
assert_eq!(tick_interval(None, true, young), None);
|
||||
let tiny = Some(Duration::from_micros(100));
|
||||
assert_eq!(tick_interval(tiny, true, young), tiny);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hides_only_the_known_lint_provider_complaint() {
|
||||
assert!(is_hidden_message(
|
||||
"Diagnostic provider \"php\" errored with \"CreateProcess failed\", removing from pool"
|
||||
));
|
||||
assert!(!is_hidden_message(
|
||||
"File watcher died: CreateProcess failed"
|
||||
));
|
||||
assert!(!is_hidden_message(
|
||||
"Diagnostic provider \"phpstan\" errored"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
456
crates/engine/src/lsp/php_lint.rs
Normal file
456
crates/engine/src/lsp/php_lint.rs
Normal file
|
|
@ -0,0 +1,456 @@
|
|||
//! Lutra's own `php -l` (H3): syntax errors of open PHP files where
|
||||
//! Phpactor cannot lint them.
|
||||
//!
|
||||
//! Phpactor 2026.06.25.0 on Windows cannot start subprocesses (see
|
||||
//! [`super::phpactor_launch`]), so its PHP lint provider removes itself and
|
||||
//! syntax errors only showed up as Phpactor's own parse diagnostics. Lutra
|
||||
//! therefore runs `php -l` itself there:
|
||||
//! - **When:** for every open PHP buffer when it is first seen and after
|
||||
//! every save (the saved version moved and the buffer is clean). Only on
|
||||
//! Windows by default, with the toolchain's PHP; elsewhere Phpactor lints
|
||||
//! itself. [`PhpLint::set_php`] (`Engine::set_php_lint`) overrides it.
|
||||
//! - **How:** on one worker thread, never under the engine lock. The pump
|
||||
//! hands over a cheap rope snapshot; the worker runs
|
||||
//! `php -n -l -d display_errors=1 -d log_errors=0` through
|
||||
//! [`lutra_proc::spawn`] (so PHP dies with Lutra), writes the text to its
|
||||
//! standard input and reads at most [`MAX_OUTPUT`] bytes of its output,
|
||||
//! killing it after [`TIMEOUT`]. Queued runs of the same file collapse to
|
||||
//! the newest. Files over [`MAX_BYTES`] are skipped.
|
||||
//! - **Result:** `Parse error` and `Fatal error` lines become error
|
||||
//! diagnostics on the whole reported line with `source: "php -l"`
|
||||
//! ([`parse_output`]). The pump stores them per file and merges them
|
||||
//! into `diagnosticsChanged` and `diagnostics.list` after the server's.
|
||||
//! They stay until the next run of that file and are dropped when the
|
||||
//! project closes. A PHP that cannot run gives no diagnostics.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{Read, Write};
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::mpsc::{self, Receiver, Sender};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use lutra_text::Buffer;
|
||||
|
||||
use super::{DiagnosticItem, DiagnosticSeverity, LinePosition, LineRange, MAX_FILES};
|
||||
use crate::State;
|
||||
use crate::buffers::BufferId;
|
||||
use crate::workspace::path_string;
|
||||
|
||||
/// The `source` of `php -l` diagnostics.
|
||||
pub const SOURCE: &str = "php -l";
|
||||
|
||||
/// How long one `php -l` may run before it is killed.
|
||||
pub const TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
/// Largest text linted, in bytes.
|
||||
pub const MAX_BYTES: usize = 8 * 1024 * 1024;
|
||||
|
||||
/// Most output bytes read from one run.
|
||||
pub const MAX_OUTPUT: u64 = 64 * 1024;
|
||||
|
||||
/// Most diagnostics kept per file.
|
||||
pub const MAX_ITEMS: usize = 100;
|
||||
|
||||
/// Longest message kept, in characters.
|
||||
const MAX_MESSAGE: usize = 8 * 1024;
|
||||
|
||||
/// Which PHP lints.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
enum Php {
|
||||
/// The toolchain's PHP on Windows; off elsewhere.
|
||||
#[default]
|
||||
Auto,
|
||||
/// Off.
|
||||
Off,
|
||||
/// This executable, on every platform.
|
||||
With(PathBuf),
|
||||
}
|
||||
|
||||
/// One file to lint.
|
||||
struct Job {
|
||||
/// The PHP executable.
|
||||
php: PathBuf,
|
||||
/// Project-relative path with `/`.
|
||||
path: String,
|
||||
/// The text, as saved.
|
||||
text: Buffer,
|
||||
}
|
||||
|
||||
/// The diagnostics of one run.
|
||||
struct Linted {
|
||||
/// Project-relative path with `/`.
|
||||
path: String,
|
||||
/// What PHP reported; empty for a clean file or a run that failed.
|
||||
items: Vec<DiagnosticItem>,
|
||||
}
|
||||
|
||||
/// The worker thread's queues.
|
||||
struct Worker {
|
||||
/// Jobs to the worker; dropping it ends the thread.
|
||||
jobs: Sender<Job>,
|
||||
/// Results from it.
|
||||
results: Receiver<Linted>,
|
||||
}
|
||||
|
||||
/// The `php -l` state of the engine.
|
||||
#[derive(Default)]
|
||||
pub struct PhpLint {
|
||||
/// Which PHP lints.
|
||||
php: Php,
|
||||
/// The worker, started on the first job.
|
||||
worker: Option<Worker>,
|
||||
/// The project root the results belong to.
|
||||
root: Option<PathBuf>,
|
||||
/// The saved version of each buffer last linted.
|
||||
seen: BTreeMap<BufferId, u64>,
|
||||
/// Diagnostics by project-relative path; clean files are absent.
|
||||
items: BTreeMap<String, Vec<DiagnosticItem>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for PhpLint {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("PhpLint")
|
||||
.field("php", &self.php)
|
||||
.field("running", &self.worker.is_some())
|
||||
.field("files_with_errors", &self.items.len())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl PhpLint {
|
||||
/// Lints with `php` on every platform, or never with `None`.
|
||||
pub fn set_php(&mut self, php: Option<PathBuf>) {
|
||||
self.php = php.map_or(Php::Off, Php::With);
|
||||
}
|
||||
|
||||
/// The files with diagnostics.
|
||||
pub fn paths(&self) -> impl Iterator<Item = &String> {
|
||||
self.items.keys()
|
||||
}
|
||||
|
||||
/// The diagnostics of `path` (empty when clean or not linted).
|
||||
pub fn items(&self, path: &str) -> &[DiagnosticItem] {
|
||||
self.items.get(path).map_or(&[], Vec::as_slice)
|
||||
}
|
||||
}
|
||||
|
||||
/// The PHP that lints now, if any.
|
||||
fn php(state: &State) -> Option<PathBuf> {
|
||||
match &state.lsp.lint.php {
|
||||
Php::Off => None,
|
||||
Php::With(path) => Some(path.clone()),
|
||||
Php::Auto if cfg!(windows) => {
|
||||
let status = &state.toolchain.status().php;
|
||||
status
|
||||
.found
|
||||
.then(|| status.path.clone().map(PathBuf::from))?
|
||||
}
|
||||
Php::Auto => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Queues runs for new and saved PHP buffers and applies finished runs.
|
||||
/// Called by [`super::pump`]; never blocks.
|
||||
pub fn pump(state: &mut State) {
|
||||
let root = state
|
||||
.project
|
||||
.as_ref()
|
||||
.map(|p| p.project.root().to_path_buf());
|
||||
if state.lsp.lint.root != root {
|
||||
clear(state);
|
||||
state.lsp.lint.root = root.clone();
|
||||
}
|
||||
apply_results(state);
|
||||
let (Some(_), Some(php)) = (root, php(state)) else {
|
||||
return;
|
||||
};
|
||||
let mut jobs = Vec::new();
|
||||
let State { buffers, lsp, .. } = state;
|
||||
let lint = &mut lsp.lint;
|
||||
lint.seen.retain(|id, _| buffers.get(*id).is_some());
|
||||
for id in buffers.ids() {
|
||||
let Some(open) = buffers.get(id) else {
|
||||
continue;
|
||||
};
|
||||
if !super::is_php(&open.path) || open.dirty() {
|
||||
continue;
|
||||
}
|
||||
if lint.seen.get(&id) == Some(&open.saved_version) {
|
||||
continue;
|
||||
}
|
||||
lint.seen.insert(id, open.saved_version);
|
||||
if open.buffer.len_bytes() > MAX_BYTES {
|
||||
continue;
|
||||
}
|
||||
jobs.push(Job {
|
||||
php: php.clone(),
|
||||
path: path_string(&open.path),
|
||||
text: open.buffer.clone(),
|
||||
});
|
||||
}
|
||||
for job in jobs {
|
||||
send(&mut state.lsp.lint, job);
|
||||
}
|
||||
}
|
||||
|
||||
/// Hands a job to the worker, starting it if needed. A worker that cannot
|
||||
/// be started or has died drops the job: linting is a convenience, and the
|
||||
/// next save tries again.
|
||||
fn send(lint: &mut PhpLint, job: Job) {
|
||||
if lint.worker.is_none() {
|
||||
lint.worker = start();
|
||||
}
|
||||
if let Some(worker) = &lint.worker
|
||||
&& worker.jobs.send(job).is_err()
|
||||
{
|
||||
lint.worker = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the worker thread; `None` if the thread cannot be started.
|
||||
fn start() -> Option<Worker> {
|
||||
let (jobs, queue) = mpsc::channel::<Job>();
|
||||
let (done, results) = mpsc::channel::<Linted>();
|
||||
std::thread::Builder::new()
|
||||
.name("lutra-php-lint".into())
|
||||
.spawn(move || work(&queue, &done))
|
||||
.ok()?;
|
||||
Some(Worker { jobs, results })
|
||||
}
|
||||
|
||||
/// The worker: runs queued jobs until the engine drops its sender,
|
||||
/// collapsing queued runs of one file to the newest. Results that cannot
|
||||
/// be delivered are dropped because the engine stopped listening.
|
||||
fn work(queue: &Receiver<Job>, done: &Sender<Linted>) {
|
||||
while let Ok(first) = queue.recv() {
|
||||
let mut batch = vec![first];
|
||||
while let Ok(job) = queue.try_recv() {
|
||||
batch.retain(|queued| queued.path != job.path);
|
||||
batch.push(job);
|
||||
}
|
||||
for job in batch {
|
||||
let text = job.text.text();
|
||||
let items = run(&job.php, &text)
|
||||
.map(|output| parse_output(&output, &job.text))
|
||||
.unwrap_or_default();
|
||||
if done
|
||||
.send(Linted {
|
||||
path: job.path,
|
||||
items,
|
||||
})
|
||||
.is_err()
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stores finished runs and queues `diagnosticsChanged` for files whose
|
||||
/// diagnostics changed.
|
||||
fn apply_results(state: &mut State) {
|
||||
let mut finished = Vec::new();
|
||||
if let Some(worker) = &state.lsp.lint.worker {
|
||||
while let Ok(linted) = worker.results.try_recv() {
|
||||
finished.push(linted);
|
||||
}
|
||||
}
|
||||
for Linted { path, items } in finished {
|
||||
let stored = &mut state.lsp.lint.items;
|
||||
if items.is_empty() {
|
||||
if stored.remove(&path).is_none() {
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
if stored.get(&path) == Some(&items) {
|
||||
continue;
|
||||
}
|
||||
if !stored.contains_key(&path) && stored.len() >= MAX_FILES {
|
||||
continue;
|
||||
}
|
||||
stored.insert(path.clone(), items);
|
||||
}
|
||||
super::emit_diagnostics(state, path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops every `php -l` diagnostic (the project closed or changed),
|
||||
/// queuing `diagnosticsChanged` for each file that had some, and forgets
|
||||
/// what was linted.
|
||||
fn clear(state: &mut State) {
|
||||
state.lsp.lint.seen.clear();
|
||||
let files = std::mem::take(&mut state.lsp.lint.items);
|
||||
for path in files.into_keys() {
|
||||
super::emit_diagnostics(state, path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `php -l` on `text` and returns its output (standard output, where
|
||||
/// the CLI prints errors with `display_errors=1`).
|
||||
///
|
||||
/// # Errors
|
||||
/// PHP cannot be started, its pipes fail, or it runs longer than
|
||||
/// [`TIMEOUT`] (it is killed then).
|
||||
pub fn run(php: &std::path::Path, text: &str) -> Result<String, String> {
|
||||
let mut command = Command::new(php);
|
||||
command
|
||||
.args(["-n", "-l", "-d", "display_errors=1", "-d", "log_errors=0"])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null());
|
||||
hide_window(&mut command);
|
||||
let mut child = lutra_proc::spawn(command).map_err(|e| e.to_string())?;
|
||||
let stdout = child.stdout.take().ok_or("no output pipe")?;
|
||||
let (tx, rx) = mpsc::channel();
|
||||
std::thread::Builder::new()
|
||||
.name("lutra-php-lint-out".into())
|
||||
.spawn(move || {
|
||||
let mut out = Vec::new();
|
||||
let _ = stdout.take(MAX_OUTPUT).read_to_end(&mut out);
|
||||
let _ = tx.send(out);
|
||||
})
|
||||
.map_err(|e| e.to_string())?;
|
||||
if let Some(mut stdin) = child.stdin.take() {
|
||||
stdin
|
||||
.write_all(text.as_bytes())
|
||||
.map_err(|e| format!("cannot write to php: {e}"))?;
|
||||
}
|
||||
let started = Instant::now();
|
||||
loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(_)) => break,
|
||||
Ok(None) if started.elapsed() >= TIMEOUT => {
|
||||
let _ = child.kill_and_wait();
|
||||
return Err(format!(
|
||||
"php -l did not finish within {} s",
|
||||
TIMEOUT.as_secs()
|
||||
));
|
||||
}
|
||||
Ok(None) => std::thread::sleep(Duration::from_millis(5)),
|
||||
Err(e) => return Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
let out = rx
|
||||
.recv_timeout(Duration::from_secs(1))
|
||||
.map_err(|_| "the output of php -l did not end".to_string())?;
|
||||
Ok(String::from_utf8_lossy(&out).into_owned())
|
||||
}
|
||||
|
||||
/// Keeps a console window from flashing up when the GUI runs PHP on
|
||||
/// Windows (`CREATE_NO_WINDOW`).
|
||||
#[cfg(windows)]
|
||||
fn hide_window(command: &mut Command) {
|
||||
use std::os::windows::process::CommandExt;
|
||||
command.creation_flags(0x0800_0000);
|
||||
}
|
||||
|
||||
/// Nothing to hide outside Windows.
|
||||
#[cfg(not(windows))]
|
||||
fn hide_window(_command: &mut Command) {}
|
||||
|
||||
/// Reads the errors in `php -l` output for `text`: lines like
|
||||
/// `PHP Parse error: syntax error, unexpected token "}" in Standard input code on line 5`
|
||||
/// (with or without the `PHP ` prefix; `Parse error` and `Fatal error`).
|
||||
/// The file name is cut off: `Standard input code` (Lutra lints through
|
||||
/// standard input), else everything after the last ` in `.
|
||||
/// Each becomes an error on the whole reported line (1-based in the
|
||||
/// output, clamped to the text). Other lines (`No syntax errors detected`,
|
||||
/// `Errors parsing …`) are ignored; at most [`MAX_ITEMS`] are read and
|
||||
/// messages are capped at 8 KiB.
|
||||
pub fn parse_output(output: &str, text: &Buffer) -> Vec<DiagnosticItem> {
|
||||
output
|
||||
.lines()
|
||||
.filter_map(|line| {
|
||||
let line = line.trim();
|
||||
let line = line.strip_prefix("PHP ").unwrap_or(line);
|
||||
let rest = line
|
||||
.strip_prefix("Parse error:")
|
||||
.or_else(|| line.strip_prefix("Fatal error:"))?;
|
||||
let (head, number) = rest.rsplit_once(" on line ")?;
|
||||
let number: usize = number.trim().parse().ok()?;
|
||||
let message = head
|
||||
.strip_suffix(" in Standard input code")
|
||||
.or_else(|| head.rsplit_once(" in ").map(|(message, _)| message))
|
||||
.unwrap_or(head)
|
||||
.trim();
|
||||
let last = text.line_count().saturating_sub(1);
|
||||
let row = number.saturating_sub(1).min(last);
|
||||
let width = text
|
||||
.line_text(row)
|
||||
.map(|l| l.encode_utf16().count())
|
||||
.unwrap_or(0);
|
||||
Some(DiagnosticItem {
|
||||
range: LineRange {
|
||||
start: LinePosition {
|
||||
line: row,
|
||||
column: 0,
|
||||
},
|
||||
end: LinePosition {
|
||||
line: row,
|
||||
column: width,
|
||||
},
|
||||
},
|
||||
severity: DiagnosticSeverity::Error,
|
||||
message: super::capped(message, MAX_MESSAGE),
|
||||
source: Some(SOURCE.into()),
|
||||
code: None,
|
||||
})
|
||||
})
|
||||
.take(MAX_ITEMS)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use lutra_text::Buffer;
|
||||
use proptest::prelude::*;
|
||||
|
||||
use super::{MAX_ITEMS, SOURCE, parse_output};
|
||||
use crate::lsp::DiagnosticSeverity;
|
||||
|
||||
#[test]
|
||||
fn reads_parse_and_fatal_errors() {
|
||||
let text = Buffer::new("<?php\n\nfunction f() {\n retur 1;\n}\r\n");
|
||||
let output = "PHP Parse error: syntax error, unexpected integer \"1\" in Standard input code on line 4\nErrors parsing Standard input code\n";
|
||||
let items = parse_output(output, &text);
|
||||
assert_eq!(items.len(), 1);
|
||||
let item = &items[0];
|
||||
assert_eq!(item.message, "syntax error, unexpected integer \"1\"");
|
||||
assert_eq!(item.severity, DiagnosticSeverity::Error);
|
||||
assert_eq!(item.source.as_deref(), Some(SOURCE));
|
||||
assert_eq!((item.range.start.line, item.range.start.column), (3, 0));
|
||||
assert_eq!((item.range.end.line, item.range.end.column), (3, 12));
|
||||
let fatal = parse_output(
|
||||
"\nFatal error: Cannot use x in this context in Standard input code on line 99\n",
|
||||
&text,
|
||||
);
|
||||
assert_eq!(fatal[0].message, "Cannot use x in this context");
|
||||
assert_eq!(fatal[0].range.start.line, 5);
|
||||
let named = parse_output("Parse error: oops in C:\\p\\a.php on line 1", &text);
|
||||
assert_eq!(named[0].message, "oops");
|
||||
assert!(
|
||||
parse_output("No syntax errors detected in Standard input code\n", &text).is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn columns_count_utf16() {
|
||||
let text = Buffer::new("<?php\n$a = '😀' +;\n");
|
||||
let items = parse_output("Parse error: x in - on line 2", &text);
|
||||
assert_eq!(items[0].range.end.column, 12);
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#[test]
|
||||
fn never_panics_and_stays_in_the_text(output in ".{0,400}", text in ".{0,200}", n in 0usize..1000) {
|
||||
let buffer = Buffer::new(&text);
|
||||
let output = format!("{output}\nParse error: {output} in x on line {n}\n");
|
||||
let items = parse_output(&output, &buffer);
|
||||
prop_assert!(items.len() <= MAX_ITEMS);
|
||||
for item in items {
|
||||
prop_assert!(item.range.start.line < buffer.line_count());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -12,7 +12,8 @@
|
|||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender, TryRecvError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use lutra_lsp::{LspError, Server, ServerEvent, ServerOptions, Status};
|
||||
|
|
@ -29,8 +30,10 @@ pub struct Launch {
|
|||
/// 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
|
||||
/// while the session is busy (see [`super::TICK_WINDOW`]), and at
|
||||
/// [`super::FAST_TICK_INTERVAL`] while the server indexes or the
|
||||
/// session is young (see [`super::tick_interval`]); `None` for servers
|
||||
/// that need no nudge. Phpactor on Windows needs it, see
|
||||
/// [`super::phpactor_launch`].
|
||||
pub tick: Option<Duration>,
|
||||
}
|
||||
|
|
@ -103,14 +106,18 @@ pub struct Session {
|
|||
impl Session {
|
||||
/// Starts the session thread, which starts `launch` in `root`.
|
||||
///
|
||||
/// # Parameters
|
||||
/// - `indexing`: set by the pump while the server reports work-done
|
||||
/// progress; the thread ticks fast while it is set.
|
||||
///
|
||||
/// # Errors
|
||||
/// The thread could not be started.
|
||||
pub fn start(launch: Launch, root: PathBuf) -> Result<Self, String> {
|
||||
pub fn start(launch: Launch, root: PathBuf, indexing: Arc<AtomicBool>) -> 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))
|
||||
.spawn(move || run(launch, &root, &indexing, &queue, &reporter))
|
||||
.map_err(|e| format!("cannot start the language server thread: {e}"))?;
|
||||
Ok(Self {
|
||||
jobs,
|
||||
|
|
@ -153,7 +160,13 @@ impl Session {
|
|||
/// 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>) {
|
||||
fn run(
|
||||
launch: Launch,
|
||||
root: &Path,
|
||||
indexing: &AtomicBool,
|
||||
queue: &Receiver<Job>,
|
||||
reporter: &Sender<Report>,
|
||||
) {
|
||||
let Launch {
|
||||
command,
|
||||
args,
|
||||
|
|
@ -175,7 +188,7 @@ fn run(launch: Launch, root: &Path, queue: &Receiver<Job>, reporter: &Sender<Rep
|
|||
return;
|
||||
}
|
||||
};
|
||||
work(&server, tick, queue, reporter);
|
||||
work(&server, tick, indexing, queue, reporter);
|
||||
match Arc::try_unwrap(server) {
|
||||
Ok(server) => server.shutdown(),
|
||||
Err(shared) => drop(shared),
|
||||
|
|
@ -186,11 +199,35 @@ fn run(launch: Launch, root: &Path, queue: &Receiver<Job>, reporter: &Sender<Rep
|
|||
/// 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();
|
||||
///
|
||||
/// The interval comes from [`super::tick_interval`]. A fast one (below
|
||||
/// [`COARSE_WAIT`]) is kept with [`std::thread::sleep`] between polls of
|
||||
/// the queue, because a channel wait with a timeout wakes at most about
|
||||
/// 64 times a second on Windows (its timer resolution of 15.6 ms;
|
||||
/// measured: 63–67 wakes/s for 1, 2 and 5 ms timeouts), while a sleep
|
||||
/// uses a high-resolution timer. A job then waits at most one interval.
|
||||
fn work(
|
||||
server: &Server,
|
||||
tick: Option<Duration>,
|
||||
indexing: &AtomicBool,
|
||||
queue: &Receiver<Job>,
|
||||
reporter: &Sender<Report>,
|
||||
) {
|
||||
let started = Instant::now();
|
||||
let mut last_job = started;
|
||||
let mut last_tick = None;
|
||||
loop {
|
||||
let next = match tick {
|
||||
let fast = indexing.load(Ordering::Relaxed);
|
||||
let interval = super::tick_interval(tick, fast, started.elapsed());
|
||||
let next = match interval {
|
||||
Some(interval) if interval < COARSE_WAIT => match queue.try_recv() {
|
||||
Ok(job) => Ok(job),
|
||||
Err(TryRecvError::Empty) => {
|
||||
std::thread::sleep(interval);
|
||||
Err(RecvTimeoutError::Timeout)
|
||||
}
|
||||
Err(TryRecvError::Disconnected) => Err(RecvTimeoutError::Disconnected),
|
||||
},
|
||||
Some(interval) => queue.recv_timeout(interval),
|
||||
None => queue.recv().map_err(|_| RecvTimeoutError::Disconnected),
|
||||
};
|
||||
|
|
@ -204,13 +241,18 @@ fn work(server: &Server, tick: Option<Duration>, queue: &Receiver<Job>, reporter
|
|||
}
|
||||
let now = Instant::now();
|
||||
let ready = server.status() == Status::Ready;
|
||||
if super::tick_due(tick, ready, Some(last_job), last_tick, now) {
|
||||
let activity = if interval == tick { last_job } else { now };
|
||||
if super::tick_due(interval, ready, Some(activity), last_tick, now) {
|
||||
last_tick = Some(now);
|
||||
server.notify(super::TICK_METHOD, Value::Object(Map::new()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Intervals below this are waited for with a sleep instead of a channel
|
||||
/// timeout (see [`work`]).
|
||||
const COARSE_WAIT: Duration = Duration::from_millis(16);
|
||||
|
||||
/// 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,
|
||||
|
|
|
|||
|
|
@ -416,7 +416,7 @@ fn no_server_without_a_project_or_toolchain() {
|
|||
}
|
||||
assert_eq!(
|
||||
engine.execute("lsp.status", Value::Null).unwrap().value,
|
||||
json!({"state": "stopped"})
|
||||
json!({"state": "stopped", "progress": {"active": false}})
|
||||
);
|
||||
let err = engine
|
||||
.execute("diagnostics.list", json!({"bogus": 1}))
|
||||
|
|
|
|||
526
crates/engine/tests/lsp_ux.rs
Normal file
526
crates/engine/tests/lsp_ux.rs
Normal file
|
|
@ -0,0 +1,526 @@
|
|||
//! Phpactor UX (H3): `window/showMessage` as notifications,
|
||||
//! `$/progress` as `lspProgress`, the fast tick while the server indexes,
|
||||
//! and Lutra's own `php -l` on save.
|
||||
//!
|
||||
//! The fake server (`lutra-lsp-fake --script`) sends the messages; the
|
||||
//! `php -l` tests need PHP on `PATH` (or `LUTRA_PHP`) and skip with a
|
||||
//! message without it. The ignored `real_phpactor_first_completion`
|
||||
//! measures the time to the first useful completion on a generated
|
||||
//! project.
|
||||
|
||||
#![allow(
|
||||
clippy::unwrap_used,
|
||||
clippy::expect_used,
|
||||
clippy::panic,
|
||||
clippy::indexing_slicing
|
||||
)]
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use lutra_engine::lsp::Launch;
|
||||
use lutra_engine::{Engine, EngineError};
|
||||
use lutra_lsp::ServerOptions;
|
||||
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
|
||||
}
|
||||
|
||||
/// A temp project with `files`, opened in an engine; with `script`, the
|
||||
/// fake server runs with it (see the fake server's docs), else none.
|
||||
fn project(files: &[(&str, &str)], script: Option<Value>) -> (TempDir, TempDir, Engine) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let scripts = tempfile::tempdir().unwrap();
|
||||
for (name, text) in files {
|
||||
fs::write(dir.path().join(name), text).unwrap();
|
||||
}
|
||||
let mut engine = Engine::new().unwrap();
|
||||
engine.set_php_lint(None);
|
||||
if let Some(script) = script {
|
||||
let file = scripts.path().join("script.json");
|
||||
fs::write(&file, script.to_string()).unwrap();
|
||||
engine.set_language_server(Some(Launch {
|
||||
command: fake_server().into(),
|
||||
args: vec![OsString::from("--script"), file.into_os_string()],
|
||||
options: ServerOptions::default(),
|
||||
tick: None,
|
||||
}));
|
||||
}
|
||||
engine
|
||||
.execute("project.open", json!({"path": dir.path()}))
|
||||
.unwrap();
|
||||
(dir, scripts, engine)
|
||||
}
|
||||
|
||||
/// Pumps until an event satisfies `done` (at most 10 s); returns every
|
||||
/// event seen.
|
||||
fn pump_until(engine: &mut Engine, done: impl Fn(&Value) -> bool) -> Vec<Value> {
|
||||
let started = Instant::now();
|
||||
let mut seen = Vec::new();
|
||||
loop {
|
||||
for event in pump(engine) {
|
||||
let hit = done(&event);
|
||||
seen.push(event);
|
||||
if hit {
|
||||
return seen;
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(10),
|
||||
"timed out; events: {seen:#?}"
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
}
|
||||
|
||||
/// The version of buffer `id`.
|
||||
fn version(engine: &mut Engine, id: u64) -> Value {
|
||||
engine
|
||||
.execute("buffer.get", json!({"id": id}))
|
||||
.unwrap()
|
||||
.value["version"]
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// A `$/progress` notification.
|
||||
fn progress(token: &str, value: Value) -> Value {
|
||||
json!({"method": "$/progress", "params": {"token": token, "value": value}})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn messages_become_notifications_and_progress_reaches_the_status() {
|
||||
let show = |kind: u8, message: &str| json!({"method": "window/showMessage", "params": {"type": kind, "message": message}});
|
||||
let script = json!({"notifications": [
|
||||
show(2, "Index is stale"),
|
||||
show(2, "Diagnostic provider \"php\" errored with \"CreateProcess failed\", removing from pool"),
|
||||
show(2, "Index is stale"),
|
||||
show(1, "File watcher died"),
|
||||
{"method": "window/logMessage", "params": {"type": 4, "message": "quiet"}},
|
||||
progress("idx", json!({"kind": "begin", "title": "Indexing workspace", "message": "3 PHP files", "percentage": 0})),
|
||||
progress("idx", json!({"kind": "report", "message": "2/3", "percentage": 67})),
|
||||
progress("other", json!({"kind": "report", "percentage": 5})),
|
||||
progress("idx", json!({"kind": "end", "message": "done"})),
|
||||
progress("refs", json!({"kind": "begin", "title": "Finding references", "percentage": 250})),
|
||||
show(3, "last")
|
||||
]});
|
||||
let (_dir, _scripts, mut engine) = project(&[("a.php", "<?php\n")], Some(script));
|
||||
let events = pump_until(&mut engine, |e| e["params"]["message"] == "last");
|
||||
let notes: Vec<(&str, &str)> = events
|
||||
.iter()
|
||||
.filter(|e| e["messageKey"] == "notification.lsp.message")
|
||||
.map(|e| {
|
||||
(
|
||||
e["level"].as_str().unwrap(),
|
||||
e["params"]["message"].as_str().unwrap(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
notes,
|
||||
[
|
||||
("warning", "Index is stale"),
|
||||
("error", "File watcher died"),
|
||||
("info", "last")
|
||||
]
|
||||
);
|
||||
let progress: Vec<&Value> = events
|
||||
.iter()
|
||||
.filter(|e| e["kind"] == "lspProgress")
|
||||
.collect();
|
||||
assert_eq!(
|
||||
progress,
|
||||
[
|
||||
&json!({"kind": "lspProgress", "active": true, "title": "Indexing workspace", "message": "3 PHP files", "percentage": 0}),
|
||||
&json!({"kind": "lspProgress", "active": true, "title": "Indexing workspace", "message": "2/3", "percentage": 67}),
|
||||
&json!({"kind": "lspProgress", "active": false}),
|
||||
&json!({"kind": "lspProgress", "active": true, "title": "Finding references", "percentage": 100}),
|
||||
]
|
||||
);
|
||||
let status = engine.execute("lsp.status", json!({})).unwrap().value;
|
||||
assert_eq!(status["progress"]["title"], "Finding references");
|
||||
let log = engine.execute("lsp.log", json!({})).unwrap().value;
|
||||
let lines: Vec<&str> = log["lines"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|l| l.as_str().unwrap())
|
||||
.collect();
|
||||
assert!(lines.contains(&"[info] hello"), "{lines:?}");
|
||||
assert!(lines.contains(&"[log] quiet"), "{lines:?}");
|
||||
assert!(
|
||||
lines.iter().any(|l| l.contains("CreateProcess failed")),
|
||||
"{lines:?}"
|
||||
);
|
||||
let after = events_of(&mut engine, "lsp.restart");
|
||||
assert!(
|
||||
after.contains(&json!({"kind": "lspProgress", "active": false})),
|
||||
"{after:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// PHP for the `php -l` tests: `LUTRA_PHP` or `php` on `PATH`; `None`
|
||||
/// (the test skips) when it does not run.
|
||||
fn php() -> Option<PathBuf> {
|
||||
let php = PathBuf::from(std::env::var("LUTRA_PHP").unwrap_or_else(|_| "php".into()));
|
||||
let runs = std::process::Command::new(&php)
|
||||
.arg("-v")
|
||||
.output()
|
||||
.is_ok_and(|o| o.status.success());
|
||||
if !runs {
|
||||
eprintln!("skipped: no PHP (set LUTRA_PHP or put php on PATH)");
|
||||
}
|
||||
runs.then_some(php)
|
||||
}
|
||||
|
||||
/// The `php -l` items of a `diagnosticsChanged` event.
|
||||
fn lint_items(event: &Value) -> Vec<&Value> {
|
||||
event["items"]
|
||||
.as_array()
|
||||
.map(|items| items.iter().filter(|i| i["source"] == "php -l").collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn php_lint_reports_syntax_errors_on_open_and_save() {
|
||||
let Some(php) = php() else {
|
||||
return;
|
||||
};
|
||||
let broken = "<?php\n\nfunction f() {\n retur 1;\n}\n";
|
||||
let (dir, _scripts, mut engine) = project(&[("a.php", broken), ("b.txt", "x")], None);
|
||||
engine.set_php_lint(Some(php));
|
||||
let id = open(&mut engine, "a.php");
|
||||
open(&mut engine, "b.txt");
|
||||
let events = pump_until(&mut engine, |e| e["kind"] == "diagnosticsChanged");
|
||||
let changed = events.last().unwrap();
|
||||
assert_eq!(changed["path"], "a.php");
|
||||
let items = lint_items(changed);
|
||||
assert_eq!(items.len(), 1, "{changed}");
|
||||
assert_eq!(items[0]["severity"], "error");
|
||||
assert_eq!(items[0]["range"]["start"], json!({"line": 3, "column": 0}));
|
||||
assert_eq!(items[0]["range"]["end"], json!({"line": 3, "column": 12}));
|
||||
assert!(
|
||||
items[0]["message"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("syntax error"),
|
||||
"{changed}"
|
||||
);
|
||||
let listed = engine.execute("diagnostics.list", json!({})).unwrap().value;
|
||||
assert_eq!(listed["files"][0]["path"], "a.php");
|
||||
|
||||
let base = version(&mut engine, id);
|
||||
engine
|
||||
.execute(
|
||||
"buffer.edit",
|
||||
json!({"id": id, "baseVersion": base, "edits": [{"from": 26, "to": 31, "insert": "return"}]}),
|
||||
)
|
||||
.unwrap();
|
||||
for _ in 0..20 {
|
||||
let events = pump(&mut engine);
|
||||
assert!(
|
||||
!events.iter().any(|e| e["kind"] == "diagnosticsChanged"),
|
||||
"a dirty buffer is not linted: {events:?}"
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
engine.execute("file.save", json!({"id": id})).unwrap();
|
||||
let events = pump_until(&mut engine, |e| e["kind"] == "diagnosticsChanged");
|
||||
assert_eq!(
|
||||
events.last().unwrap(),
|
||||
&json!({"kind": "diagnosticsChanged", "path": "a.php", "items": []})
|
||||
);
|
||||
assert!(
|
||||
fs::read_to_string(dir.path().join("a.php"))
|
||||
.unwrap()
|
||||
.contains("return 1;")
|
||||
);
|
||||
|
||||
let base = version(&mut engine, id);
|
||||
engine
|
||||
.execute(
|
||||
"buffer.edit",
|
||||
json!({"id": id, "baseVersion": base, "edits": [{"from": 38, "to": 38, "insert": "}"}]}),
|
||||
)
|
||||
.unwrap();
|
||||
engine.execute("file.save", json!({"id": id})).unwrap();
|
||||
let events = pump_until(&mut engine, |e| e["kind"] == "diagnosticsChanged");
|
||||
assert_eq!(lint_items(events.last().unwrap()).len(), 1);
|
||||
let mut events = events_of(&mut engine, "project.close");
|
||||
events.extend(pump(&mut engine));
|
||||
let cleared = events
|
||||
.iter()
|
||||
.find(|e| e["kind"] == "diagnosticsChanged")
|
||||
.unwrap();
|
||||
assert_eq!(cleared["items"], json!([]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn php_lint_merges_with_the_servers_diagnostics() {
|
||||
let Some(php) = php() else {
|
||||
return;
|
||||
};
|
||||
let (_dir, _scripts, mut engine) = project(&[("a.php", "<?php\nif (\n")], Some(json!({})));
|
||||
engine.set_php_lint(Some(php));
|
||||
open(&mut engine, "a.php");
|
||||
let events = pump_until(&mut engine, |e| {
|
||||
e["kind"] == "diagnosticsChanged" && e["items"].as_array().is_some_and(|i| i.len() == 2)
|
||||
});
|
||||
let items = events.last().unwrap()["items"].as_array().unwrap();
|
||||
assert_eq!(items[0]["source"], "fake");
|
||||
assert_eq!(items[1]["source"], "php -l");
|
||||
let events = events_of(&mut engine, "lsp.restart");
|
||||
let changed = events
|
||||
.iter()
|
||||
.find(|e| e["kind"] == "diagnosticsChanged")
|
||||
.unwrap();
|
||||
let items = changed["items"].as_array().unwrap();
|
||||
assert_eq!(items.len(), 1, "the server's diagnostic goes, php -l stays");
|
||||
assert_eq!(items[0]["source"], "php -l");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn php_lint_is_off_without_php() {
|
||||
let (_dir, _scripts, mut engine) = project(&[("a.php", "<?php\nif (\n")], None);
|
||||
open(&mut engine, "a.php");
|
||||
for _ in 0..40 {
|
||||
let events = pump(&mut engine);
|
||||
assert!(
|
||||
!events.iter().any(|e| e["kind"] == "diagnosticsChanged"),
|
||||
"{events:?}"
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
let listed = engine.execute("diagnostics.list", json!({})).unwrap().value;
|
||||
assert_eq!(listed["files"], json!([]));
|
||||
}
|
||||
|
||||
/// Opens `path`; returns the buffer id.
|
||||
fn open(engine: &mut Engine, path: &str) -> u64 {
|
||||
engine
|
||||
.execute("file.open", json!({"path": path}))
|
||||
.unwrap()
|
||||
.value["id"]
|
||||
.as_u64()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Runs `command` and waits for its pending result, as a host does.
|
||||
fn ask(engine: &mut Engine, command: &str, params: Value) -> Result<Value, EngineError> {
|
||||
let mut outcome = engine.execute(command, params)?;
|
||||
match outcome.pending.take() {
|
||||
Some(pending) => Ok(engine.resolve(pending.wait())?.value),
|
||||
None => Ok(outcome.value),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `command` and returns the events it queued, as JSON.
|
||||
fn events_of(engine: &mut Engine, command: &str) -> Vec<Value> {
|
||||
engine
|
||||
.execute(command, json!({}))
|
||||
.unwrap()
|
||||
.events
|
||||
.iter()
|
||||
.map(|e| serde_json::to_value(e).unwrap())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Pumps once and returns the events as JSON.
|
||||
fn pump(engine: &mut Engine) -> Vec<Value> {
|
||||
engine
|
||||
.pump_vfs()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|e| serde_json::to_value(e).unwrap())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A shop-like project: `classes` classes in `src/` plus the file the
|
||||
/// test completes in.
|
||||
fn shop(classes: usize) -> Vec<(String, String)> {
|
||||
let mut files = Vec::new();
|
||||
for i in 0..classes {
|
||||
files.push((
|
||||
format!("src/Product{i}.php"),
|
||||
format!(
|
||||
"<?php\n\nnamespace Shop;\n\n/**\n * A product of the shop, number {i}.\n */\nfinal class Product{i}\n{{\n public function __construct(private string $name, private int $price) {{}}\n\n /** The display name. */\n public function name(): string\n {{\n return $this->name;\n }}\n\n /** The price in cents, times `$count`. */\n public function price(int $count = 1, bool $gross = true): int\n {{\n return $this->price * $count;\n }}\n}}\n"
|
||||
),
|
||||
));
|
||||
}
|
||||
files.push((
|
||||
"src/Cart.php".into(),
|
||||
"<?php\n\nnamespace Shop;\n\nfinal class Cart\n{\n public function add(Product1999 $product): void\n {\n $product->\n }\n}\n".into(),
|
||||
));
|
||||
files
|
||||
}
|
||||
|
||||
/// Time from opening a generated project to the first completion list
|
||||
/// that has the method of a class Phpactor must have indexed
|
||||
/// (`Product1999`, or the last class of a smaller project), with the
|
||||
/// `lspProgress` events on the way:
|
||||
///
|
||||
/// `LUTRA_PHPACTOR=<phar> [LUTRA_PHP=php] [LUTRA_SHOP_CLASSES=2000] cargo test -p lutra-engine --test lsp_ux real_phpactor_first_completion -- --ignored --nocapture`
|
||||
#[test]
|
||||
#[ignore = "needs PHP and Phpactor (LUTRA_PHPACTOR)"]
|
||||
fn real_phpactor_first_completion() {
|
||||
let phar = std::env::var("LUTRA_PHPACTOR").expect("LUTRA_PHPACTOR");
|
||||
let php = std::env::var("LUTRA_PHP").unwrap_or_else(|_| "php".into());
|
||||
let classes: usize = std::env::var("LUTRA_SHOP_CLASSES")
|
||||
.ok()
|
||||
.and_then(|n| n.parse().ok())
|
||||
.unwrap_or(2000);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for (name, text) in shop(classes) {
|
||||
let text = text.replace("Product1999", &format!("Product{}", classes - 1));
|
||||
let path = dir.path().join(name);
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, text).unwrap();
|
||||
}
|
||||
let mut engine = Engine::new().unwrap();
|
||||
engine.set_language_server(Some(lutra_engine::lsp::phpactor_launch(
|
||||
&php,
|
||||
&phar,
|
||||
cfg!(windows),
|
||||
)));
|
||||
engine
|
||||
.execute("project.open", json!({"path": dir.path()}))
|
||||
.unwrap();
|
||||
let started = Instant::now();
|
||||
let id = open(&mut engine, "src/Cart.php");
|
||||
let at_arrow =
|
||||
json!({"id": id, "position": {"line": 8, "column": 18}, "triggerCharacter": ">"});
|
||||
let mut ready = None;
|
||||
let mut attempts = 0;
|
||||
loop {
|
||||
for event in pump(&mut engine) {
|
||||
match event["kind"].as_str() {
|
||||
Some("lspStatus") if event["state"] == "ready" && ready.is_none() => {
|
||||
ready = Some(started.elapsed());
|
||||
println!("ready after {:?}", started.elapsed());
|
||||
}
|
||||
Some("lspProgress") => println!("{:?} {event}", started.elapsed()),
|
||||
Some("notification") => println!("{:?} {event}", started.elapsed()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if ready.is_some() {
|
||||
attempts += 1;
|
||||
let out = ask(&mut engine, "lsp.completion", at_arrow.clone()).unwrap();
|
||||
let found = out["items"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|i| i["label"] == "price");
|
||||
if found {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(180),
|
||||
"no useful completion within 180 s"
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(250));
|
||||
}
|
||||
println!(
|
||||
"FIRST USEFUL COMPLETION {:?} after project.open ({classes} classes, {attempts} attempts)",
|
||||
started.elapsed()
|
||||
);
|
||||
std::thread::sleep(Duration::from_secs(2));
|
||||
for event in pump(&mut engine) {
|
||||
if event["kind"] == "notification" {
|
||||
println!("{event}");
|
||||
}
|
||||
}
|
||||
let log = engine.execute("lsp.log", json!({})).unwrap().value;
|
||||
for line in log["lines"].as_array().unwrap() {
|
||||
if line.as_str().unwrap().starts_with("[show") {
|
||||
println!("log: {line}");
|
||||
}
|
||||
}
|
||||
let requests: usize = std::env::var("LUTRA_UX_REQUESTS")
|
||||
.ok()
|
||||
.and_then(|n| n.parse().ok())
|
||||
.unwrap_or(0);
|
||||
if requests > 0 {
|
||||
std::thread::sleep(Duration::from_secs(5));
|
||||
let epoch = || {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_millis()
|
||||
};
|
||||
let cases = [
|
||||
("member", " $product->pri", None::<&str>),
|
||||
("class", " $x = new Produc", None),
|
||||
];
|
||||
for (name, line, trigger) in cases {
|
||||
let source = fs::read_to_string(dir.path().join("src/Cart.php")).unwrap();
|
||||
let text: String = source
|
||||
.split('\n')
|
||||
.enumerate()
|
||||
.map(|(i, l)| if i == 8 { line } else { l })
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
let current = engine
|
||||
.execute("buffer.get", json!({"id": id}))
|
||||
.unwrap()
|
||||
.value;
|
||||
engine
|
||||
.execute(
|
||||
"buffer.edit",
|
||||
json!({"id": id, "baseVersion": current["version"], "edits": [{"from": 0, "to": current["text"].as_str().unwrap().encode_utf16().count(), "insert": text}]}),
|
||||
)
|
||||
.unwrap();
|
||||
let at = json!({"id": id, "position": {"line": 8, "column": line.len()}, "triggerCharacter": trigger});
|
||||
let _ = ask(&mut engine, "lsp.completion", at.clone());
|
||||
println!("PHASE {name} start {}", epoch());
|
||||
let mut ms = Vec::new();
|
||||
let mut last = Value::Null;
|
||||
for _ in 0..requests {
|
||||
let t = Instant::now();
|
||||
last = ask(&mut engine, "lsp.completion", at.clone()).unwrap();
|
||||
ms.push(t.elapsed().as_secs_f64() * 1000.0);
|
||||
}
|
||||
println!("PHASE {name} end {}", epoch());
|
||||
ms.sort_by(f64::total_cmp);
|
||||
println!(
|
||||
"{name}: {requests} requests, median {:.0} ms, max {:.0} ms, items {}, incomplete {}",
|
||||
ms[ms.len() / 2],
|
||||
ms[ms.len() - 1],
|
||||
last["items"].as_array().unwrap().len(),
|
||||
last["incomplete"]
|
||||
);
|
||||
}
|
||||
}
|
||||
let idle: u64 = std::env::var("LUTRA_UX_IDLE_SECS")
|
||||
.ok()
|
||||
.and_then(|n| n.parse().ok())
|
||||
.unwrap_or(0);
|
||||
if idle > 0 {
|
||||
let epoch = || {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_millis()
|
||||
};
|
||||
println!("PHASE idle start {} at {:?}", epoch(), started.elapsed());
|
||||
std::thread::sleep(Duration::from_secs(idle));
|
||||
println!("PHASE idle end {} at {:?}", epoch(), started.elapsed());
|
||||
}
|
||||
}
|
||||
|
|
@ -24,10 +24,13 @@
|
|||
//! (then `RequestCancelled` and the notification `fake/cancelled`),
|
||||
//! `fake/crash` exits with code 7, `fake/garbage` writes malformed frames
|
||||
//! before answering. `shutdown` answers `null`; `exit` exits with 0.
|
||||
//! - `--script FILE` reads a JSON object `{capabilities?, responses?}`:
|
||||
//! `capabilities` are merged into the `initialize` answer, and
|
||||
//! `responses` maps a request method to the result it gets, before the
|
||||
//! built-in answers (M3.5: references, prepareRename, rename).
|
||||
//! - `--script FILE` reads a JSON object
|
||||
//! `{capabilities?, responses?, notifications?}`: `capabilities` are
|
||||
//! merged into the `initialize` answer, `responses` maps a request
|
||||
//! method to the result it gets, before the built-in answers (M3.5:
|
||||
//! references, prepareRename, rename), and `notifications`
|
||||
//! (`[{method, params}]`) are sent in order after `initialized` (H3:
|
||||
//! messages and progress).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::io::{self, BufReader, Write};
|
||||
|
|
@ -316,6 +319,18 @@ impl Fake {
|
|||
"params": {"token": "t"}}),
|
||||
);
|
||||
notify("window/logMessage", json!({"type": 3, "message": "hello"}));
|
||||
let scripted = self
|
||||
.script
|
||||
.get("notifications")
|
||||
.and_then(Value::as_array)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
for n in scripted {
|
||||
notify(
|
||||
at(&n, "/method").as_str().unwrap_or_default(),
|
||||
at(&n, "/params").clone(),
|
||||
);
|
||||
}
|
||||
}
|
||||
"exit" => exit(0),
|
||||
"$/cancelRequest" => {
|
||||
|
|
|
|||
|
|
@ -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; engine ↔ Phpactor wiring and diagnostics (M3.3), pending outcomes (M3.5), completion, hover and signature help (M3.4); C5 child process groups (H1), settings dialog string and path controls and assist settings (H4), the banner-aligned themes and diagnostic/VCS tokens (H5); Git backend (M4.1), Changes tool window (M4.2) · **Last updated:** 2026-10-25
|
||||
> **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), pending outcomes (M3.5), completion, hover and signature help (M3.4); C5 child process groups (H1), settings dialog string and path controls and assist settings (H4), the banner-aligned themes and diagnostic/VCS tokens (H5), Phpactor UX: fast tick, messages, progress, `php -l` (H3); Git backend (M4.1), Changes tool window (M4.2) · **Last updated:** 2026-10-25
|
||||
|
||||
## Overview
|
||||
|
||||
|
|
@ -384,7 +384,8 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
|
|||
- 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.list {path?}` returns `{files: [{path, items}]}` sorted by path. `lsp.status` returns `{state, message?, startupMs?, progress}`. `lsp.restart` is in the Tools menu.
|
||||
- `lspProgress {active, title?, message?, percentage?}` and `lsp.log` (H3), see Phpactor UX below.
|
||||
- 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.
|
||||
|
|
@ -397,14 +398,24 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
|
|||
- **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.
|
||||
- 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 loop, so it does not depend on the host's pump. H3 adds a fast tick while Phpactor indexes (see Phpactor UX).
|
||||
- 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.
|
||||
- The PHP lint provider still fails once and removes itself; its `window/showMessage` warning is only logged (`lsp::is_hidden_message`).
|
||||
- Lutra runs `php -l` itself instead (H3, see Phpactor UX). 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.
|
||||
- **Phpactor UX (H3):** `crates/engine/src/lsp/` (`mod.rs`: progress, messages, log, merge; `session.rs`: fast tick; `php_lint.rs`), `lsp.log` in `cmd/lsp_diagnostics.rs`, the status-bar item `ui/src/components/problems/LspProgressItem.vue`.
|
||||
- **Fast tick.** Phpactor's indexer waits for a 1 ms timer after every file, and on Windows that timer only fires when a message arrives, so it indexes one file per tick. While Phpactor reports work-done progress, and during the first 120 s of a session, the tick is 1 ms (`FAST_TICK_INTERVAL`, `tick_interval`); otherwise 25 ms and the 60 s window as before. The pump sets a flag the session thread reads.
|
||||
- A channel `recv_timeout` wakes at most ~64 times a second on Windows (15.6 ms timer resolution; measured 63–67 wakes/s for 1, 2 and 5 ms timeouts), so intervals below 16 ms poll the queue and `thread::sleep` (high resolution; 697 wakes/s at 1 ms). A job waits at most one interval.
|
||||
- Measured on a generated 2,000-class project (`real_phpactor_first_completion`, Windows 11, PHP 8.4, debug build), project open to the first completion list with a method of the last class: 71.6 s with the 25 ms tick (before), 47.8 s with a 2 ms `recv_timeout` (really ~16 ms), 29.9 s at 5 ms, 23.8–26.9 s at 2 ms, 20.7–22.6 s at 1 ms with sleep. Phpactor then indexes ~110–190 files/s.
|
||||
- Cost while the window runs and Phpactor is idle: about 10% of one core for Phpactor and 4.5% for the session thread at 1 ms (9% and 3% at 2 ms). After the window it is the old 25 ms tick.
|
||||
- **Progress.** `$/progress` begin/report/end (at most 32 tasks) become `lspProgress {active, title?, message?, percentage?}` with the newest running task; `lsp.status` has it as `progress`. It clears when the session stops, restarts or fails. The status bar shows title and percentage with the message as tooltip (Phpactor: `Indexing workspace 25%`, `500/2001 (24.99%, …)`).
|
||||
- **Messages.** `window/showMessage` becomes a notification of the same level, `notification.lsp.message {message}`; the same text again within 30 s is not shown. Phpactor's known lint-provider complaint on Windows is only logged. `window/showMessage`, `window/logMessage` and stderr lines go to a log of the last 1,000 lines, `lsp.log` → `{lines}` (`[level] …`, `[show level] …`, `[stderr] …`).
|
||||
- **`php -l`.** On Windows Lutra runs the toolchain's `php -n -l -d display_errors=1 -d log_errors=0` itself for each open PHP buffer when first seen and after each save (a clean buffer whose saved version moved), on one worker thread through `lutra_proc::spawn`, with the saved text on stdin. Queued runs of one file collapse to the newest; files over 8 MiB are skipped; a run is killed after 10 s; output is capped at 64 KiB. `Parse error` / `Fatal error` lines become error diagnostics on the whole line with `source: "php -l"` (at most 100 per file). They merge after the server's into `diagnosticsChanged` and `diagnostics.list`, stay until the file's next run, survive a server restart and clear on project close. Elsewhere it is off (Phpactor lints itself); `Engine::set_php_lint` overrides it.
|
||||
- **Completion delay (H4's `editor.completion.delayMs`).** Phpactor answers every completion with `isIncomplete: true`, so CodeMirror asks again on every keystroke. Measured on 2,000 classes: a member completion costs ~6 ms of Phpactor CPU (median 21 ms), a class-name completion ~180 ms CPU (median 270 ms, 100 items). A Vitest model of CodeMirror's behaviour (server latency 40 or 150 ms, 80/150/250 ms per key) gave the same number of requests at 0 and 100 ms for 150 ms per key and slower (`->price`: 6, `ProductRepository`: 17); only typing faster than the delay (80 ms per key) cut them (6 → 1, 17 → 1), and then no list showed until the typing paused. The default stays 0: 100 ms only delays the list. The real lever is cancelling superseded requests (a follow-up).
|
||||
- Tests: `crates/engine/tests/lsp_ux.rs` (scripted fake-server messages and progress, `php -l` on open and save, merge with the server and a restart, off without PHP; the ignored real-Phpactor measurement), unit tests (tick rule, hidden message, `php -l` output parsing with a proptest), Vitest `ui/tests/problems/LspProgressItem.test.ts`.
|
||||
- **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.
|
||||
|
|
@ -412,7 +423,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
|
|||
- Without the adjustments: no diagnostics within 180 s.
|
||||
- **Known gaps:**
|
||||
- ~~A Phpactor process outlives Lutra when Lutra is killed.~~ Fixed by H1: Phpactor starts through `lutra_proc::spawn` (see Child processes).
|
||||
- `window/showMessage` and `logMessage` are dropped, and server-initiated progress is not shown.
|
||||
- ~~`window/showMessage` and `logMessage` are dropped, and server-initiated progress is not shown.~~ Fixed by H3.
|
||||
- **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.
|
||||
|
|
@ -606,6 +617,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
|
|||
| 2026-10-25 | minor | M4.1: Git backend (`lutra-vcs`, `git.*` commands, `gitChanged`, `git.executable`) |
|
||||
| 2026-10-24 | minor | H4: string and path controls in the settings dialog (`pick_file` IPC), assist settings (auto popup, completion delay, hover delay) read live |
|
||||
| 2026-10-25 | minor | H5: banner-aligned light and dark palettes, `DIAGNOSTIC_TOKENS` and `VCS_TOKENS`, completion icon colours by kind, contrast test extended |
|
||||
| 2026-10-25 | minor | H3: Phpactor UX: fast tick while indexing (1 ms, sleep-based), `lspProgress` and the status-bar item, `window/showMessage` as notifications, `lsp.log`, Lutra's own `php -l` on Windows |
|
||||
| 2026-10-25 | minor | H6: isolated data directory (`--data-dir`, `LUTRA_DATA_DIR`, `--control` temp dir), shared tools dir, rendezvous order |
|
||||
| 2026-10-24 | minor | H1: `crates/proc` (L0), child processes in kill-on-close groups (Windows job objects, Unix process groups with a watchdog); Phpactor and the PHP probe use it |
|
||||
| 2026-10-22 | minor | M3.5: definition, references, rename (`lsp_nav`, workspace edits, undoable remote edits, nav UI) |
|
||||
|
|
|
|||
|
|
@ -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 with string and path controls, 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, completion and hover, definition, references and rename, Phpactor dies with Lutra); G7 under way (`lutra` CLI and single instance, MCP server, integrated terminal); G8 under way (Git backend, M4.1; Changes window, M4.2); G14 English UI catalog in place · **Last updated:** 2026-10-25
|
||||
> **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 with string and path controls, 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, completion and hover, definition, references and rename, Phpactor dies with Lutra, faster indexing, progress and messages, `php -l` on Windows); G7 under way (`lutra` CLI and single instance, MCP server, integrated terminal); G8 under way (Git backend, M4.1; Changes window, M4.2); G14 English UI catalog in place · **Last updated:** 2026-10-25
|
||||
|
||||
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.
|
||||
|
||||
|
|
@ -46,7 +46,7 @@ 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. 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`). M3.4 added completion, hover and signature help in the editor (Phpactor's answers, Lutra's triggers, safe Markdown, measured 61–109 ms per completion while typing on Windows). M3.5 added go to definition (F12, Mod+click, a picker for several), find references (a References tab) and rename (F2, an inline field; open buffers dirty and undoable, closed files written atomically, edits outside the project refused), all through Phpactor without blocking the engine; rename has no preview list yet, and the editor's undo does not revert closed files it wrote. H1 (C5) put Phpactor into a kill-on-close group (`crates/proc`: a job object on Windows, a process group with a watchdog on Unix), so it no longer outlives Lutra, even when Lutra is killed. Still open: slow first indexing on Windows (Phpactor advances one step per stdin message, so a 2,000-class project takes ~65 s before completion is useful), PHP lint syntax errors on Windows, quick-fixes.
|
||||
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`). M3.4 added completion, hover and signature help in the editor (Phpactor's answers, Lutra's triggers, safe Markdown, measured 61–109 ms per completion while typing on Windows). M3.5 added go to definition (F12, Mod+click, a picker for several), find references (a References tab) and rename (F2, an inline field; open buffers dirty and undoable, closed files written atomically, edits outside the project refused), all through Phpactor without blocking the engine; rename has no preview list yet, and the editor's undo does not revert closed files it wrote. H1 (C5) put Phpactor into a kill-on-close group (`crates/proc`: a job object on Windows, a process group with a watchdog on Unix), so it no longer outlives Lutra, even when Lutra is killed. H3 (C5) made Phpactor on Windows useful sooner and more visible: a 1 ms tick while it indexes (a 2,000-class project gives a useful completion after 21–27 s instead of 72 s, measured), its progress in the status bar, its messages as notifications, and Lutra's own `php -l` for syntax errors on open and save. Still open: indexing is still bound by Phpactor's one-file-per-message loop (~110–190 files/s); superseded completion requests are not cancelled (Phpactor answers every list as incomplete, so it is asked on every keystroke; ~180 ms CPU per class-name request on 2,000 classes); quick-fixes.
|
||||
|
||||
## Revision history
|
||||
|
||||
|
|
@ -56,6 +56,7 @@ G6 progress: M3.2 landed the LSP client library in `crates/lsp`: JSON-RPC framin
|
|||
| 2026-10-25 | minor | G8 shrunk: Git backend (M4.1) |
|
||||
| 2026-10-24 | patch | G3/G6: string and path settings in the dialog, completion and tooltip settings (H4) |
|
||||
| 2026-10-25 | minor | G11 note: isolated data directory for dev and live-check instances (H6) |
|
||||
| 2026-10-25 | minor | G6 shrunk: faster indexing on Windows, progress and messages, `php -l` (H3) |
|
||||
| 2026-10-24 | minor | G6: Phpactor no longer outlives Lutra (H1) |
|
||||
| 2026-10-22 | minor | G6 shrunk: definition, references, rename (M3.5) |
|
||||
| 2026-10-22 | minor | G6 shrunk: completion, hover and signature help (M3.4) |
|
||||
|
|
|
|||
|
|
@ -18,8 +18,8 @@ Hours are the estimated agent wall-clock hours for one agent to reach behaviour
|
|||
| Project view, VFS | 6 | 8% (est.) | views list (project / scopes), toolbar (Select Opened File, Expand/Collapse All), sort and display options, show/hide excluded, distinct icons for library and excluded folders, file colours, speed search, preview, file operations | ~37 (est.) | `lutra-vfs` (M1.2): lazy sorted listing, ignore rules (.gitignore, .ignore, info/exclude, global excludes, Lutra defaults), native file watching via `notify` with a polling fallback, capped UTF-8 reads, atomic writes; 34 tests on temp dirs, watcher tests run on both backends (`crates/vfs/tests`). M1.5: project tree UI (lazy listing, keyboard navigation, dimmed ignored entries, event refresh) in `ui/src/components/project/`, Vitest against a mocked engine. M1.3: `project.open`, `project.close`, `project.children` (watches listed directories, capped at 256 native / 32 polling, least recently listed dropped), `treeChanged` events from disk, `events.subscribe` on the control channel with a TCP test (`crates/control/tests/events.rs`). M1.4: the tree runs against the engine in the app: folder picker (`project.openDialog`) and `lutra-desktop --control PORT PATH` open a project, the tree lists it lazily with ignored (`var/` from `.gitignore`) and excluded (`node_modules`) entries dimmed, a file created on disk appears in an expanded folder within ~100 ms; verified with `ui.screenshot` on Windows 11 and Vitest (`ui/tests/project/`, `ui/tests/ipcEvents.test.ts`). M1.13: a directory listed only partly (more than 100,000 entries) ends with a "Listing truncated" note row (Vitest). M1.12: a folder that cannot be opened from the picker or the command line (including `unsaved_changes` when switching projects) and stopped file watching show as toasts instead of stderr (`apps/lutra-desktop/src/host.rs`, `ui/src/stores/notifications.ts`, `ui/tests/notifications/`, 19 Vitest tests; live check pending, gaming mode); score unchanged. Graded against `plan/phpstorm/02-project-view.md`: tool window, folder-first tree, dimmed ignored/excluded, keyboard navigation and live refresh exist; most toolbar, view and display options do not |
|
||||
| Navigation | 10 | 13% (est.) | go to declaration: type declaration, implementations, the hover link underline; find usages: popup variant, usages highlighted in the file, scopes, grouping options, read/write access; 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; 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) | ~96 (est.) | M3.5: Go to Definition (`lsp.definition`, F12 or Mod+click with a pointer cursor while Mod is held) through Phpactor: one location revealed, several in a picker (one modal at a time), none as a toast; Find References (`lsp.references`, Shift+F12) in a References tab of the bottom panel, grouped by file with the line preview and the name marked, click or Enter reveals. Requests wait off the engine lock (pending outcomes) and see every edit sent before them. Live against Phpactor 2026.06.25.0 on Windows (port 7935, three-file temp project, debug build, tick on): class definition across files 93 ms cold, 7–18 ms warm; references (4 uses in 3 files, incl. a CRLF file) ~140 ms (measured). Tests: `crates/engine/tests/lsp_nav.rs` (fake server with scripted answers; an ignored real-Phpactor test), Vitest `ui/tests/nav/`. The F12 and F2 keys were not pressed in the live app (no key input without stealing the owner's focus); the key and click paths are covered by Vitest. 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 | 5% (est.) | type-matching and second-invocation completion, postfix completion, live templates, path completion, ranking options and the replace-on-accept variant, accept characters, auto-insert of a single suggestion, auto-import checked against the real Phpactor (applied when the server sends it; tested with the fake server only), completion settings beyond H4's auto popup and delays (case sensitivity, sorting), parameter info settings, a documentation tool window, type info, faster indexing on Windows (Phpactor's tick-driven loop takes ~65 s for 2,000 classes) | ~240 (est.) | M3.4: completion, hover and signature help from Phpactor. Engine `lsp.completion {id, position, triggerCharacter?}` (items with label, kind, detail, Markdown documentation, insertText, textEdit, additionalTextEdits, sortText; at most 500, sorted by sortText, `incomplete` when cut or when the server says so; snippets turned into plain text), `lsp.hover` (Markdown, range) and `lsp.signatureHelp` (UTF-16 parameter spans), sent off the engine lock through M3.5's pending outcomes (`crates/engine/src/cmd/lsp_assist.rs`). Editor (`ui/src/components/editor/assist/`): a CodeMirror completion source with Lutra's own triggers (identifiers, `$`, `->`, `?->`, `::`, namespace `\`; not in strings or comments unless asked), the server's ranking as boost, local filtering for complete lists, text edits and imports applied in UTF-16 (CRLF files too), Lucide kind icons; hover documentation after 350 ms and on demand (`editor.quickDocumentation` `Mod+I`); signature help on `(` and `,` that follows the cursor (`editor.parameterInfo`); `editor.complete`; Markdown rendered by Lutra's own renderer without any HTML (XSS-tested). Tests: 6 engine tests against the fake server, 9 unit tests, 29 Vitest tests, an ignored test against the real PHAR. Measured with the real Phpactor on Windows 11 (debug build, 25 ms tick): completion while typing 61–109 ms (median 76 ms; ~107 ms through the control channel in the app), hover 4–91 ms (median 15–16 ms), signature help 4–28 ms (median 16 ms); a useful list 2.3 s after opening a file of a 20-class project and 65 s for 2,000 classes (Phpactor indexes first and answers with an empty incomplete list until then). Checked in the app (port 7934): completion after `->`, quick documentation of a class, parameter info with the active parameter, screenshots read. Graded against `plan/phpstorm/12-completion.md`: the depth comes from Phpactor (members, classes, variables, keywords; detail and documentation often missing), Lutra has no type inference of its own |
|
||||
| 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 |
|
||||
| Code completion | 10 | 5% (est.) | type-matching and second-invocation completion, postfix completion, live templates, path completion, ranking options and the replace-on-accept variant, accept characters, auto-insert of a single suggestion, auto-import checked against the real Phpactor (applied when the server sends it; tested with the fake server only), completion settings beyond H4's auto popup and delays (case sensitivity, sorting), parameter info settings, a documentation tool window, type info | ~238 (est.) | H3: Phpactor indexes ~3× faster on Windows (a 1 ms tick while it reports progress and in a session's first 120 s): the first useful completion on a 2,000-class project after 20.7–26.9 s instead of 71.6 s (measured, debug build); its indexing progress shows in the status bar; `editor.completion.delayMs` stays 0 (Phpactor CPU per request and a request-count model measured; 100 ms only delays the list). M3.4: completion, hover and signature help from Phpactor. Engine `lsp.completion {id, position, triggerCharacter?}` (items with label, kind, detail, Markdown documentation, insertText, textEdit, additionalTextEdits, sortText; at most 500, sorted by sortText, `incomplete` when cut or when the server says so; snippets turned into plain text), `lsp.hover` (Markdown, range) and `lsp.signatureHelp` (UTF-16 parameter spans), sent off the engine lock through M3.5's pending outcomes (`crates/engine/src/cmd/lsp_assist.rs`). Editor (`ui/src/components/editor/assist/`): a CodeMirror completion source with Lutra's own triggers (identifiers, `$`, `->`, `?->`, `::`, namespace `\`; not in strings or comments unless asked), the server's ranking as boost, local filtering for complete lists, text edits and imports applied in UTF-16 (CRLF files too), Lucide kind icons; hover documentation after 350 ms and on demand (`editor.quickDocumentation` `Mod+I`); signature help on `(` and `,` that follows the cursor (`editor.parameterInfo`); `editor.complete`; Markdown rendered by Lutra's own renderer without any HTML (XSS-tested). Tests: 6 engine tests against the fake server, 9 unit tests, 29 Vitest tests, an ignored test against the real PHAR. Measured with the real Phpactor on Windows 11 (debug build, 25 ms tick): completion while typing 61–109 ms (median 76 ms; ~107 ms through the control channel in the app), hover 4–91 ms (median 15–16 ms), signature help 4–28 ms (median 16 ms); a useful list 2.3 s after opening a file of a 20-class project and 65 s for 2,000 classes (Phpactor indexes first and answers with an empty incomplete list until then). Checked in the app (port 7934): completion after `->`, quick documentation of a class, parameter info with the active parameter, screenshots read. Graded against `plan/phpstorm/12-completion.md`: the depth comes from Phpactor (members, classes, variables, keywords; detail and documentation often missing), Lutra has no type inference of its own |
|
||||
| Inspections and quick-fixes | 8 | 5% (est.) | Lutra's own inspections and their settings, severities per inspection, quick-fixes (LSP code actions), suppression, inspection profiles, running inspections on a scope, 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) | ~287 (est.) | H3: PHP syntax errors on Windows from Lutra's own `php -l` (on open and save, off the engine lock, killed with Lutra), merged into the editor underlines and the Problems tab with source `php -l`; the language server's messages as notifications and its log as `lsp.log`. Tests: `crates/engine/tests/lsp_ux.rs`, unit tests incl. a parser proptest. 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 | 3% (est.) | rename: preview of all changes, comments/strings and text occurrences, scope, renaming files with classes, one undo across files (closed files written on disk are not undone by the editor); extract variable/method/constant, inline, move, change signature, safe delete, pull up/push down, introduce parameter | ~244 (est.) | M3.5: Rename (`lsp.prepareRename` then `lsp.rename`, F2) through Phpactor with an inline field over the symbol that shows how many uses in how many files change. The workspace edit is checked completely first (inside the project, ranges fit, open buffers unchanged since the request, no file operations); then closed files are written atomically through the VFS (written ones restored if a later write fails), open buffers change through `buffer.edit` (dirty, one undo step each in the editor), Phpactor reindexes the written files (sent as `didOpen`/`didSave`/`didClose`; its index followed in 140 ms, measured) and a summary notification follows. Live: renaming a method used in 3 files took 28 ms (open buffer + 2 closed files, CRLF kept). Tests: `crates/engine/tests/lsp_nav.rs` (multi-file rename incl. a closed CRLF file, an edit outside the project refused, a bad range refused, a buffer edited meanwhile refused; ignored real-Phpactor rename and rename back), Vitest `ui/tests/nav/`. |
|
||||
| Code style and formatting | 4 | 0% | everything | ~120 (est.) | — |
|
||||
| Git | 8 | 4% (est.) | Changes window: chunk and line staging, changelists, recent messages and a message template, pre-commit checks, skipping hooks, commit-and-push, a tree view and grouping, a context menu (rollback, delete, ignore); gutter markers, status colours, diff viewer, branch widget (C5 wave 2/3); log, blame, conflicts, stash, remotes (C6); ignored files in the status; chunk staging | ~138 (est.) | M4.2: Changes tab in the bottom panel (`ui/src/components/vcs/changes/`): Staged / Changes / Untracked groups from `git.status` (re-read on `gitChanged`), stage and unstage per file and per group with checkboxes (a staged rename passes both paths), keyboard navigation with Space to stage, double-click or Enter opens through `vcs.showDiff` when the diff viewer provides it, else the file; a commit message box with Amend and Commit (also `Mod+Enter`), which runs `flushDirty()` first, cancels when a save fails and toasts the short hash; hints for a missing git and a folder without a repository; `vcs.openChanges` `Mod+Alt+Shift+G`, `vcs.commit` `Mod+Alt+Shift+M`, `vcs.refresh`. Tests: 19 Vitest tests (`ui/tests/vcs/ChangesToolWindow.test.ts`). M4.1 (backend, reachable through the palette, control channel and MCP): `git.status`, `git.stage`, `git.unstage` (also before the first commit), `git.commit {message, amend}` with hooks, `git.show` at HEAD or the index, `git.branches`, `git.checkout` (remote → tracking branch), `git.createBranch`; `gitChanged` after changes and from a `.git` poll plus the project watcher. Runs the installed git ≥ 2.30 (`git.executable`), porcelain v2 / `-z` only, no prompts, timeouts and caps, off the engine lock. Tests against real temp repositories (`crates/vcs/tests/repo.rs`, `crates/engine/tests/git.rs`). Graded against `plan/phpstorm/16-vcs-basics.md`: committing and staging work from the UI; diff, gutter markers, status colours, branches, log, blame and remotes do not yet. |
|
||||
|
|
@ -65,6 +65,7 @@ The project tree is the first user-visible feature (Project view 8%, estimated);
|
|||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-25 | minor | H3: Inspections and quick-fixes 4% → 5% (est.), `php -l` on Windows; Code completion evidence (indexing ~3× faster), score unchanged; hours 290 → 287 and 240 → 238 |
|
||||
| 2026-10-25 | minor | M4.2: Git 1% → 4% (est.), Changes tool window; hours 148 → 138 |
|
||||
| 2026-10-25 | minor | M4.1: Git 0% → 1% (est.), Git backend without UI; hours 150 → 148 |
|
||||
| 2026-10-25 | minor | H5: Settings row evidence (banner-aligned themes, diagnostic and VCS tokens); score unchanged |
|
||||
|
|
|
|||
|
|
@ -1,11 +1,13 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* Status bar along the bottom of the main window. Shows the product name and
|
||||
* version, or the last engine error.
|
||||
* version, or the last engine error, and on the right the language server's
|
||||
* progress (H3).
|
||||
*/
|
||||
import { computed } from "vue";
|
||||
import { t } from "../i18n";
|
||||
import { useAppStore } from "../stores/app";
|
||||
import LspProgressItem from "./problems/LspProgressItem.vue";
|
||||
|
||||
const app = useAppStore();
|
||||
|
||||
|
|
@ -25,6 +27,7 @@ const label = computed(() => {
|
|||
data-test="status-bar"
|
||||
>
|
||||
<span>{{ label }}</span>
|
||||
<LspProgressItem />
|
||||
</footer>
|
||||
</template>
|
||||
|
||||
|
|
|
|||
84
ui/src/components/problems/LspProgressItem.vue
Normal file
84
ui/src/components/problems/LspProgressItem.vue
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* Status-bar item (H3): the language server's running work-done progress
|
||||
* task (`lspProgress`), such as Phpactor indexing the workspace, with its
|
||||
* title and percentage. Its latest message (`500/2001 (24.99%, …)`) is the
|
||||
* tooltip. Hidden while no task runs. State comes from the Problems store.
|
||||
*/
|
||||
import { LoaderCircle } from "@lucide/vue";
|
||||
import { computed } from "vue";
|
||||
import { t } from "../../i18n";
|
||||
import { useProblemsStore } from "./problems";
|
||||
|
||||
const problems = useProblemsStore();
|
||||
|
||||
/** The visible text, or null when no task runs. */
|
||||
const text = computed(() => {
|
||||
const progress = problems.progress;
|
||||
if (!progress) {
|
||||
return null;
|
||||
}
|
||||
const title = progress.title === "" ? t("problems.lsp.progress.working") : progress.title;
|
||||
return progress.percentage === null
|
||||
? title
|
||||
: t("problems.lsp.progress.percentage", { title, percentage: progress.percentage });
|
||||
});
|
||||
|
||||
/** The tooltip and accessible label. */
|
||||
const label = computed(() => {
|
||||
const progress = problems.progress;
|
||||
if (!progress || text.value === null) {
|
||||
return "";
|
||||
}
|
||||
const base = t("problems.lsp.progress.label", { title: text.value });
|
||||
return progress.message ? `${base} (${progress.message})` : base;
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span
|
||||
v-if="text !== null"
|
||||
class="lsp-progress"
|
||||
role="status"
|
||||
:title="label"
|
||||
:aria-label="label"
|
||||
data-test="lsp-progress"
|
||||
>
|
||||
<LoaderCircle
|
||||
class="lsp-progress__icon"
|
||||
:size="12"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span>{{ text }}</span>
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.lsp-progress {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
margin-left: auto;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
max-width: 40%;
|
||||
}
|
||||
|
||||
.lsp-progress__icon {
|
||||
flex: none;
|
||||
animation: lsp-progress-spin 1.2s linear infinite;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.lsp-progress__icon {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes lsp-progress-spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
|
@ -6,6 +6,10 @@
|
|||
* 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.
|
||||
* - **Progress (H3):** the server's newest work-done progress task
|
||||
* (`progress` of `lsp.status`, then `lspProgress`), shown by
|
||||
* `LspProgressItem` in the status bar. It clears when the server stops,
|
||||
* restarts or fails, and on project close.
|
||||
* - **Editor:** every change is handed to the editor's lint extension
|
||||
* ({@link publishDiagnostics}), which draws the underlines and gutter
|
||||
* markers.
|
||||
|
|
@ -48,6 +52,16 @@ export interface LspStatus {
|
|||
message: string | null;
|
||||
}
|
||||
|
||||
/** The language server's newest running work-done progress task. */
|
||||
export interface LspProgress {
|
||||
/** Its title, such as `Indexing workspace`. */
|
||||
title: string;
|
||||
/** Its latest message, if any. */
|
||||
message: string | null;
|
||||
/** 0–100, if the server gives one. */
|
||||
percentage: number | null;
|
||||
}
|
||||
|
||||
/** The diagnostics of one file. */
|
||||
export interface ProblemFile {
|
||||
/** Project-relative path with `/`. */
|
||||
|
|
@ -160,6 +174,30 @@ export function toStatus(raw: unknown): LspStatus | null {
|
|||
return { state: known, message: typeof message === "string" ? message : null };
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the payload of `lspProgress` or the `progress` of `lsp.status`.
|
||||
*
|
||||
* @param raw - untrusted.
|
||||
* @returns the running task, or null when none runs or it is malformed.
|
||||
*/
|
||||
export function toProgress(raw: unknown): LspProgress | null {
|
||||
if (typeof raw !== "object" || raw === null) {
|
||||
return null;
|
||||
}
|
||||
const { active, title, message, percentage } = raw as Record<string, unknown>;
|
||||
if (active !== true) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
title: typeof title === "string" ? title.slice(0, 200) : "",
|
||||
message: typeof message === "string" ? message.slice(0, 500) : null,
|
||||
percentage:
|
||||
typeof percentage === "number" && Number.isFinite(percentage)
|
||||
? Math.round(Math.min(100, Math.max(0, percentage)))
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
/** The Problems store. */
|
||||
export const useProblemsStore = defineStore("problems", () => {
|
||||
/** Whether the tool window is shown in the bottom panel. */
|
||||
|
|
@ -170,6 +208,8 @@ export const useProblemsStore = defineStore("problems", () => {
|
|||
const files = shallowRef<ProblemFile[]>([]);
|
||||
/** The language server's state; null before the first report. */
|
||||
const lsp = ref<LspStatus | null>(null);
|
||||
/** The server's running work-done progress task; null when none. */
|
||||
const progress = ref<LspProgress | null>(null);
|
||||
/** Key of the selected row. */
|
||||
const selectedKey = ref<string | null>(null);
|
||||
/** Bumped when the window should take the keyboard focus. */
|
||||
|
|
@ -226,6 +266,9 @@ export const useProblemsStore = defineStore("problems", () => {
|
|||
const [list, status] = await Promise.all([run("diagnostics.list"), run("lsp.status")]);
|
||||
if (status.ok) {
|
||||
lsp.value = toStatus(status.value) ?? lsp.value;
|
||||
const value = status.value;
|
||||
const raw = typeof value === "object" && value !== null && !Array.isArray(value) ? value.progress : null;
|
||||
progress.value = toProgress(raw);
|
||||
}
|
||||
if (!list.ok) {
|
||||
return;
|
||||
|
|
@ -255,9 +298,15 @@ export const useProblemsStore = defineStore("problems", () => {
|
|||
}
|
||||
} else if (event.kind === "lspStatus") {
|
||||
lsp.value = toStatus(event) ?? lsp.value;
|
||||
if (lsp.value && lsp.value.state !== "ready" && lsp.value.state !== "starting") {
|
||||
progress.value = null;
|
||||
}
|
||||
} else if (event.kind === "lspProgress") {
|
||||
progress.value = toProgress(event);
|
||||
} else if (event.kind === "projectClosed") {
|
||||
clear();
|
||||
lsp.value = null;
|
||||
progress.value = null;
|
||||
} else if (event.kind === "projectOpened") {
|
||||
void load();
|
||||
}
|
||||
|
|
@ -323,6 +372,7 @@ export const useProblemsStore = defineStore("problems", () => {
|
|||
expanded,
|
||||
files,
|
||||
lsp,
|
||||
progress,
|
||||
rows,
|
||||
counts,
|
||||
selectedKey,
|
||||
|
|
|
|||
|
|
@ -128,6 +128,7 @@
|
|||
"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.lsp.message": "PHP language server: {message}",
|
||||
"notification.lsp.renamed": "Renamed to {name}: {edits} changes in {files} files ({written} closed files saved)",
|
||||
"notification.project.notLocal": "The chosen folder is not on this computer: {reason}",
|
||||
"notification.project.openFailed": "Cannot open {path}: {reason}",
|
||||
|
|
@ -156,6 +157,9 @@
|
|||
"problems.file.count": "{count} problems",
|
||||
"problems.list.label": "Problems of the project",
|
||||
"problems.lsp.failed": "Phpactor stopped: {message}",
|
||||
"problems.lsp.progress.label": "Language server: {title}",
|
||||
"problems.lsp.progress.percentage": "{title} {percentage}%",
|
||||
"problems.lsp.progress.working": "Language server working…",
|
||||
"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.",
|
||||
|
|
|
|||
|
|
@ -128,6 +128,17 @@ export type EngineEventPayload =
|
|||
/** Why it restarts or failed; unchecked. */
|
||||
message?: unknown;
|
||||
}
|
||||
| {
|
||||
kind: "lspProgress";
|
||||
/** Whether a work-done progress task runs; unchecked. */
|
||||
active: unknown;
|
||||
/** Its title; unchecked. */
|
||||
title?: unknown;
|
||||
/** Its latest message; unchecked. */
|
||||
message?: unknown;
|
||||
/** 0–100; unchecked. */
|
||||
percentage?: unknown;
|
||||
}
|
||||
| {
|
||||
kind: "diagnosticsChanged";
|
||||
/** Project-relative path of the file; unchecked, it comes from the engine. */
|
||||
|
|
|
|||
|
|
@ -50,6 +50,7 @@ const usedKeys = sourceFiles(SRC).flatMap((file) =>
|
|||
const RUNTIME_KEYS = new Set([
|
||||
"notification.command.failed",
|
||||
"notification.lsp.failed",
|
||||
"notification.lsp.message",
|
||||
"notification.lsp.renamed",
|
||||
"notification.project.notLocal",
|
||||
"notification.project.openFailed",
|
||||
|
|
|
|||
140
ui/tests/problems/LspProgressItem.test.ts
Normal file
140
ui/tests/problems/LspProgressItem.test.ts
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
/**
|
||||
* Tests of the language server progress (H3): reading untrusted
|
||||
* `lspProgress` payloads, the store loading `progress` from `lsp.status`
|
||||
* and following `lspProgress`, `lspStatus` and project close, and the
|
||||
* status-bar item showing title and percentage with the message as its
|
||||
* tooltip. 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 StatusBar from "../../src/components/StatusBar.vue";
|
||||
import { toProgress, useProblemsStore } from "../../src/components/problems/problems";
|
||||
|
||||
/** Engine event callbacks of every subscription. */
|
||||
let listeners: ((event: { payload: unknown }) => void)[];
|
||||
/** 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();
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
pinia = createPinia();
|
||||
setActivePinia(pinia);
|
||||
listeners = [];
|
||||
mounted = [];
|
||||
status = { state: "ready" };
|
||||
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 }) => {
|
||||
if (cmd !== "engine_execute" || !args) {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
if (args.command === "diagnostics.list") {
|
||||
return Promise.resolve({ files: [] });
|
||||
}
|
||||
if (args.command === "lsp.status") {
|
||||
return Promise.resolve(status);
|
||||
}
|
||||
return Promise.resolve(null);
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const wrapper of mounted) {
|
||||
wrapper.unmount();
|
||||
}
|
||||
useProblemsStore(pinia).stop();
|
||||
});
|
||||
|
||||
describe("toProgress", () => {
|
||||
it("reads running tasks and rejects the rest", () => {
|
||||
expect(toProgress({ active: true, title: "Indexing workspace", message: "1/2", percentage: 50 })).toEqual({
|
||||
title: "Indexing workspace",
|
||||
message: "1/2",
|
||||
percentage: 50,
|
||||
});
|
||||
expect(toProgress({ active: true, percentage: 400 })).toEqual({ title: "", message: null, percentage: 100 });
|
||||
expect(toProgress({ active: true, percentage: Number.NaN, title: 3 })).toEqual({
|
||||
title: "",
|
||||
message: null,
|
||||
percentage: null,
|
||||
});
|
||||
expect(toProgress({ active: false, title: "x" })).toBeNull();
|
||||
expect(toProgress({ active: "yes" })).toBeNull();
|
||||
expect(toProgress(null)).toBeNull();
|
||||
expect(toProgress({ active: true, title: "t".repeat(500) })?.title).toHaveLength(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe("language server progress", () => {
|
||||
it("loads, follows events and shows title, percentage and message in the status bar", async () => {
|
||||
status = { state: "ready", progress: { active: true, title: "Indexing workspace", percentage: 0 } };
|
||||
const problems = useProblemsStore();
|
||||
problems.start();
|
||||
const wrapper = mount(StatusBar, { global: { plugins: [pinia] } });
|
||||
mounted.push(wrapper);
|
||||
await flushPromises();
|
||||
expect(wrapper.get("[data-test=lsp-progress]").text()).toBe("Indexing workspace 0%");
|
||||
|
||||
await emit({
|
||||
kind: "lspProgress",
|
||||
active: true,
|
||||
title: "Indexing workspace",
|
||||
message: "500/2001 (24.99%)",
|
||||
percentage: 25,
|
||||
});
|
||||
const item = wrapper.get("[data-test=lsp-progress]");
|
||||
expect(item.text()).toBe("Indexing workspace 25%");
|
||||
expect(item.attributes("title")).toBe("Language server: Indexing workspace 25% (500/2001 (24.99%))");
|
||||
expect(item.attributes("role")).toBe("status");
|
||||
|
||||
await emit({ kind: "lspProgress", active: true, title: "" });
|
||||
expect(wrapper.get("[data-test=lsp-progress]").text()).toBe("Language server working…");
|
||||
|
||||
await emit({ kind: "lspProgress", active: false });
|
||||
expect(wrapper.find("[data-test=lsp-progress]").exists()).toBe(false);
|
||||
});
|
||||
|
||||
it("clears when the server restarts or the project closes", async () => {
|
||||
const problems = useProblemsStore();
|
||||
problems.start();
|
||||
await flushPromises();
|
||||
await emit({ kind: "lspProgress", active: true, title: "Indexing workspace" });
|
||||
expect(problems.progress?.title).toBe("Indexing workspace");
|
||||
await emit({ kind: "lspStatus", state: "ready" });
|
||||
expect(problems.progress).not.toBeNull();
|
||||
await emit({ kind: "lspStatus", state: "restarting", message: "exit 7" });
|
||||
expect(problems.progress).toBeNull();
|
||||
await emit({ kind: "lspProgress", active: true, title: "Indexing workspace" });
|
||||
await emit({ kind: "projectClosed" });
|
||||
expect(problems.progress).toBeNull();
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue