diff --git a/Cargo.lock b/Cargo.lock index 7674f46..a912c3c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2513,6 +2513,7 @@ dependencies = [ "serde_json", "tauri", "tauri-build", + "tauri-plugin-dialog", "xcap", ] @@ -3670,6 +3671,30 @@ dependencies = [ "web-sys", ] +[[package]] +name = "rfd" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a15ad77d9e70a92437d8f74c35d99b4e4691128df018833e99f90bcd36152672" +dependencies = [ + "block2", + "dispatch2", + "glib-sys", + "gobject-sys", + "gtk-sys", + "js-sys", + "log", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "raw-window-handle", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "windows-sys 0.60.2", +] + [[package]] name = "ropey" version = "1.6.1" @@ -4421,6 +4446,64 @@ dependencies = [ "tauri-utils", ] +[[package]] +name = "tauri-plugin" +version = "2.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74be5dd4bed9afbd145e5716b5fa2ec28cbc29c34ffa61c258c9273d896c8020" +dependencies = [ + "anyhow", + "glob", + "plist", + "schemars 0.8.22", + "serde", + "serde_json", + "tauri-utils", + "walkdir", +] + +[[package]] +name = "tauri-plugin-dialog" +version = "2.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61854a36651aa48381e5e209f69a01273b77f3f9f91f0c430b1b98d33bd47229" +dependencies = [ + "log", + "raw-window-handle", + "rfd", + "serde", + "serde_json", + "tauri", + "tauri-plugin", + "tauri-plugin-fs", + "thiserror 2.0.21", + "url", +] + +[[package]] +name = "tauri-plugin-fs" +version = "2.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de22eef34fd78c0da050e748710edd50bf127e651d02ea1b2bfada1523cc5c51" +dependencies = [ + "anyhow", + "dunce", + "glob", + "log", + "objc2-foundation", + "percent-encoding", + "schemars 0.8.22", + "serde", + "serde_json", + "serde_repr", + "tauri", + "tauri-plugin", + "tauri-utils", + "thiserror 2.0.21", + "toml 1.1.8+spec-1.1.0", + "url", +] + [[package]] name = "tauri-runtime" version = "2.11.3" diff --git a/README.md b/README.md index 4639037..eb3e68e 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,7 @@ claude mcp add lutra -- lutra mcp ## Status -**Pre-alpha (2026-10-14): foundation done.** No PHP feature ships yet; the MVP (M1–M3) is estimated at about 190 agent hours. [**ROADMAP.md**](ROADMAP.md) has the stage and what's next, +**Pre-alpha (2026-10-15): M1 in progress.** You can open a folder and browse it in the project tree, with live updates from disk; editing in the UI and PHP features come next. The MVP (M1–M3) is estimated at about 190 agent hours. [**ROADMAP.md**](ROADMAP.md) has the stage and what's next, [`docs/target-app-parity.md`](docs/target-app-parity.md) the parity assessment and [`docs/gaps.md`](docs/gaps.md) the ranked work list. **First target (MVP, M1–M3):** open a project, project tree, tabs, editor with highlighting, find in files, diff --git a/ROADMAP.md b/ROADMAP.md index 8c2f4bf..7f9e832 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: pre-alpha (foundation done)** · next: M1 editor and project; alpha when the six core workflows work end to end (see [docs/roadmap.md › Alpha gate](docs/roadmap.md#alpha-gate)) -> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-14 · **Change:** minor (M0 done, first estimates) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only +> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-15 · **Change:** minor (project tree works against the engine) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only Lutra is a clean-room, open-source PHP IDE with a Rust core and a Tauri + Vue interface, targeting the PhpStorm workflow. Agents can drive all of it over MCP, the `lutra` CLI and a JSON control channel. This page is the summary; the evidence is in [`docs/target-app-parity.md`](docs/target-app-parity.md) and the work list in [`docs/gaps.md`](docs/gaps.md). @@ -13,7 +13,7 @@ Lutra is a clean-room, open-source PHP IDE with a Rust core and a Tauri + Vue in | | Value | Kind | |---|---|---| | **Feature breadth** (PhpStorm's actions, tool windows, languages, integrations exist) | **0%** | measured | -| **Feature depth** (weighted by use, scored by behaviour) | **0%** | measured | +| **Feature depth** (weighted by use, scored by behaviour) | **~0.5%** (Project view 8% × weight 6) | estimated | | **To MVP (M3)** | **~190 h** (M1 ~60 h, M2 ~50 h, M3 ~80 h) | estimated | | **To full parity** | **~3,300 h** (range 2,000–5,000 h) | estimated | @@ -25,7 +25,7 @@ Dimension hours overlap: language, framework and tooling hours are part of the f | Dimension | % | One agent (h) | Doc | |---|---:|---:|---| -| Features (depth) | 0% | ~2,930 | [target-app-parity.md](docs/target-app-parity.md) | +| Features (depth) | ~0.5% | ~2,930 | [target-app-parity.md](docs/target-app-parity.md) | | UI/UX fidelity | 0% | ~150 on top of features | [ui-parity.md](docs/ui-parity.md) | | PHP language support | 0% | ~920 (in features) | [language-parity.md](docs/language-parity.md) | | Frameworks (Symfony, Laravel, Shopware, WordPress) | 0% | ~300 (in features) | [framework-parity.md](docs/framework-parity.md) | @@ -42,7 +42,7 @@ Stability 5%: no-panic lints, the engine guard and a fuzzed control protocol exi | Area | % | One agent (h) | |---|---:|---:| | Editor core (buffers, undo, multi-caret, folding, soft wrap) | 0% | ~120 | -| Project view, VFS, file watching | 0% | ~40 | +| Project view, VFS, file watching | 8% (est.) | ~40 | | Navigation (go to class/file/symbol, recent files, structure) | 0% | ~120 | | Search and replace (in file, in project, structural) | 0% | ~80 | | Code completion | 0% | ~250 | @@ -77,6 +77,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a | Date | What landed | |---|---| +| 2026-10-15 | M1 so far: text buffer, VFS with native watching, engine workspace (files, buffers, edit protocol, events), desktop bridge: open a folder by picker or command line, browse it in the project tree with live updates from disk. | | 2026-10-14 | M0 foundation: Cargo workspace with layered crates, no-panic lints with a self-test, `cargo xtask ci` (fmt, clippy, tests, layers, assets, clean-room, licences, frontend lint/typecheck/tests), Vue frontend, command registry with panic guard (`app.about`, `app.quit`), JSON control channel, Tauri window themed from Rust tokens, CI workflow. First estimates. | | 2026-10-13 | Project started: name, conventions, agent rules and progress docs. | @@ -84,5 +85,6 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a | Date | Change | Summary | |---|---|---| +| 2026-10-15 | minor | Feature depth above 0%: project tree runs against the engine (M1.4) | | 2026-10-14 | minor | M0 done; MVP and parity estimates; stability and agent automation scored | | 2026-10-13 | major | Initial roadmap | diff --git a/apps/lutra-desktop/Cargo.toml b/apps/lutra-desktop/Cargo.toml index a8e7c43..dc2f22d 100644 --- a/apps/lutra-desktop/Cargo.toml +++ b/apps/lutra-desktop/Cargo.toml @@ -19,6 +19,7 @@ lutra-control.workspace = true lutra-engine.workspace = true serde_json = "1.0.154" tauri = { version = "2.11.6", features = [] } +tauri-plugin-dialog = "2.7.3" xcap = "0.9.8" [build-dependencies] diff --git a/apps/lutra-desktop/capabilities/default.json b/apps/lutra-desktop/capabilities/default.json index f87573b..204e5f7 100644 --- a/apps/lutra-desktop/capabilities/default.json +++ b/apps/lutra-desktop/capabilities/default.json @@ -1,7 +1,7 @@ { "$schema": "../gen/schemas/desktop-schema.json", "identifier": "default", - "description": "Permissions of the main window", + "description": "Permissions of the main window: listening to engine events. Engine commands are app commands and need no permission; the folder picker is opened from Rust.", "windows": ["main"], - "permissions": ["core:default"] + "permissions": ["core:event:allow-listen", "core:event:allow-unlisten"] } diff --git a/apps/lutra-desktop/src/host.rs b/apps/lutra-desktop/src/host.rs index 4792f06..f154c52 100644 --- a/apps/lutra-desktop/src/host.rs +++ b/apps/lutra-desktop/src/host.rs @@ -1,13 +1,23 @@ -//! The host: owns the engine, applies effects to the Tauri app and serves -//! the control channel's [`Backend`]. +//! The host: owns the engine, applies effects to the Tauri app, publishes +//! engine events to the window and to control channel subscribers, pumps +//! changes on disk into the engine, and serves the control channel's +//! [`Backend`]. +//! +//! Events reach the frontend as the Tauri event [`ENGINE_EVENT`] with the +//! engine's `Event` as payload. Events are published while the engine lock is +//! held, so commands and the pump thread never reorder them. -use std::path::Path; -use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError, Weak}; +use std::thread; +use std::time::Duration; use lutra_control::{Backend, EventSink, Subscribers}; -use lutra_engine::{CommandInfo, Effect, Engine, EngineError}; -use serde_json::Value; -use tauri::AppHandle; +use lutra_engine::{CommandInfo, Effect, Engine, EngineError, Event}; +use serde_json::{Value, json}; +use tauri::{AppHandle, Emitter}; +use tauri_plugin_dialog::DialogExt; use crate::screenshot; @@ -17,16 +27,25 @@ pub const WINDOW_TITLE: &str = "Lutra"; /// Label of the main window. pub const MAIN_WINDOW: &str = "main"; -/// Engine plus the handle needed to apply effects. +/// Name of the Tauri event that carries engine events to the frontend. +pub const ENGINE_EVENT: &str = "engine://event"; + +/// Time between two pumps of changes on disk. +const PUMP_INTERVAL: Duration = Duration::from_millis(100); + +/// Engine plus the handles needed to apply effects and publish events. pub struct Host { /// The engine. Commands run inside its guard, so the lock is never /// poisoned by a command; a poisoned lock is still recovered. engine: Mutex, /// The Tauri app, set once the app is set up. app: OnceLock, - /// Control channel connections subscribed to engine events. Forwarding - /// events to the frontend and pumping changes on disk arrive with M1.4. + /// Control channel connections subscribed to engine events. subscribers: Subscribers, + /// This host, for callbacks that outlive a call (the folder picker). + me: Weak, + /// A folder picker is open; another request is ignored until it closes. + picking: AtomicBool, } impl Host { @@ -34,12 +53,15 @@ impl Host { /// /// # Errors /// The engine's error if the built-in commands cannot be registered. - pub fn new() -> Result { - Ok(Self { - engine: Mutex::new(Engine::new()?), + pub fn new() -> Result, EngineError> { + let engine = Engine::new()?; + Ok(Arc::new_cyclic(|me| Self { + engine: Mutex::new(engine), app: OnceLock::new(), subscribers: Subscribers::default(), - }) + me: me.clone(), + picking: AtomicBool::new(false), + })) } /// Records the app handle once Tauri has started. Later calls are @@ -53,13 +75,29 @@ impl Host { self.engine.lock().unwrap_or_else(PoisonError::into_inner) } - /// Runs a command, applies its effects and publishes its events. + /// Sends events to the control channel subscribers and the window. + /// Emitting to the window fails only when the window is gone, in which + /// case nobody is listening, so that error is ignored. + fn publish(&self, events: &[Event]) { + self.subscribers.publish(events); + if let Some(app) = self.app.get() { + for event in events { + let _ = app.emit(ENGINE_EVENT, event); + } + } + } + + /// Runs a command, publishes its events and applies its effects. /// /// # Errors /// The engine's error for the command. pub fn run(&self, command: &str, params: Value) -> Result { - let outcome = self.engine().execute(command, params)?; - self.subscribers.publish(&outcome.events); + let outcome = { + let mut engine = self.engine(); + let outcome = engine.execute(command, params)?; + self.publish(&outcome.events); + outcome + }; for effect in outcome.effects { self.apply(effect); } @@ -71,14 +109,116 @@ impl Host { self.engine().list_commands() } + /// Opens the folder at `path` as the project; a relative path is taken + /// relative to the current directory. + /// + /// # Errors + /// The engine's error, e.g. when the folder does not exist. + pub fn open_project(&self, path: &Path) -> Result { + let path = if path.is_absolute() { + path.to_path_buf() + } else { + std::env::current_dir() + .map(|dir| dir.join(path)) + .unwrap_or_else(|_| path.to_path_buf()) + }; + self.run("project.open", json!({ "path": path })) + } + + /// Sends the window the events that describe the current state (the open + /// project and its buffers), for a frontend that just started listening + /// and missed them. Control channel subscribers are not affected. + pub fn replay_to_window(&self) { + let Some(app) = self.app.get() else { return }; + let engine = self.engine(); + let state = engine.state(); + let Some(workspace) = &state.project else { + return; + }; + let root = workspace.project.root(); + let event = Event::ProjectOpened { + root: root.to_string_lossy().into_owned(), + name: root + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_else(|| root.to_string_lossy().into_owned()), + }; + let _ = app.emit(ENGINE_EVENT, &event); + for id in state.buffers.ids() { + if let Some(open) = state.buffers.get(id) { + let event = Event::BufferOpened { + id, + path: lutra_engine::workspace::path_string(&open.path), + }; + let _ = app.emit(ENGINE_EVENT, &event); + } + } + } + + /// Starts the thread that applies changes on disk every + /// [`PUMP_INTERVAL`] and publishes the resulting events. The thread ends + /// with the host. A pump that panicked is reported and retried on the + /// next tick. + /// + /// # Errors + /// If the thread cannot be spawned. + pub fn start_pump(&self) -> std::io::Result<()> { + let me = self.me.clone(); + thread::Builder::new() + .name("lutra-vfs-pump".into()) + .spawn(move || { + loop { + thread::sleep(PUMP_INTERVAL); + let Some(host) = me.upgrade() else { return }; + let mut engine = host.engine(); + match engine.pump_vfs() { + Ok(events) => host.publish(&events), + Err(e) => eprintln!("lutra: applying changes on disk failed: {e}"), + } + } + }) + .map(|_| ()) + } + /// Applies one effect. Before the app is attached there is nothing to /// act on, so effects are dropped. fn apply(&self, effect: Effect) { let Some(app) = self.app.get() else { return }; match effect { Effect::Quit => app.exit(0), + Effect::PickFolder => self.pick_folder(app), } } + + /// Shows the native folder picker without blocking and opens the chosen + /// folder. Only one picker is open at a time; a request while one is + /// open is ignored. Cancelling does nothing. A folder that cannot be + /// opened is reported on stderr until the frontend can show + /// notifications. + fn pick_folder(&self, app: &AppHandle) { + if self.picking.swap(true, Ordering::AcqRel) { + return; + } + let me = self.me.clone(); + app.dialog() + .file() + .set_title("Open Folder") + .pick_folder(move |folder| { + let Some(host) = me.upgrade() else { return }; + host.picking.store(false, Ordering::Release); + let Some(folder) = folder else { return }; + let path: PathBuf = match folder.into_path() { + Ok(path) => path, + Err(e) => { + eprintln!("lutra: the picked folder is not a local path: {e}"); + return; + } + }; + if let Err(e) = host.open_project(&path) { + eprintln!("lutra: cannot open {}: {e}", path.display()); + } + }); + } } impl Backend for Host { diff --git a/apps/lutra-desktop/src/main.rs b/apps/lutra-desktop/src/main.rs index 6a126cf..728ca45 100644 --- a/apps/lutra-desktop/src/main.rs +++ b/apps/lutra-desktop/src/main.rs @@ -1,8 +1,9 @@ //! The Lutra desktop app (layer L6): a Tauri 2 shell around the engine. //! //! Builds the main window with the theme tokens injected before first paint, -//! bridges frontend IPC to engine commands, and optionally serves the JSON -//! control channel (`--control PORT`). +//! bridges frontend IPC to engine commands and engine events to the window +//! (see [`host`]), opens the project given on the command line, and +//! optionally serves the JSON control channel (`--control PORT`). #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] @@ -53,25 +54,24 @@ fn main() -> ExitCode { /// A message if the engine cannot start, the control port cannot be bound, /// or Tauri fails. fn run(args: &args::Args) -> Result<(), String> { - let host = Arc::new(Host::new().map_err(|e| e.to_string())?); + let host = Host::new().map_err(|e| e.to_string())?; if let Some(port) = args.control { let server = lutra_control::start(port, host.clone()) .map_err(|e| format!("cannot serve the control channel on port {port}: {e}"))?; eprintln!("lutra: control channel on {}", server.local_addr()); } - if let Some(path) = &args.path { - eprintln!( - "lutra: opening {} arrives with milestone M1; starting without a project", - path.display() - ); - } + host.start_pump() + .map_err(|e| format!("cannot start watching for changes: {e}"))?; let theme = theme::DARK; let setup_host = host.clone(); + let initial_path = args.path.clone(); tauri::Builder::default() + .plugin(tauri_plugin_dialog::init()) .manage(host) .invoke_handler(tauri::generate_handler![ engine_execute, - engine_list_commands + engine_list_commands, + engine_ready ]) .setup(move |app| { setup_host.attach(app.handle().clone()); @@ -84,6 +84,11 @@ fn run(args: &args::Args) -> Result<(), String> { window = window.background_color(color); } window.build()?; + if let Some(path) = &initial_path + && let Err(e) = setup_host.open_project(path) + { + eprintln!("lutra: cannot open {}: {e}", path.display()); + } Ok(()) }) .run(tauri::generate_context!()) @@ -115,6 +120,13 @@ fn engine_list_commands(host: tauri::State<'_, Arc>) -> Vec { host.commands() } +/// IPC: the frontend listens for engine events now; replays the current +/// project state it may have missed while loading. +#[tauri::command] +fn engine_ready(host: tauri::State<'_, Arc>) { + host.replay_to_window(); +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 4703c49..6947bab 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -16,6 +16,7 @@ pub fn register_builtins(registry: &mut Registry) -> Result<(), EngineError> { registry.register(Box::new(app::About))?; registry.register(Box::new(app::Quit))?; registry.register(Box::new(project::Open))?; + registry.register(Box::new(project::OpenDialog))?; registry.register(Box::new(project::Close))?; registry.register(Box::new(project::Children))?; registry.register(Box::new(file::Open))?; diff --git a/crates/engine/src/cmd/project.rs b/crates/engine/src/cmd/project.rs index 28eb14d..df88b30 100644 --- a/crates/engine/src/cmd/project.rs +++ b/crates/engine/src/cmd/project.rs @@ -1,11 +1,32 @@ -//! Project commands: `project.open`, `project.close`, `project.children`. +//! Project commands: `project.open`, `project.openDialog`, `project.close`, +//! `project.children`. use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use super::params::{parse, project_path}; use crate::workspace::{Workspace, path_string, vfs_error}; -use crate::{Command, CommandSpec, EngineError, Event, Outcome, State}; +use crate::{Command, CommandSpec, Effect, EngineError, Event, Outcome, State}; + +/// `project.openDialog`: asks the host to show the folder picker; the host +/// runs `project.open` with the chosen folder. +pub struct OpenDialog; + +impl Command for OpenDialog { + fn spec(&self) -> &CommandSpec { + &CommandSpec { + id: "project.openDialog", + label: "Open Folder…", + menu_path: Some("File/Open Folder…"), + default_shortcut: Some("Mod+O"), + params: "none; returns null and the effect pickFolder: the host shows the folder picker and runs project.open with the choice; cancelling is not an error", + } + } + + fn run(&self, _state: &mut State, _params: Value) -> Result { + Ok(Outcome::effect(Effect::PickFolder)) + } +} /// Closes the open project and all its buffers. /// diff --git a/crates/engine/src/command.rs b/crates/engine/src/command.rs index 7024bd1..34dbdc9 100644 --- a/crates/engine/src/command.rs +++ b/crates/engine/src/command.rs @@ -28,6 +28,9 @@ pub struct CommandSpec { pub enum Effect { /// Quit the application. Quit, + /// Show the native folder picker and run `project.open` with the chosen + /// folder. Cancelling the picker does nothing and is not an error. + PickFolder, } /// Result of a successful command. diff --git a/crates/engine/src/engine.rs b/crates/engine/src/engine.rs index b1dd88f..3dcbf17 100644 --- a/crates/engine/src/engine.rs +++ b/crates/engine/src/engine.rs @@ -176,6 +176,14 @@ mod tests { assert_eq!(out.effects, vec![Effect::Quit]); } + #[test] + fn open_dialog_asks_the_host_to_pick_a_folder() { + let mut engine = Engine::new().unwrap(); + let out = engine.execute("project.openDialog", Value::Null).unwrap(); + assert_eq!(out.effects, vec![Effect::PickFolder]); + assert_eq!(out.value, Value::Null); + } + #[test] fn unknown_and_disabled_commands_fail() { let mut engine = Engine::new().unwrap(); @@ -233,6 +241,7 @@ mod tests { "project.children", "project.close", "project.open", + "project.openDialog", "test.disabled", ] ); diff --git a/docs/architecture.md b/docs/architecture.md index 1ec8dc1..6db1a53 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,6 +1,6 @@ # Architecture -> **Status:** M0 decisions recorded · **Last updated:** 2026-10-14 +> **Status:** M0 decisions recorded, M1 workspace and desktop bridge documented · **Last updated:** 2026-10-15 ## Overview @@ -80,10 +80,18 @@ Theme tokens are defined in Rust (`lutra_engine::theme`) and rendered as CSS cus `lutra_engine::Event`, serialised as `{"kind": "", ...}`: `projectOpened {root, name}`, `projectClosed`, `treeChanged {dir}`, `bufferOpened {id, path}`, `bufferChanged {id, version}`, `dirtyChanged {id, dirty}`, `bufferClosed {id}`, `fileChangedOnDisk {path, id, removed}`, `watchFailed {message}`. Events say what changed; clients fetch data with `project.children` and `buffer.get`. -Changes on disk reach the engine through `Engine::pump_vfs()`, which hosts call regularly (the desktop's pump thread arrives with M1.4; tests call it directly). It maps VFS events to `treeChanged` for the parent directories, reloads a clean buffer whose file changed (unless the file already matches, as after our own save) with `bufferChanged`, and reports `fileChangedOnDisk` for a dirty buffer, which keeps its text, or for a removed file. At most 10,000 VFS events are handled per pump. +Changes on disk reach the engine through `Engine::pump_vfs()`, which hosts call regularly (the desktop's pump thread every 100 ms; tests call it directly). It maps VFS events to `treeChanged` for the parent directories, reloads a clean buffer whose file changed (unless the file already matches, as after our own save) with `bufferChanged`, and reports `fileChangedOnDisk` for a dirty buffer, which keeps its text, or for a removed file. At most 10,000 VFS events are handled per pump. Watched directories: the VFS watcher is non-recursive, so `project.children` watches each directory it lists. At most 256 directories besides the root are watched natively and 32 when polling (each polled directory is rescanned every 100 ms); beyond that the least recently listed directory is unwatched, and listing it again re-watches it. Expanding a deep `vendor/` therefore costs at most 256 native watches; changes in directories that dropped out are not reported until they are listed again. `node_modules`, ignored and hidden directories are never watched. +### Desktop bridge (M1.4) + +- The desktop host publishes every event, from commands and from its pump thread, to control channel subscribers and to the window as the Tauri event `engine://event` with the engine `Event` as payload. Events are published while the engine lock is held, so their order is the engine's order. +- `ui/src/ipc.ts` exposes `onEngineEvent(handler) => unsubscribe` with the typed union `EngineEventPayload`. The first successful subscription calls the IPC command `engine_ready`; the host then replays `projectOpened` and `bufferOpened` for the current state to the window only. A project opened from the command line (`lutra-desktop --control 7979 PATH`) or before a page reload therefore still reaches the UI. +- `project.openDialog` returns `Effect::PickFolder`; the host shows the native folder picker (`tauri-plugin-dialog`, from Rust, non-blocking) and runs `project.open` with the choice. At most one picker is open; cancelling does nothing. A folder that cannot be opened (for example `unsaved_changes`) is only logged to stderr until the UI can show notifications. +- Capabilities: the main window may only listen to and unlisten from events (`core:event:allow-listen`, `core:event:allow-unlisten`). Engine commands are app commands and need no permission; the dialog plugin is used from Rust only, so the frontend gets no dialog permission. +- Contract fix: the project UI from M1.5 was written against assumed shapes. `ui/src/components/project/engineEvents.ts` is now the adapter between the engine contract and the UI types: `toProjectEvent` translates `{kind: "projectOpened", root, name}` and friends into the store's events, and `toTreeEntries` translates `project.children`'s `{dir, entries: [{name, path, kind: file|directory|other, ignored, role}], truncated}` into tree entries (`kind: dir|file`, `role`, `excluded`, `special` for `other`) plus `truncated`. Malformed entries are skipped; a result without `entries` becomes an `ipc` error on the directory. + ## Decisions (M0) | Question | Decision | Why | @@ -101,6 +109,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat | Date | Change | Summary | |---|---|---| +| 2026-10-15 | minor | M1.4: desktop bridge (engine://event, engine_ready replay, folder picker, capabilities), UI contract fix | | 2026-10-14 | minor | M1.3: workspace commands, edit protocol, events, events.subscribe, watched-directory limits | | 2026-10-14 | minor | Screenshot method, placeholder app identifier | | 2026-10-13 | major | M0: layers metadata, command and guard design, control protocol, open questions decided | diff --git a/docs/gaps.md b/docs/gaps.md index 1eb44b0..a375069 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers) · **Last updated:** 2026-10-14 +> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers); G3 project tree works in the app · **Last updated:** 2026-10-15 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. @@ -8,7 +8,7 @@ Every known shortfall, ranked. This is the work list: unless the owner gives a t |---|---|---|---| | G1 | ~~Foundation: workspace, quality gate, command registry, guard, control channel~~ closed 2026-10-14 | M0 | done (~2 h measured) | | G2 | Editor core: ~~engine buffers, save~~ (M1.3), editor UI, undo, multi-caret, recovery journal | M1 | ~25 h | -| G3 | Project model: ~~VFS~~ (M1.2: listing, ignore rules, native file watching with polling fallback, safe file IO), project tree (UI exists against a mocked engine, M1.5; engine side with `project.children` and tree events landed in M1.3; wiring in M1.4), tabs; command palette, settings, theme switching | M1 | ~27 h | +| G3 | Project model: ~~VFS~~ (M1.2: listing, ignore rules, native file watching with polling fallback, safe file IO), ~~project tree wiring~~ (M1.5 UI, M1.3 engine, M1.4 bridge: folder picker, live tree), tree toolbar and options, showing truncated listings, error notifications for the folder picker, tabs; command palette, settings, theme switching | M1 | ~24 h | | G4 | Syntax and structure: tree-sitter PHP, Lezer highlighting, file structure | M2 | ~15 h | | G5 | Search and navigation: find in files, go to file/class/symbol, first index | M2 | ~35 h | | G6 | Language server: completion, diagnostics, definition, hover, rename via Phpactor | M3 | ~45 h | @@ -35,6 +35,7 @@ Known smaller items from M0: | Date | Change | Summary | |---|---|---| +| 2026-10-15 | minor | G3 shrunk: project tree wired to the engine (M1.4) | | 2026-10-14 | minor | G2 shrunk, G3 note: engine workspace (M1.3) | | 2026-10-14 | minor | G3 note: project tree UI (M1.5) | | 2026-10-14 | minor | G2 note: text buffer landed (M1.1) | diff --git a/docs/roadmap.md b/docs/roadmap.md index b00d53c..06aa8b5 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,13 +1,13 @@ # Milestones -> **Status:** M0 done, M1 in progress · **Last updated:** 2026-10-14 +> **Status:** M0 done, M1 in progress · **Last updated:** 2026-10-15 Hours are agent wall-clock hours for one agent; M0 is measured, the rest estimated. | Milestone | Goal | State | Hours | |---|---|---|---:| | M0 | Foundation: workspace, lints, quality gate, command registry, control channel, empty window | done 2026-10-14 (CI workflow written, not yet run: no remote) | ~2 (measured) | -| M1 | Editor and project: open folder, tree, tabs, editor, save, recovery, palette, settings, themes | in progress (M1.1 text, M1.2 VFS, M1.5 tree UI, M1.3 engine workspace) | ~60 | +| M1 | Editor and project: open folder, tree, tabs, editor, save, recovery, palette, settings, themes | in progress (M1.1 text, M1.2 VFS, M1.5 tree UI, M1.3 engine workspace, M1.4 desktop bridge) | ~60 | | M2 | Syntax and search: highlighting, structure, find in files, go to file/class/symbol | not started | ~50 | | M3 | LSP, terminal, CLI: completion, diagnostics, go to definition, hover, rename; terminal; `lutra` CLI and MCP — **MVP** | not started | ~80 | | M4 | Git: status, diff, commit, branches, log, blame, conflicts | not started | ~150 | @@ -31,6 +31,7 @@ By the estimates above the alpha gate needs M1–M4 plus cross-platform verifica | Date | Change | Summary | |---|---|---| +| 2026-10-15 | minor | M1.4 desktop bridge | | 2026-10-14 | minor | M1 in progress | | 2026-10-14 | minor | M0 done; hours per milestone | | 2026-10-13 | major | Initial milestones | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 66b5d42..4e9ea16 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Target-app parity -> **Status:** M1 in progress (text buffer, VFS, tree UI, engine workspace landed), no PHP feature ships · **Last updated:** 2026-10-14 · **Target:** PhpStorm 2026.x +> **Status:** M1 in progress (text buffer, VFS, engine workspace, project tree in the app), no PHP feature ships · **Last updated:** 2026-10-15 · **Target:** PhpStorm 2026.x ## How this is measured @@ -13,7 +13,7 @@ Hours are the estimated agent wall-clock hours for one agent to reach behaviour | Area | Weight | Score | Missing | Hours (one agent) | Evidence | |---|---:|---:|---|---:|---| | Editor core | 12 | 0% | everything user-visible: no editor in the UI yet; engine buffers, file commands and events exist | ~120 (est.) | `crates/text`: rope buffer, positions, edits (M1.1, unit tests + proptests). M1.3: engine buffers with versions and dirty state, `file.open`, `buffer.get`, `buffer.edit` (UTF-16 change sets, `stale_version`), `file.save`, `file.saveAll`, `buffer.close` with unsaved-changes guard, line ending and BOM kept on save, clean buffers reload on external change; 14 integration tests on temp dirs (`crates/engine/tests/workspace.rs`) | -| Project view, VFS | 6 | 0% | everything reachable in the app: the tree UI is not wired to the engine yet (M1.4) | ~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`) | +| 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, showing truncated listings | ~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`). 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 | 0% | everything | ~120 (est.) | — | | Search and replace | 6 | 0% | everything | ~80 (est.) | — | | Code completion | 10 | 0% | everything | ~250 (est.) | — | @@ -50,7 +50,7 @@ No PHP feature. The foundation, verified on Windows 11: ## What ships (M1, in progress) -Nothing user-visible yet, so every score stays 0%. +The project tree is the first user-visible feature (Project view 8%, estimated); every other score stays 0%. - M1.1 text buffer (`crates/text`): `Buffer` on a `ropey` rope with byte, char, UTF-16 and line counts; byte offset to line and column in UTF-16 code units or chars and back, all fallible (out of range, inside a character, inside a CRLF, inside a surrogate pair); atomic `Edit` batches in LSP `TextEdit[]` semantics that reject reversed, out-of-range and overlapping ranges; ` ` / ` @@ -61,6 +61,7 @@ Nothing user-visible yet, so every score stays 0%. | Date | Change | Summary | |---|---|---| +| 2026-10-15 | minor | Project view 0% → 8% (estimated): tree runs against the engine in the app (M1.4) | | 2026-10-14 | minor | Project view evidence: project tree UI (M1.5), score unchanged | | 2026-10-14 | minor | M1.3 engine workspace evidence (Editor core, Project view; scores unchanged) | | 2026-10-14 | minor | M1.1 text buffer evidence (Editor core, score unchanged) | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index afa1996..b422e7e 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,11 +1,12 @@ # UI parity checklist -> **Status:** main window layout and project tree against a mocked engine (M1.5) · **Last updated:** 2026-10-14 +> **Status:** main window layout and project tree against a mocked engine (M1.5) · **Last updated:** 2026-10-15 - [ ] Main window: tool window stripes, editor area, status bar, navigation bar - M1.5 (2026-10-14): left tool window with header, hide button, collapsed stripe with a show button, resizable by pointer and keyboard; editor area placeholder; status bar. Missing: stripes with several tool windows, bottom/right docking, navigation bar, layout persistence. Not checked in the running app yet (needs M1.4). - [ ] Project tool window (tree, scroll from source, file operations) - - M1.5 (2026-10-14): tree of the open folder with lazy `project.children` listings, folders and PHP files with Lucide icons, ignored/excluded entries dimmed, keyboard navigation (WAI-ARIA tree: arrows, Home/End, Enter), double-click opens, refresh on `TreeChanged`, listing errors shown in the tree, empty state with Open Folder…. Vitest only, against a mocked engine. Missing: scroll from source (Select Opened File), expand/collapse all, views list, sort options, speed search, file colours, file operations. Behaviour notes: `plan/phpstorm/02-project-view.md`. + - M1.5 (2026-10-14): tree of the open folder with lazy `project.children` listings, folders and PHP files with Lucide icons, ignored/excluded entries dimmed, keyboard navigation (WAI-ARIA tree: arrows, Home/End, Enter), double-click opens, refresh on `TreeChanged`, listing errors shown in the tree, empty state with Open Folder…. Vitest only, against a mocked engine. + - M1.4 (2026-10-15): runs against the real engine in the app: projects open from the folder picker or the command line, the tree updates live when files change on disk; checked with `ui.screenshot` on Windows 11. Missing: scroll from source (Select Opened File), expand/collapse all, views list, sort options, speed search, file colours, file operations. Behaviour notes: `plan/phpstorm/02-project-view.md`. - [ ] Editor tabs (pin, split, reorder, close others) - [ ] Command palette / search everywhere - [ ] Settings dialog with search @@ -22,5 +23,6 @@ | Date | Change | Summary | |---|---|---| +| 2026-10-15 | minor | Project tool window runs against the engine (M1.4) | | 2026-10-14 | minor | Notes on main window and project tool window (M1.5) | | 2026-10-13 | major | Baseline | diff --git a/ui/src/components/project/engineEvents.ts b/ui/src/components/project/engineEvents.ts index d16a84f..d803a20 100644 --- a/ui/src/components/project/engineEvents.ts +++ b/ui/src/components/project/engineEvents.ts @@ -1,32 +1,49 @@ /** - * Thin adapter between the project UI and the engine event stream. + * Thin adapter between the project UI and the engine. * - * The desktop bridge (M1.4) will add a typed `onEngineEvent(handler) => - * unsubscribe` to `ui/src/ipc.ts`, fed by the Tauri event `engine://event`. - * Until it lands, this module provides the same signature backed by a local - * dispatcher so the store and its tests can be written against it. Wiring the - * real stream is a one-line change: replace the local {@link onEngineEvent} - * with `export { onEngineEvent } from "../../ipc";`. + * Translates the engine's contract into the types the project store and tree + * use: engine events (`ui/src/ipc.ts` › `onEngineEvent`, tagged by `kind`) + * become {@link EngineEvent}s, and `project.children` results become + * {@link TreeListing}s through {@link toTreeEntries}. Keeping the + * translation here lets the store stay independent of the wire format. * - * The event and payload shapes below follow the planned engine `Event` enum - * (M1.3) and are the frontend's assumption until that lands. + * Subscriptions go through a local dispatcher: the first handler opens one + * subscription to the real event stream, the last one closes it. Tests feed + * the dispatcher with {@link emitEngineEvent} using engine payloads, so the + * translation is tested too. */ +import { onEngineEvent as onIpcEngineEvent, type EngineEventPayload } from "../../ipc"; -/** Kind of a project tree entry as reported by `project.children`. */ +/** Kind of a project tree entry. Engine kinds `file` and `other` are both leaves. */ export type TreeEntryKind = "dir" | "file"; -/** One entry of a directory listing, as returned by `project.children`. */ +/** Lutra's role for an entry: third-party `library` code or `excluded` from the project model. */ +export type EntryRole = "normal" | "library" | "excluded"; + +/** One entry of a directory listing. */ export interface TreeEntry { /** File or directory name, without any path. */ name: string; /** Project-relative path with `/` separators; the root is `""`. */ path: string; - /** Whether the entry is a directory or a file. */ + /** Whether the entry is a directory or a leaf. */ kind: TreeEntryKind; /** Matched by an ignore rule (`.gitignore`, `.ignore`, global excludes). */ ignored: boolean; - /** Excluded from the project model (for example `node_modules/`). */ + /** Lutra's role for the entry; `normal` when the engine did not send one. */ + role?: EntryRole; + /** Excluded from the project model (for example `node_modules/`); same as `role === "excluded"`. */ excluded?: boolean; + /** Neither a file nor a directory (a broken link, a socket). */ + special?: boolean; +} + +/** A translated `project.children` result. */ +export interface TreeListing { + /** The entries, in engine order. */ + entries: TreeEntry[]; + /** The directory had more entries than the engine lists. */ + truncated: boolean; } /** The project root, as carried by the `ProjectOpened` event. */ @@ -38,42 +55,134 @@ export interface ProjectRoot { } /** - * Engine events the project UI reacts to. The engine sends more kinds - * (buffer events); consumers ignore any `type` they do not handle. + * Engine events the project UI reacts to. Other engine events are not + * translated and never reach project handlers. */ export type EngineEvent = | { type: "ProjectOpened"; root: ProjectRoot } | { type: "ProjectClosed" } | { type: "TreeChanged"; dir: string }; -/** Callback receiving engine events. */ +/** Callback receiving project events. */ export type EngineEventHandler = (event: EngineEvent) => void; +/** + * Translates an engine event into a project event. + * + * @param payload - the engine event. + * @returns the project event, or null for kinds the project UI ignores. + */ +export function toProjectEvent(payload: EngineEventPayload): EngineEvent | null { + switch (payload.kind) { + case "projectOpened": + return { type: "ProjectOpened", root: { path: payload.root, name: payload.name } }; + case "projectClosed": + return { type: "ProjectClosed" }; + case "treeChanged": + return { type: "TreeChanged", dir: payload.dir }; + default: + return null; + } +} + +/** Reads a string field of an unknown object. */ +function stringField(value: Record, key: string): string | null { + const field = value[key]; + return typeof field === "string" ? field : null; +} + +/** + * Translates one engine entry. + * + * @param raw - an entry of the engine's `entries` array. + * @returns the tree entry, or null if the entry is malformed. + */ +function toTreeEntry(raw: unknown): TreeEntry | null { + if (typeof raw !== "object" || raw === null) { + return null; + } + const value = raw as Record; + const name = stringField(value, "name"); + const path = stringField(value, "path"); + const kind = stringField(value, "kind"); + if (name === null || path === null || kind === null) { + return null; + } + const roleField = stringField(value, "role"); + const role: EntryRole = roleField === "library" || roleField === "excluded" ? roleField : "normal"; + return { + name, + path, + kind: kind === "directory" ? "dir" : "file", + ignored: value.ignored === true, + role, + excluded: role === "excluded", + special: kind === "other", + }; +} + +/** + * Translates a `project.children` result + * (`{ dir, entries: [{ name, path, kind, ignored, role }], truncated }`). + * Malformed entries are skipped. + * + * @param value - the command result. + * @returns the listing, or null if the result has no `entries` array. + */ +export function toTreeEntries(value: unknown): TreeListing | null { + if (typeof value !== "object" || value === null) { + return null; + } + const result = value as Record; + if (!Array.isArray(result.entries)) { + return null; + } + const entries: TreeEntry[] = []; + for (const raw of result.entries as unknown[]) { + const entry = toTreeEntry(raw); + if (entry) { + entries.push(entry); + } + } + return { entries, truncated: result.truncated === true }; +} + /** Handlers subscribed through the local dispatcher. */ const handlers = new Set(); +/** Ends the subscription to the real event stream, null while closed. */ +let stopIpc: (() => void) | null = null; + /** - * Subscribes to engine events. + * Delivers an engine event to every project handler, translated. Used by + * the real event stream and by tests. + * + * @param payload - the engine event. + */ +export function emitEngineEvent(payload: EngineEventPayload): void { + const event = toProjectEvent(payload); + if (!event) { + return; + } + for (const handler of [...handlers]) { + handler(event); + } +} + +/** + * Subscribes to project events. * * @param handler - called for every event, in order of arrival. * @returns a function that removes the subscription. */ export function onEngineEvent(handler: EngineEventHandler): () => void { handlers.add(handler); + stopIpc ??= onIpcEngineEvent(emitEngineEvent); return () => { handlers.delete(handler); + if (handlers.size === 0) { + stopIpc?.(); + stopIpc = null; + } }; } - -/** - * Delivers an event to every subscriber of the local dispatcher. Used by - * tests and as the mock engine until the desktop bridge exists; removed when - * {@link onEngineEvent} is wired to `ui/src/ipc.ts`. - * - * @param event - the event to deliver. - */ -export function emitEngineEvent(event: EngineEvent): void { - for (const handler of [...handlers]) { - handler(event); - } -} diff --git a/ui/src/ipc.ts b/ui/src/ipc.ts index cefb2a9..3618431 100644 --- a/ui/src/ipc.ts +++ b/ui/src/ipc.ts @@ -3,9 +3,71 @@ * * Every user-visible action runs as an engine command through {@link run}. * Calls never reject: failures come back as `{ ok: false, error }` so that - * every caller has to handle them. + * every caller has to handle them. State changes arrive as engine events + * through {@link onEngineEvent}. */ import { invoke } from "@tauri-apps/api/core"; +import { listen, type UnlistenFn } from "@tauri-apps/api/event"; + +/** Name of the Tauri event that carries engine events. */ +export const ENGINE_EVENT = "engine://event"; + +/** + * An engine event as the desktop shell emits it: the engine's `Event`, + * tagged by `kind`. Paths are project-relative with `/`; the root is `""`. + */ +export type EngineEventPayload = + | { kind: "projectOpened"; root: string; name: string } + | { kind: "projectClosed" } + | { kind: "treeChanged"; dir: string } + | { kind: "bufferOpened"; id: number; path: string } + | { kind: "bufferChanged"; id: number; version: number } + | { kind: "dirtyChanged"; id: number; dirty: boolean } + | { kind: "bufferClosed"; id: number } + | { kind: "fileChangedOnDisk"; path: string; id: number; removed: boolean } + | { kind: "watchFailed"; message: string }; + +/** Callback receiving engine events. */ +export type EngineEventHandler = (event: EngineEventPayload) => void; + +/** Whether the shell was told that the frontend listens (`engine_ready`). */ +let announced = false; + +/** + * Subscribes to engine events. The first successful subscription tells the + * shell that the frontend listens, so it replays the current project state + * the page may have missed while loading. Outside the Tauri shell (tests, + * a plain browser) subscribing fails quietly and no events arrive. + * + * @param handler - called for every event, in order of arrival. + * @returns a function that ends the subscription. + */ +export function onEngineEvent(handler: EngineEventHandler): () => void { + let unlisten: UnlistenFn | null = null; + let cancelled = false; + listen(ENGINE_EVENT, (event) => { + handler(event.payload); + }) + .then((fn) => { + if (cancelled) { + fn(); + return; + } + unlisten = fn; + if (!announced) { + announced = true; + invoke("engine_ready").catch(() => { + announced = false; + }); + } + }) + .catch(() => undefined); + return () => { + cancelled = true; + unlisten?.(); + unlisten = null; + }; +} /** A JSON value as exchanged with the engine. */ export type JsonValue = diff --git a/ui/src/stores/project.ts b/ui/src/stores/project.ts index 5f4f1f7..83ad666 100644 --- a/ui/src/stores/project.ts +++ b/ui/src/stores/project.ts @@ -12,6 +12,7 @@ import { computed, ref } from "vue"; import { run, type EngineError } from "../ipc"; import { onEngineEvent, + toTreeEntries, type EngineEvent, type ProjectRoot, type TreeEntry, @@ -19,7 +20,7 @@ import { /** Engine command ids used by the project tool window. */ export const PROJECT_COMMANDS = { - /** Lists one directory: params `{ dir }`, result `TreeEntry[]`. */ + /** Lists one directory: params `{ dir }`, result `{ dir, entries, truncated }` (see `toTreeEntries`). */ children: "project.children", /** Shows the folder picker and opens the chosen folder. */ openDialog: "project.openDialog", @@ -35,6 +36,8 @@ export interface DirState { loading: boolean; /** Error of the last `project.children` call, null if it succeeded. */ error: EngineError | null; + /** The engine listed only part of the directory. */ + truncated: boolean; } /** A visible line of the flattened tree. */ @@ -136,17 +139,26 @@ export const useProjectStore = defineStore("project", () => { async function loadChildren(dir: string): Promise { const request = ++nextRequest; requests.set(dir, request); - dirs.value[dir] = { entries: cachedEntries(dir), loading: true, error: null }; - const result = await run(PROJECT_COMMANDS.children, { dir }); + const truncated = dirs.value[dir]?.truncated ?? false; + dirs.value[dir] = { entries: cachedEntries(dir), loading: true, error: null, truncated }; + const result = await run(PROJECT_COMMANDS.children, { dir }); if (requests.get(dir) !== request) { return; } - if (result.ok) { - const entries = result.value; - dirs.value[dir] = { entries, loading: false, error: null }; - prune(dir, entries); + const listing = result.ok ? toTreeEntries(result.value) : null; + if (listing) { + dirs.value[dir] = { + entries: listing.entries, + loading: false, + error: null, + truncated: listing.truncated, + }; + prune(dir, listing.entries); } else { - dirs.value[dir] = { entries: cachedEntries(dir), loading: false, error: result.error }; + const error = result.ok + ? { code: "ipc", message: `unexpected result of ${PROJECT_COMMANDS.children}` } + : result.error; + dirs.value[dir] = { entries: cachedEntries(dir), loading: false, error, truncated }; } } diff --git a/ui/tests/ipcEvents.test.ts b/ui/tests/ipcEvents.test.ts new file mode 100644 index 0000000..28f4a7c --- /dev/null +++ b/ui/tests/ipcEvents.test.ts @@ -0,0 +1,62 @@ +/** + * Tests for the engine event subscription in `ipc.ts`: payloads reach the + * handler, the shell is told once that the frontend listens, and a failed + * subscription never rejects. + */ +import { flushPromises } from "@vue/test-utils"; +import { 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 })); + +describe("onEngineEvent", () => { + beforeEach(() => { + vi.resetModules(); + invoke.mockReset(); + listen.mockReset(); + invoke.mockResolvedValue(null); + }); + + it("forwards payloads, announces readiness once and unlistens", async () => { + const unlisten = vi.fn(); + const callbacks: ((event: { payload: unknown }) => void)[] = []; + listen.mockImplementation((_name: string, callback: (event: { payload: unknown }) => void) => { + callbacks.push(callback); + return Promise.resolve(unlisten); + }); + const { onEngineEvent, ENGINE_EVENT } = await import("../src/ipc"); + const seen: unknown[] = []; + const stop = onEngineEvent((event) => seen.push(event)); + const stop2 = onEngineEvent(() => undefined); + await flushPromises(); + expect(listen).toHaveBeenCalledWith(ENGINE_EVENT, expect.any(Function)); + expect(invoke).toHaveBeenCalledTimes(1); + expect(invoke).toHaveBeenCalledWith("engine_ready"); + callbacks[0]?.({ payload: { kind: "treeChanged", dir: "src" } }); + expect(seen).toEqual([{ kind: "treeChanged", dir: "src" }]); + stop(); + stop2(); + expect(unlisten).toHaveBeenCalledTimes(2); + }); + + it("unlistens a subscription that was cancelled before it started", async () => { + const unlisten = vi.fn(); + listen.mockResolvedValue(unlisten); + const { onEngineEvent } = await import("../src/ipc"); + const stop = onEngineEvent(() => undefined); + stop(); + await flushPromises(); + expect(unlisten).toHaveBeenCalledTimes(1); + }); + + it("swallows a failing subscription outside the shell", async () => { + listen.mockRejectedValue(new Error("no Tauri")); + const { onEngineEvent } = await import("../src/ipc"); + const stop = onEngineEvent(() => undefined); + await flushPromises(); + stop(); + expect(invoke).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/tests/project/ProjectTree.test.ts b/ui/tests/project/ProjectTree.test.ts index 16468ce..e2acbb6 100644 --- a/ui/tests/project/ProjectTree.test.ts +++ b/ui/tests/project/ProjectTree.test.ts @@ -11,12 +11,26 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; const invoke = vi.hoisted(() => vi.fn()); vi.mock("@tauri-apps/api/core", () => ({ invoke })); -import { emitEngineEvent, type TreeEntry } from "../../src/components/project/engineEvents"; +import { emitEngineEvent } from "../../src/components/project/engineEvents"; import ProjectToolWindow from "../../src/components/project/ProjectToolWindow.vue"; import { useProjectStore } from "../../src/stores/project"; +/** An entry as the engine's `project.children` returns it. */ +interface EngineEntry { + /** Display name. */ + name: string; + /** Project-relative path. */ + path: string; + /** Engine kind. */ + kind: "directory" | "file" | "other"; + /** Matched by an ignore rule. */ + ignored: boolean; + /** Lutra's role for the entry. */ + role: "normal" | "library" | "excluded"; +} + /** In-memory folder listings by directory, as `project.children` returns them. */ -let folder: Record; +let folder: Record; /** * Builds an entry. @@ -25,8 +39,10 @@ let folder: Record; * @param kind - entry kind. * @param ignored - ignore flag. */ -function entry(path: string, kind: "dir" | "file", ignored = false): TreeEntry { - return { name: path.split("/").pop() ?? path, path, kind, ignored }; +function entry(path: string, kind: "dir" | "file", ignored = false): EngineEntry { + const engineKind = kind === "dir" ? "directory" : "file"; + const role = path === "node_modules" ? "excluded" : path === "vendor" ? "library" : "normal"; + return { name: path.split("/").pop() ?? path, path, kind: engineKind, ignored, role }; } /** Mock engine: answers `project.children`, accepts other commands. */ @@ -38,7 +54,7 @@ function engine(command: string, args: { command: string; params: { dir?: string const dir = args.params.dir ?? ""; const entries = folder[dir]; return entries - ? Promise.resolve(entries) + ? Promise.resolve({ dir, entries, truncated: false }) : Promise.reject(Object.assign(new Error(`cannot list ${dir}`), { code: "not_found" })); } return Promise.resolve(null); @@ -47,7 +63,7 @@ function engine(command: string, args: { command: string; params: { dir?: string /** Mounts the tool window and opens the mock project through an event. */ async function mountOpen(): Promise { const wrapper = mount(ProjectToolWindow, { attachTo: document.body }); - emitEngineEvent({ type: "ProjectOpened", root: { path: "/tmp/demo", name: "demo" } }); + emitEngineEvent({ kind: "projectOpened", root: "/tmp/demo", name: "demo" }); await flushPromises(); return wrapper; } @@ -183,7 +199,7 @@ describe("ProjectToolWindow", () => { await press(wrapper, "ArrowRight"); expect(selectedPath(wrapper)).toBe("src/Controller"); folder.src = [entry("src/App.php", "file"), entry("src/Kernel.php", "file")]; - emitEngineEvent({ type: "TreeChanged", dir: "src" }); + emitEngineEvent({ kind: "treeChanged", dir: "src" }); await flushPromises(); expect(paths(wrapper)).toEqual(["src", "src/App.php", "src/Kernel.php", "vendor", "node_modules", "index.php"]); expect(selectedPath(wrapper)).toBeNull(); @@ -194,7 +210,7 @@ describe("ProjectToolWindow", () => { it("ignores TreeChanged for directories never loaded", async () => { wrapper = await mountOpen(); - emitEngineEvent({ type: "TreeChanged", dir: "vendor" }); + emitEngineEvent({ kind: "treeChanged", dir: "vendor" }); await flushPromises(); expect(childrenCalls()).toEqual([""]); }); @@ -211,7 +227,7 @@ describe("ProjectToolWindow", () => { it("keeps old entries when a refresh fails", async () => { wrapper = await mountOpen(); Reflect.deleteProperty(folder, ""); - emitEngineEvent({ type: "TreeChanged", dir: "" }); + emitEngineEvent({ kind: "treeChanged", dir: "" }); await flushPromises(); expect(wrapper.get("[data-test=tree-error]").text()).toBe("cannot list"); expect(paths(wrapper)).toEqual(["src", "vendor", "node_modules", "index.php"]); @@ -219,12 +235,12 @@ describe("ProjectToolWindow", () => { it("returns to the empty state on ProjectClosed and unsubscribes on unmount", async () => { wrapper = await mountOpen(); - emitEngineEvent({ type: "ProjectClosed" }); + emitEngineEvent({ kind: "projectClosed" }); await flushPromises(); expect(wrapper.find("[data-test=project-empty]").exists()).toBe(true); wrapper.unmount(); wrapper = null; - emitEngineEvent({ type: "ProjectOpened", root: { path: "/tmp/other", name: "other" } }); + emitEngineEvent({ kind: "projectOpened", root: "/tmp/other", name: "other" }); expect(useProjectStore().root).toBeNull(); }); }); diff --git a/ui/tests/project/engineEvents.test.ts b/ui/tests/project/engineEvents.test.ts new file mode 100644 index 0000000..0433ffd --- /dev/null +++ b/ui/tests/project/engineEvents.test.ts @@ -0,0 +1,105 @@ +/** + * Tests for the adapter between the engine contract and the project UI: + * `project.children` results and engine events are translated without + * losing kind, ignore flag, role or truncation. + */ +import { createPinia, setActivePinia } from "pinia"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const invoke = vi.hoisted(() => vi.fn()); +vi.mock("@tauri-apps/api/core", () => ({ invoke })); + +import { + emitEngineEvent, + onEngineEvent, + toProjectEvent, + toTreeEntries, + type EngineEvent, +} from "../../src/components/project/engineEvents"; +import { useProjectStore } from "../../src/stores/project"; + +describe("toTreeEntries", () => { + it("maps kinds, ignore flags and roles", () => { + const listing = toTreeEntries({ + dir: "", + entries: [ + { name: "src", path: "src", kind: "directory", ignored: false, role: "normal" }, + { name: "vendor", path: "vendor", kind: "directory", ignored: false, role: "library" }, + { name: "node_modules", path: "node_modules", kind: "directory", ignored: false, role: "excluded" }, + { name: "a.log", path: "a.log", kind: "file", ignored: true, role: "normal" }, + { name: "dangling", path: "dangling", kind: "other", ignored: false, role: "normal" }, + ], + truncated: true, + }); + expect(listing).toEqual({ + truncated: true, + entries: [ + { name: "src", path: "src", kind: "dir", ignored: false, role: "normal", excluded: false, special: false }, + { name: "vendor", path: "vendor", kind: "dir", ignored: false, role: "library", excluded: false, special: false }, + { name: "node_modules", path: "node_modules", kind: "dir", ignored: false, role: "excluded", excluded: true, special: false }, + { name: "a.log", path: "a.log", kind: "file", ignored: true, role: "normal", excluded: false, special: false }, + { name: "dangling", path: "dangling", kind: "file", ignored: false, role: "normal", excluded: false, special: true }, + ], + }); + }); + + it("skips malformed entries and rejects results without entries", () => { + expect(toTreeEntries({ entries: [{ name: "x" }, 3, null, { name: "a", path: "a", kind: "file" }] })).toEqual({ + truncated: false, + entries: [{ name: "a", path: "a", kind: "file", ignored: false, role: "normal", excluded: false, special: false }], + }); + expect(toTreeEntries([])).toBeNull(); + expect(toTreeEntries(null)).toBeNull(); + expect(toTreeEntries({ entries: "no" })).toBeNull(); + }); +}); + +describe("toProjectEvent", () => { + it("translates project events and ignores the rest", () => { + expect(toProjectEvent({ kind: "projectOpened", root: "/p/demo", name: "demo" })).toEqual({ + type: "ProjectOpened", + root: { path: "/p/demo", name: "demo" }, + }); + expect(toProjectEvent({ kind: "projectClosed" })).toEqual({ type: "ProjectClosed" }); + expect(toProjectEvent({ kind: "treeChanged", dir: "src" })).toEqual({ type: "TreeChanged", dir: "src" }); + expect(toProjectEvent({ kind: "bufferOpened", id: 1, path: "a.php" })).toBeNull(); + }); + + it("delivers only translated events to project handlers", () => { + const seen: EngineEvent[] = []; + const stop = onEngineEvent((event) => seen.push(event)); + emitEngineEvent({ kind: "dirtyChanged", id: 1, dirty: true }); + emitEngineEvent({ kind: "treeChanged", dir: "" }); + stop(); + emitEngineEvent({ kind: "treeChanged", dir: "late" }); + expect(seen).toEqual([{ type: "TreeChanged", dir: "" }]); + }); +}); + +describe("project store with the engine result", () => { + beforeEach(() => { + setActivePinia(createPinia()); + invoke.mockReset(); + }); + + it("keeps truncation and role from project.children", async () => { + invoke.mockResolvedValue({ + dir: "", + entries: [{ name: "vendor", path: "vendor", kind: "directory", ignored: false, role: "library" }], + truncated: true, + }); + const store = useProjectStore(); + store.handleEvent({ type: "ProjectOpened", root: { path: "/p", name: "p" } }); + await store.loadChildren(""); + expect(store.dirs[""]?.truncated).toBe(true); + expect(store.dirs[""]?.entries?.[0]?.role).toBe("library"); + }); + + it("reports an unexpected result as an error instead of throwing", async () => { + invoke.mockResolvedValue(["old", "shape"]); + const store = useProjectStore(); + store.handleEvent({ type: "ProjectOpened", root: { path: "/p", name: "p" } }); + await store.loadChildren(""); + expect(store.dirs[""]?.error?.code).toBe("ipc"); + }); +}); diff --git a/ui/tests/project/store.test.ts b/ui/tests/project/store.test.ts index 01ce404..4d82364 100644 --- a/ui/tests/project/store.test.ts +++ b/ui/tests/project/store.test.ts @@ -23,9 +23,9 @@ describe("project store", () => { const store = useProjectStore(); store.handleEvent({ type: "ProjectOpened", root: { path: "/p", name: "p" } }); const second = store.loadChildren(""); - resolvers[1]?.([{ name: "new.php", path: "new.php", kind: "file", ignored: false }]); + resolvers[1]?.({ dir: "", entries: [{ name: "new.php", path: "new.php", kind: "file", ignored: false, role: "normal" }], truncated: false }); await second; - resolvers[0]?.([{ name: "old.php", path: "old.php", kind: "file", ignored: false }]); + resolvers[0]?.({ dir: "", entries: [{ name: "old.php", path: "old.php", kind: "file", ignored: false, role: "normal" }], truncated: false }); await Promise.resolve(); expect(store.rows.map((row) => (row.kind === "entry" ? row.entry.path : row.kind))).toEqual(["new.php"]); });