M3.3: engine wiring for Phpactor and diagnostics

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-21 18:58:32 +02:00
parent 65c6966588
commit 13c76d3046
34 changed files with 3562 additions and 37 deletions

View file

@ -0,0 +1,247 @@
//! One language server session: the thread that owns the
//! [`lutra_lsp::Server`] of the open project.
//!
//! The engine lock only ever enqueues [`Job`]s. The session thread starts
//! the server (spawning a process can take tens of milliseconds on Windows
//! with a virus scanner), turns buffer snapshots into text, sends document
//! sync and runs the closures of [`super::submit`], strictly in the order
//! they were queued. A request queued after an edit therefore reaches the
//! server after that edit's `didChange`. What the thread learns goes back
//! to the next pump as a [`Report`].
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
use std::time::{Duration, Instant};
use lutra_lsp::{LspError, Server, ServerEvent, ServerOptions, Status};
use lutra_text::{Buffer, Edit};
use serde_json::{Map, Value};
/// How a session starts its server.
#[derive(Debug, Clone, PartialEq)]
pub struct Launch {
/// The executable (PHP for Phpactor).
pub command: OsString,
/// Its arguments (the PHAR and `language-server` for Phpactor).
pub args: Vec<OsString>,
/// Client options (timeouts, restart policy, `initializationOptions`).
pub options: ServerOptions,
/// Send the no-op notification [`super::TICK_METHOD`] at this interval
/// while the session is busy (see [`super::TICK_WINDOW`]); `None` for
/// servers that need no nudge. Phpactor on Windows needs it, see
/// [`super::phpactor_launch`].
pub tick: Option<Duration>,
}
/// Work for the session thread, run in queue order.
pub enum Job {
/// Open a document with the text of a buffer snapshot.
Open {
/// Absolute path.
path: PathBuf,
/// The buffer at the version the engine recorded.
text: Buffer,
},
/// Apply the edits `buffer.edit` applied (byte ranges into the previous
/// text).
Change {
/// Absolute path.
path: PathBuf,
/// The edit batch.
edits: Vec<Edit>,
},
/// Replace the whole text (a reload from disk, a restore, a resync).
Full {
/// Absolute path.
path: PathBuf,
/// The buffer snapshot.
text: Buffer,
},
/// The buffer was saved.
Save {
/// Absolute path.
path: PathBuf,
},
/// The buffer was closed.
Close {
/// Absolute path.
path: PathBuf,
},
/// A closure from [`super::submit`]: requests of M3.4/M3.5.
Run(Box<dyn FnOnce(&Server) + Send>),
}
/// What the session thread reports to the pump.
pub enum Report {
/// The server process started; its events arrive on `events`.
Started {
/// The server, shared so the engine can read its status.
server: Arc<Server>,
/// Its event channel.
events: Receiver<ServerEvent>,
},
/// The server could not be started.
SpawnFailed(String),
/// A `didChange` did not fit the client's copy of the document; the
/// pump resends the whole text.
Desync(PathBuf),
}
/// The engine's handle on a running session thread.
pub struct Session {
/// Jobs to the thread. Dropping it ends the thread, which shuts the
/// server down.
jobs: Sender<Job>,
/// Reports from the thread.
pub reports: Receiver<Report>,
/// The thread, joined by [`Session::join`].
thread: Option<std::thread::JoinHandle<()>>,
}
impl Session {
/// Starts the session thread, which starts `launch` in `root`.
///
/// # Errors
/// The thread could not be started.
pub fn start(launch: Launch, root: PathBuf) -> Result<Self, String> {
let (jobs, queue) = mpsc::channel::<Job>();
let (reporter, reports) = mpsc::channel::<Report>();
let thread = std::thread::Builder::new()
.name("lsp-session".into())
.spawn(move || run(launch, &root, &queue, &reporter))
.map_err(|e| format!("cannot start the language server thread: {e}"))?;
Ok(Self {
jobs,
reports,
thread: Some(thread),
})
}
/// Queues a job.
///
/// # Returns
/// `false` when the thread is gone.
pub fn send(&self, job: Job) -> bool {
self.jobs.send(job).is_ok()
}
/// Ends the queue and waits until the thread has shut the server down
/// (`shutdown`, `exit`, kill if needed: at most about 3 s). For a host
/// that is about to exit, where a background shutdown would be cut
/// short and leave the server process running. The caller must have
/// dropped its own handles on the server first, or the thread cannot
/// take sole ownership and the server is only stopped in the
/// background. A thread that panicked is ignored: there is nothing
/// left to stop.
pub fn join(self) {
let Self {
jobs,
reports,
thread,
} = self;
drop(jobs);
drop(reports);
if let Some(thread) = thread {
let _ = thread.join();
}
}
}
/// The session thread: starts the server, works off the queue until the
/// engine drops its sender, then shuts the server down (`shutdown`, `exit`,
/// kill), here and never under the engine lock. Reports that cannot be
/// delivered are dropped because the engine has stopped listening.
fn run(launch: Launch, root: &Path, queue: &Receiver<Job>, reporter: &Sender<Report>) {
let Launch {
command,
args,
options,
tick,
} = launch;
let server = match Server::spawn(&command, &args, root, options) {
Ok((server, events)) => {
let server = Arc::new(server);
let _ = reporter.send(Report::Started {
server: Arc::clone(&server),
events,
});
server
}
Err(error) => {
let _ = reporter.send(Report::SpawnFailed(error.to_string()));
while queue.recv().is_ok() {}
return;
}
};
work(&server, tick, queue, reporter);
match Arc::try_unwrap(server) {
Ok(server) => server.shutdown(),
Err(shared) => drop(shared),
}
}
/// Works off the queue until the engine drops its sender. With a tick
/// interval, also sends [`super::TICK_METHOD`] whenever one is due
/// ([`super::tick_due`]): the thread wakes at least once per interval, so
/// ticks do not depend on how often the host pumps.
fn work(server: &Server, tick: Option<Duration>, queue: &Receiver<Job>, reporter: &Sender<Report>) {
let mut last_job = Instant::now();
let mut last_tick = None;
loop {
let next = match tick {
Some(interval) => queue.recv_timeout(interval),
None => queue.recv().map_err(|_| RecvTimeoutError::Disconnected),
};
match next {
Ok(job) => {
last_job = Instant::now();
handle(server, job, reporter);
}
Err(RecvTimeoutError::Timeout) => {}
Err(RecvTimeoutError::Disconnected) => return,
}
let now = Instant::now();
let ready = server.status() == Status::Ready;
if super::tick_due(tick, ready, Some(last_job), last_tick, now) {
last_tick = Some(now);
server.notify(super::TICK_METHOD, Value::Object(Map::new()));
}
}
}
/// Runs one job against the server. Sync failures are expected races
/// (a buffer closed twice, a document already open after a restart of the
/// session) and change nothing, except a `didChange` that no longer fits,
/// which asks the pump for a full resync.
fn handle(server: &Server, job: Job, reporter: &Sender<Report>) {
match job {
Job::Open { path, text } => {
let text = text.text();
if let Err(LspError::AlreadyOpen { .. }) = server.did_open(&path, "php", &text) {
let _ = server.did_change_full(&path, &text);
}
}
Job::Change { path, edits } => {
if let Err(LspError::Text(_) | LspError::NotOpen { .. }) =
server.did_change(&path, &edits)
{
let _ = reporter.send(Report::Desync(path));
}
}
Job::Full { path, text } => {
let text = text.text();
if let Err(LspError::NotOpen { .. }) = server.did_change_full(&path, &text) {
let _ = server.did_open(&path, "php", &text);
}
}
Job::Save { path } => {
let _ = server.did_save(&path);
}
Job::Close { path } => {
let _ = server.did_close(&path);
}
Job::Run(f) => f(server),
}
}