diff --git a/apps/lutra-desktop/src/host.rs b/apps/lutra-desktop/src/host.rs index 2e101b9..894e54b 100644 --- a/apps/lutra-desktop/src/host.rs +++ b/apps/lutra-desktop/src/host.rs @@ -130,17 +130,20 @@ impl Host { } } - /// Runs a command, publishes its events and applies its effects. + /// Runs a command, publishes its events and applies its effects. A + /// command that waits for the language server is waited for without the + /// engine lock ([`lutra_engine::run_waiting`]), so the pump and other + /// commands keep running meanwhile. /// /// # Errors /// The engine's error for the command. pub fn run(&self, command: &str, params: Value) -> Result { - let outcome = { - let mut engine = self.engine(); - let outcome = engine.execute(command, params)?; - self.publish(&outcome.events); - outcome - }; + let outcome = lutra_engine::run_waiting( + || self.engine(), + command, + params, + |events| self.publish(events), + )?; for effect in outcome.effects { self.apply(effect); } diff --git a/apps/lutra-desktop/src/main.rs b/apps/lutra-desktop/src/main.rs index 90dd77a..4b767a6 100644 --- a/apps/lutra-desktop/src/main.rs +++ b/apps/lutra-desktop/src/main.rs @@ -77,6 +77,7 @@ fn run(args: &args::Args) -> Result<(), String> { .plugin(tauri_plugin_dialog::init()) .invoke_handler(tauri::generate_handler![ engine_execute, + engine_execute_waiting, engine_list_commands, engine_ready ]) @@ -206,6 +207,20 @@ fn engine_execute( host.run(&command, params).map_err(|e| e.payload()) } +/// IPC: runs an engine command that may wait for the language server +/// (`lsp.*`). `async` makes Tauri run it off the main thread, so the window +/// stays responsive while it waits (the wait itself never holds the engine +/// lock, see [`Host::run`]). Unlike [`engine_execute`], calls are not +/// ordered with other commands; the frontend uses it only for requests that +/// follow the edits they depend on. +#[tauri::command(async)] +fn engine_execute_waiting( + host: tauri::State<'_, Arc>, + command: String, + params: Value, +) -> Result { + host.run(&command, params).map_err(|e| e.payload()) +} /// IPC: lists the engine's commands for the frontend. #[tauri::command] fn engine_list_commands(host: tauri::State<'_, Arc>) -> Vec { diff --git a/crates/control/src/protocol.rs b/crates/control/src/protocol.rs index 4216837..c8161ca 100644 --- a/crates/control/src/protocol.rs +++ b/crates/control/src/protocol.rs @@ -245,7 +245,8 @@ mod tests { impl Backend for TestBackend { fn execute(&self, command: &str, params: Value) -> Result { - let out = self.engine.lock().unwrap().execute(command, params)?; + let out = + lutra_engine::run_waiting(|| self.engine.lock().unwrap(), command, params, |_| {})?; self.effects.lock().unwrap().extend(out.effects); Ok(out.value) } diff --git a/crates/engine/src/command.rs b/crates/engine/src/command.rs index a33cac1..025d6c5 100644 --- a/crates/engine/src/command.rs +++ b/crates/engine/src/command.rs @@ -34,7 +34,7 @@ pub enum Effect { } /// Result of a successful command. -#[derive(Debug, Clone, PartialEq, Default)] +#[derive(Debug, Default)] pub struct Outcome { /// JSON result returned to the caller. pub value: Value, @@ -43,6 +43,11 @@ pub struct Outcome { /// State changes for the host to publish, oldest first. Filled by the /// engine from the events the command queued; commands leave it empty. pub events: Vec, + /// An answer the command is still waiting for (a language server + /// request). The host waits for it with [`Pending::wait`] without the + /// engine lock and finishes it with [`crate::Engine::resolve`]; the + /// caller's result is the resolved value, not [`Outcome::value`]. + pub pending: Option, } impl Outcome { @@ -50,19 +55,114 @@ impl Outcome { pub fn value(value: Value) -> Self { Self { value, - effects: Vec::new(), - events: Vec::new(), + ..Self::default() } } /// An outcome with a null value and one effect. pub fn effect(effect: Effect) -> Self { Self { - value: Value::Null, effects: vec![effect], - events: Vec::new(), + ..Self::default() } } + + /// An outcome whose value comes later from `pending`. + pub fn pending(pending: Pending) -> Self { + Self { + pending: Some(pending), + ..Self::default() + } + } +} + +/// The answer a language server request delivers: its result, its error, +/// or `None` when it never came (timeout, the session ended). +pub type Reply = Option>; + +/// Turns a [`Reply`] into the command's value, under the engine lock. +type Finish = Box Result + Send>; + +/// A command result that waits for an answer from outside the engine. +/// +/// Waiting never holds the engine lock: hosts call [`Pending::wait`] after +/// releasing it, then [`crate::Engine::resolve`] with the lock to turn the +/// answer into the value (which may change the state, as a rename does). +pub struct Pending { + /// Where the answer arrives. + receiver: std::sync::mpsc::Receiver>, + /// How long to wait at most. + timeout: std::time::Duration, + /// What to do with it. + finish: Finish, +} + +impl std::fmt::Debug for Pending { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Pending") + .field("timeout", &self.timeout) + .finish_non_exhaustive() + } +} + +impl Pending { + /// A pending result. + /// + /// # Parameters + /// - `receiver`: receives the answer; a dropped sender counts as no + /// answer. + /// - `timeout`: the longest wait; the request's own timeout should be + /// shorter, so it reports first. + /// - `finish`: builds the value from the answer, under the lock. + pub fn new( + receiver: std::sync::mpsc::Receiver>, + timeout: std::time::Duration, + finish: impl FnOnce(&mut State, Reply) -> Result + Send + 'static, + ) -> Self { + Self { + receiver, + timeout, + finish: Box::new(finish), + } + } + + /// Blocks until the answer arrives, the sender is dropped or the + /// timeout (plus one second of grace) passes. Call it without the + /// engine lock. + pub fn wait(self) -> Answered { + let reply = self + .receiver + .recv_timeout(self.timeout + std::time::Duration::from_secs(1)) + .ok(); + Answered { + reply, + finish: self.finish, + } + } +} + +/// A [`Pending`] whose answer arrived (or never will); pass it to +/// [`crate::Engine::resolve`]. +pub struct Answered { + /// The answer. + reply: Reply, + /// What to do with it. + finish: Finish, +} + +impl std::fmt::Debug for Answered { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Answered") + .field("reply", &self.reply) + .finish_non_exhaustive() + } +} + +impl Answered { + /// Builds the value; for [`crate::Engine::resolve`]. + pub(crate) fn finish(self, state: &mut State) -> Result { + (self.finish)(state, self.reply) + } } /// A user-visible action. diff --git a/crates/engine/src/engine.rs b/crates/engine/src/engine.rs index 84fd9aa..58e1307 100644 --- a/crates/engine/src/engine.rs +++ b/crates/engine/src/engine.rs @@ -254,6 +254,64 @@ impl Engine { pub fn state(&self) -> &State { &self.state } + + /// Finishes a command whose [`Outcome::pending`] was answered (see + /// [`crate::Pending`]): builds its value inside the guard and returns it + /// with every event queued so far, like [`Engine::execute`]. + /// + /// # Errors + /// The command's error, or [`EngineError::Internal`] if it panicked. + pub fn resolve(&mut self, answered: crate::Answered) -> Result { + let state = &mut self.state; + let result = guard::run(|| { + let value = answered.finish(state); + crate::workspace::sync_buffer_dirs(state); + value + }); + result.map(|value| Outcome { + value, + events: state.take_events(), + ..Outcome::default() + }) + } +} + +/// Runs a command for a host that keeps the engine behind a lock, waiting +/// for a pending answer without the lock (see [`crate::Pending`]). +/// +/// # Parameters +/// - `lock`: locks the engine. +/// - `publish`: receives the events of each step while the lock is held, +/// so they stay in engine order. +/// +/// # Returns +/// The final outcome: its value is the resolved one; effects come from the +/// first step; events were already published. +/// +/// # Errors +/// The engine's error for the command or its resolution. +pub fn run_waiting>( + lock: impl Fn() -> G, + command: &str, + params: Value, + mut publish: impl FnMut(&[crate::Event]), +) -> Result { + let mut outcome = { + let mut engine = lock(); + let outcome = engine.execute(command, params)?; + publish(&outcome.events); + outcome + }; + outcome.events.clear(); + let Some(pending) = outcome.pending.take() else { + return Ok(outcome); + }; + let answered = pending.wait(); + let mut engine = lock(); + let resolved = engine.resolve(answered)?; + publish(&resolved.events); + outcome.value = resolved.value; + Ok(outcome) } #[cfg(test)] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index c336473..cc00479 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -21,8 +21,8 @@ pub mod theme; pub mod workspace; pub use buffers::{BufferId, LineEndingName, OpenBuffer}; -pub use command::{Command, CommandInfo, CommandSpec, Effect, Outcome}; -pub use engine::{Engine, EngineConfig}; +pub use command::{Answered, Command, CommandInfo, CommandSpec, Effect, Outcome, Pending, Reply}; +pub use engine::{Engine, EngineConfig, run_waiting}; pub use error::{EngineError, ErrorPayload}; pub use event::{Event, NotificationLevel, SearchMatch}; pub use registry::Registry; diff --git a/crates/engine/tests/pending.rs b/crates/engine/tests/pending.rs new file mode 100644 index 0000000..41879c0 --- /dev/null +++ b/crates/engine/tests/pending.rs @@ -0,0 +1,348 @@ +//! Pending outcomes: a command that waits for an answer from outside the +//! engine (a language server request) returns [`Pending`]; hosts wait for +//! it without the engine lock ([`run_waiting`]) and finish it under the +//! lock ([`Engine::resolve`]). Covers the answer, a dropped sender, the +//! deadline, the lock staying free while waiting, events of both steps, +//! and a language server restart while a request is pending. + +#![allow( + clippy::unwrap_used, + clippy::expect_used, + clippy::panic, + clippy::indexing_slicing +)] + +use std::ffi::OsString; +use std::path::PathBuf; +use std::sync::{Arc, Mutex, mpsc}; +use std::time::{Duration, Instant}; + +use lutra_engine::lsp::Launch; +use lutra_engine::{ + Command, CommandSpec, Engine, EngineError, Event, Outcome, Pending, Reply, State, run_waiting, +}; +use lutra_lsp::{LspError, ServerOptions}; +use serde_json::{Value, json}; + +/// How a [`Waits`] command's answer arrives. +#[derive(Clone, Copy)] +enum Answer { + /// From another thread after 100 ms. + Later, + /// Never: the sender is dropped at once. + Dropped, + /// Never: the sender is kept beyond the deadline (200 ms). + Stalls, + /// By the test: the sender is put into [`HANDED`]. + Handed, +} + +/// The sender of the last `Answer::Handed` command. +static HANDED: Mutex>>> = Mutex::new(None); + +/// `test.wait`: returns a pending outcome answered as `Answer` says; its +/// first step and its finish each queue one notification. +struct Waits(Answer, CommandSpec); + +impl Waits { + /// A `Waits` command with id `id`. + fn new(answer: Answer, id: &'static str) -> Self { + Self( + answer, + CommandSpec { + id, + label: "Wait", + menu_path: None, + default_shortcut: None, + params: "none", + }, + ) + } +} + +impl Command for Waits { + fn spec(&self) -> &CommandSpec { + &self.1 + } + + fn run(&self, state: &mut State, _params: Value) -> Result { + let (tx, rx) = mpsc::channel(); + match self.0 { + Answer::Later => { + std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(100)); + let _ = tx.send(Ok(json!(42))); + }); + } + Answer::Dropped => drop(tx), + Answer::Handed => *HANDED.lock().unwrap() = Some(tx), + Answer::Stalls => { + std::thread::spawn(move || { + std::thread::sleep(Duration::from_secs(3)); + drop(tx); + }); + } + } + state.notify( + lutra_engine::NotificationLevel::Info, + None, + Some("asked".into()), + None, + ); + Ok(Outcome::pending(Pending::new( + rx, + if matches!(self.0, Answer::Handed) { + Duration::from_secs(10) + } else { + Duration::from_millis(200) + }, + |state: &mut State, reply: Reply| { + state.notify( + lutra_engine::NotificationLevel::Info, + None, + Some("answered".into()), + None, + ); + match reply { + Some(Ok(value)) => Ok(json!({ "answer": value })), + Some(Err(e)) => Err(EngineError::Failed(e.to_string())), + None => Err(EngineError::Failed("no answer".into())), + } + }, + ))) + } +} + +/// An engine with the three test commands, behind a lock like in a host. +fn engine() -> Arc> { + let mut engine = Engine::new().unwrap(); + engine + .register(Box::new(Waits::new(Answer::Later, "test.later"))) + .unwrap(); + engine + .register(Box::new(Waits::new(Answer::Dropped, "test.dropped"))) + .unwrap(); + engine + .register(Box::new(Waits::new(Answer::Stalls, "test.stalls"))) + .unwrap(); + engine + .register(Box::new(Waits::new(Answer::Handed, "test.handed"))) + .unwrap(); + Arc::new(Mutex::new(engine)) +} + +/// The messages of the notifications among `events`. +fn messages(events: &[Event]) -> Vec { + events + .iter() + .filter_map(|e| match e { + Event::Notification { message, .. } => message.clone(), + _ => None, + }) + .collect() +} + +#[test] +fn the_answer_becomes_the_value_and_both_steps_publish() { + let engine = engine(); + let mut published = Vec::new(); + let out = run_waiting( + || engine.lock().unwrap(), + "test.later", + Value::Null, + |events| published.extend_from_slice(events), + ) + .unwrap(); + assert_eq!(out.value, json!({"answer": 42})); + assert!(out.pending.is_none()); + assert_eq!(messages(&published), ["asked", "answered"]); +} + +#[test] +fn the_lock_is_free_while_waiting() { + let engine = engine(); + let waiter = { + let engine = Arc::clone(&engine); + std::thread::spawn(move || { + run_waiting( + || engine.lock().unwrap(), + "test.handed", + Value::Null, + |_| {}, + ) + }) + }; + let deadline = Instant::now() + Duration::from_secs(10); + let answer = loop { + if let Some(tx) = HANDED.lock().unwrap().take() { + break tx; + } + assert!(Instant::now() < deadline, "the command never ran"); + std::thread::sleep(Duration::from_millis(1)); + }; + let about = loop { + if let Ok(mut engine) = engine.try_lock() { + break engine.execute("app.about", Value::Null).unwrap(); + } + assert!( + Instant::now() < deadline, + "the engine stayed locked while the command waited" + ); + std::thread::sleep(Duration::from_millis(1)); + }; + assert_eq!(about.value["name"], "Lutra"); + assert!(!waiter.is_finished(), "still waiting for its answer"); + answer.send(Ok(json!(42))).unwrap(); + assert_eq!(waiter.join().unwrap().unwrap().value["answer"], 42); +} +#[test] +fn a_dropped_sender_ends_at_once_with_the_finish_error() { + let engine = engine(); + let started = Instant::now(); + let err = run_waiting( + || engine.lock().unwrap(), + "test.dropped", + Value::Null, + |_| {}, + ) + .unwrap_err(); + assert_eq!(err, EngineError::Failed("no answer".into())); + assert!(started.elapsed() < Duration::from_millis(500)); +} + +#[test] +fn a_stalled_answer_ends_at_the_deadline() { + let engine = engine(); + let started = Instant::now(); + let err = run_waiting( + || engine.lock().unwrap(), + "test.stalls", + Value::Null, + |_| {}, + ) + .unwrap_err(); + assert_eq!(err, EngineError::Failed("no answer".into())); + let took = started.elapsed(); + assert!( + took >= Duration::from_millis(200) && took < Duration::from_millis(2_500), + "deadline plus one second of grace, took {took:?}" + ); +} + +#[test] +fn engine_resolve_runs_the_finish_with_the_lock() { + let engine = engine(); + let mut engine = engine.lock().unwrap(); + let mut out = engine.execute("test.later", Value::Null).unwrap(); + assert_eq!( + out.value, + Value::Null, + "the value comes from the pending answer" + ); + assert_eq!(messages(&out.events), ["asked"]); + let answered = out.pending.take().unwrap().wait(); + let resolved = engine.resolve(answered).unwrap(); + assert_eq!(resolved.value, json!({"answer": 42})); + assert_eq!(messages(&resolved.events), ["answered"]); +} + +/// The fake language server binary (see `tests/lsp.rs`). +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 +} + +/// `test.sleep`: sends the fake server's `fake/sleep`, which is never +/// answered, through [`lutra_engine::lsp::submit`]. +struct Sleeps; + +impl Command for Sleeps { + fn spec(&self) -> &CommandSpec { + &CommandSpec { + id: "test.sleep", + label: "Sleep", + menu_path: None, + default_shortcut: None, + params: "none", + } + } + + fn run(&self, state: &mut State, _params: Value) -> Result { + let (tx, rx) = mpsc::channel::>(); + let queued = lutra_engine::lsp::submit(state, move |server| { + let reply = tx.clone(); + let sent = server.request_with( + "fake/sleep", + json!({}), + Duration::from_secs(30), + Box::new(move |result| { + let _ = reply.send(result); + }), + ); + if let Err(e) = sent { + let _ = tx.send(Err(e)); + } + }); + assert!(queued, "a session runs"); + Ok(Outcome::pending(Pending::new( + rx, + Duration::from_secs(30), + |_state, reply| match reply { + Some(Ok(value)) => Ok(value), + Some(Err(e)) => Err(EngineError::Failed(e.to_string())), + None => Err(EngineError::Failed("the server stopped".into())), + }, + ))) + } +} + +#[test] +fn a_language_server_restart_ends_a_pending_request_with_an_error() { + let dir = tempfile::tempdir().unwrap(); + let mut engine = Engine::new().unwrap(); + engine.register(Box::new(Sleeps)).unwrap(); + engine.set_language_server(Some(Launch { + command: fake_server().into(), + args: Vec::::new(), + options: ServerOptions::default(), + tick: None, + })); + engine + .execute("project.open", json!({"path": dir.path()})) + .unwrap(); + let deadline = Instant::now() + Duration::from_secs(20); + while engine.state().lsp.status().state != lutra_engine::lsp::LspState::Ready { + assert!(Instant::now() < deadline, "the fake server never got ready"); + engine.pump_vfs().unwrap(); + std::thread::sleep(Duration::from_millis(5)); + } + let engine = Arc::new(Mutex::new(engine)); + let waiter = { + let engine = Arc::clone(&engine); + std::thread::spawn(move || { + let started = Instant::now(); + let result = run_waiting(|| engine.lock().unwrap(), "test.sleep", Value::Null, |_| {}); + (result, started.elapsed()) + }) + }; + std::thread::sleep(Duration::from_millis(300)); + { + let mut engine = engine.lock().unwrap(); + engine.execute("lsp.restart", Value::Null).unwrap(); + engine.pump_vfs().unwrap(); + } + let (result, took) = waiter.join().unwrap(); + let err = result.unwrap_err(); + assert_eq!(err.code(), "failed", "{err}"); + assert!(took < Duration::from_secs(10), "took {took:?}"); +} diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index b712162..4d7488a 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -87,9 +87,13 @@ impl Default for EngineBackend { impl Backend for EngineBackend { fn execute(&self, command: &str, params: Value) -> Result { - let out = self.engine.lock().unwrap().execute(command, params)?; + let out = lutra_engine::run_waiting( + || self.engine.lock().unwrap(), + command, + params, + |events| self.subscribers.publish(events), + )?; self.effects.lock().unwrap().extend(out.effects); - self.subscribers.publish(&out.events); Ok(out.value) } diff --git a/docs/architecture.md b/docs/architecture.md index b655f69..c7430a2 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -402,6 +402,26 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat - `crates/control/tests/lsp.rs` runs over TCP with ticks on. - Vitest: `ui/tests/editor/lint.test.ts` and `ui/tests/problems/ProblemsToolWindow.test.ts`. +### Pending outcomes: commands that wait for the language server (M3.5) + +- **Why:** `lsp.definition` returns `{locations}`, `lsp.completion` returns items. The answer comes from Phpactor, and nothing may wait for it under the engine lock (M3.3). +- **API** (`crates/engine/src/command.rs`, `engine.rs`): + - A command queues its request with `lsp::submit(state, |server| server.request_with(…, callback))`; the callback sends into an `mpsc` channel. + - The command returns `Outcome::pending(Pending::new(receiver, timeout, finish))` at once. + - The host calls `Pending::wait()` *without* the lock. It returns when the answer arrives, the sender is dropped or the deadline passes (timeout + 1 s of grace; the request's own timeout should be shorter, so it reports first). + - Then, with the lock again, `Engine::resolve(answered)` runs `finish(state, reply)` in the guard. `reply` is `Some(Ok(value))`, `Some(Err(LspError))` or `None` (no answer). The finish builds the value and may change the state; a rename applies its edit here. + - `lutra_engine::run_waiting(lock, command, params, publish)` does all three steps for a host. Events of each step are published while the lock is held. Effects come from the first step. +- **Hosts:** `Host::run` (desktop), `testkit::EngineBackend` and the control protocol's test backend use `run_waiting`. Control-channel and MCP callers (one thread per connection) get the final value directly. +- **IPC and ordering:** + - `engine_execute` stays a synchronous Tauri command on the main thread, so every ordinary command (`buffer.edit` above all) runs in call order, as before. + - The new `engine_execute_waiting` (`#[tauri::command(async)]`, `runWaiting` in `ui/src/ipc.ts`) runs `Host::run` off the main thread, so the window stays responsive while Phpactor works. Only `lsp.*` requests use it. + - `engine_execute` itself did not move off the main thread, unlike the first plan: moving it would let two ordinary commands race for the lock, and the order of `buffer.edit` calls must stay the call order. + - The order towards Phpactor is fixed under the engine lock: `buffer.edit` queues its `didChange` on the session queue (`lsp::record_edits`) before it returns, and `submit` queues the request on the same FIFO queue. A request therefore sees every edit whose `buffer.edit` returned before it, and the frontend awaits the buffer sync's `idle()` before sending one. +- **Failures:** + - Phpactor stalls: the request times out in `lutra-lsp`; the waiter's deadline is the backstop. + - `lsp.restart`, project close, `app.quit` (`shutdown_now`) or a crash: queued jobs are dropped and in-flight requests resolve with `Stopped`/`ServerCrashed`, so the waiter gets an error at once instead of hanging (test: `crates/engine/tests/pending.rs`). + - A finish must check that its answer still applies to the state; `lsp.rename` refuses when a buffer's version changed since the request. + ### Toolchain (M3.1) - **Owner decision D15:** Lutra downloads the Phpactor PHAR itself; PHP is the user's (found through `php.executable` or `PATH`). Library code lives in `crates/lsp/src/toolchain/` (L3), the engine side in `crates/engine/src/cmd/toolchain.rs`. @@ -444,6 +464,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat | Date | Change | Summary | |---|---|---| +| 2026-10-22 | minor | M3.5 step 1: pending outcomes (`Pending`, `Engine::resolve`, `run_waiting`), `engine_execute_waiting` / `runWaiting` | | 2026-10-20 | minor | M3.10: autosave (blur, tab switch, idle), `flushDirty`, `file.saveAll {skipConflicts}`, disk conflicts and own-write hashes in `Buffers` | | 2026-10-21 | minor | M3.3: engine ↔ Phpactor wiring (session thread, ordered sync, `lspStatus`, `diagnosticsChanged`, `diagnostics.list`, `lsp.status`, `lsp.restart`), Phpactor-on-Windows workarounds, lint extension, Problems tab | | 2026-10-19 | minor | M3.8: MCP server (`lutra mcp`, dual era 2026-07-28 + legacy `initialize`), tools, resources, event buffer; `buffer.list` | diff --git a/ui/src/ipc.ts b/ui/src/ipc.ts index 46b87e7..e87c082 100644 --- a/ui/src/ipc.ts +++ b/ui/src/ipc.ts @@ -283,6 +283,28 @@ export async function run( } } +/** + * Runs an engine command that waits for the language server (`lsp.*`, + * M3.5) on a worker thread of the shell, so the window stays responsive + * while the server works. Unlike {@link run}, calls are not ordered with + * other commands: let edits reach the engine first (`BufferSync.idle`). + * + * @param commandId - the command id, e.g. `lsp.definition`. + * @param params - the command's params object. + * @returns the command's result, or the error it failed with. + */ +export async function runWaiting( + commandId: string, + params: JsonValue = {}, +): Promise> { + try { + const value = await invoke("engine_execute_waiting", { command: commandId, params }); + return { ok: true, value }; + } catch (reason: unknown) { + return { ok: false, error: toEngineError(reason) }; + } +} + /** * Lists every command the engine knows, with its current enabled state. * diff --git a/ui/tests/ipc.test.ts b/ui/tests/ipc.test.ts index c02054d..63fd931 100644 --- a/ui/tests/ipc.test.ts +++ b/ui/tests/ipc.test.ts @@ -7,7 +7,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; const invoke = vi.hoisted(() => vi.fn()); vi.mock("@tauri-apps/api/core", () => ({ invoke })); -import { listCommands, run, toEngineError } from "../src/ipc"; +import { listCommands, run, runWaiting, toEngineError } from "../src/ipc"; describe("run", () => { beforeEach(() => { @@ -45,6 +45,19 @@ describe("run", () => { expect(await listCommands()).toEqual({ ok: true, value: [] }); expect(invoke).toHaveBeenCalledWith("engine_list_commands"); }); + + it("runs waiting commands through the async shell command", async () => { + invoke.mockResolvedValue({ locations: [] }); + const result = await runWaiting("lsp.definition", { id: 1 }); + expect(result).toEqual({ ok: true, value: { locations: [] } }); + expect(invoke).toHaveBeenCalledWith("engine_execute_waiting", { + command: "lsp.definition", + params: { id: 1 }, + }); + invoke.mockRejectedValue({ code: "failed", message: "the PHP language server is not running" }); + const failed = await runWaiting("lsp.definition", { id: 1 }); + expect(failed.ok ? null : failed.error.code).toBe("failed"); + }); }); describe("toEngineError", () => {