M1.4: desktop bridge: engine events to the window, folder picker, live project tree

The desktop host publishes every engine event, from commands and from a
pump thread that calls Engine::pump_vfs every 100 ms, to control channel
subscribers and to the window as the Tauri event engine://event, in engine
order. ui/src/ipc.ts gets a typed onEngineEvent; its first subscription
calls engine_ready, and the host replays the current project and buffers,
so a project opened from the command line (lutra-desktop --control PORT
PATH) reaches the UI. project.openDialog returns Effect::PickFolder; the
host shows the native folder picker (tauri-plugin-dialog, licence checked)
and opens the choice, one picker at a time, cancel is not an error.
Capabilities shrink to event listen/unlisten.

Contract fix: the M1.5 project UI assumed shapes the engine does not use.
engineEvents.ts now translates engine events ({kind: projectOpened, ...})
and project.children results ({dir, entries, truncated}) into the UI types,
keeping role and truncated; the store maps listings through
toTreeEntries() and the project tests use the real engine shapes.

Verified in the running app on Windows 11: tree of a project given on the
command line, expanding src, a file created on disk appearing live, the
folder picker opening one dialog and opening the chosen folder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-15 06:41:49 +02:00
parent 69130d1efb
commit dd98636de4
23 changed files with 751 additions and 99 deletions

View file

@ -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]

View file

@ -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"]
}

View file

@ -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<Engine>,
/// The Tauri app, set once the app is set up.
app: OnceLock<AppHandle>,
/// 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<Host>,
/// 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<Self, EngineError> {
Ok(Self {
engine: Mutex::new(Engine::new()?),
pub fn new() -> Result<Arc<Self>, 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<Value, EngineError> {
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<Value, EngineError> {
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 {

View file

@ -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<Host>>) -> Vec<CommandInfo> {
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>>) {
host.replay_to_window();
}
#[cfg(test)]
mod tests {
use super::*;