M1.12: notifications as toasts

The host publishes picker, command-line and pump errors as notification
events (Engine::notify, same id sequence) instead of stderr, keeps
notifications and watchFailed published before engine_ready and replays
them after the state replay, so startup warnings (corrupt settings,
journal entries) reach the UI. ipc.ts announces engine_ready once all
subscriptions started together are registered.

Frontend: notifications store and NotificationStack (bottom right, info
auto-dismissed after 5 s, warnings/errors stay, close button and Escape,
at most 5 visible with "+n more", role status/alert); watchFailed maps to
a warning toast; failed commands without their own UI raise an error
toast. Catalog keys notification.settings.*, project.*, vfs.*, watch.*,
command.* plus the runtime allow-list. Docs updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-16 16:20:45 +02:00
parent 7b7273a947
commit f41df518b5
21 changed files with 1178 additions and 94 deletions

View file

@ -6,6 +6,12 @@
//! 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.
//!
//! Errors that have no caller to return to (the folder picker, the pump, the
//! project given on the command line) are published as `notification`
//! events. Notifications and `watchFailed` events published before the
//! frontend called `engine_ready`, such as the warning about a corrupt
//! settings file found at startup, are kept and replayed to the window then.
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
@ -14,8 +20,8 @@ use std::thread;
use std::time::Duration;
use lutra_control::{Backend, EventSink, Subscribers};
use lutra_engine::{CommandInfo, Effect, Engine, EngineError, Event};
use serde_json::{Value, json};
use lutra_engine::{CommandInfo, Effect, Engine, EngineError, Event, NotificationLevel};
use serde_json::{Map, Value, json};
use tauri::{AppHandle, Emitter};
use tauri_plugin_dialog::DialogExt;
@ -33,6 +39,24 @@ pub const ENGINE_EVENT: &str = "engine://event";
/// Time between two pumps of changes on disk.
const PUMP_INTERVAL: Duration = Duration::from_millis(100);
/// Most events kept for the window before it is ready; later ones are not
/// replayed (they still reach control channel subscribers).
const EARLY_LIMIT: usize = 50;
/// Catalog key: a folder could not be opened because buffers have unsaved
/// changes. Params: `path`, `what`.
pub const KEY_UNSAVED_CHANGES: &str = "notification.project.unsavedChanges";
/// Catalog key: a folder could not be opened. Params: `path`, `reason`.
pub const KEY_OPEN_FAILED: &str = "notification.project.openFailed";
/// Catalog key: the folder picker returned something that is not a local
/// path. Params: `reason`.
pub const KEY_NOT_LOCAL: &str = "notification.project.notLocal";
/// Catalog key: applying changes on disk failed. Params: `reason`.
pub const KEY_PUMP_FAILED: &str = "notification.vfs.pumpFailed";
/// 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
@ -46,6 +70,12 @@ pub struct Host {
me: Weak<Host>,
/// A folder picker is open; another request is ignored until it closes.
picking: AtomicBool,
/// The frontend called `engine_ready`. Changed and read with the engine
/// lock held, so it is ordered with [`Host::publish`].
window_ready: AtomicBool,
/// Notifications and `watchFailed` events published before the window
/// was ready, oldest first, at most [`EARLY_LIMIT`].
early: Mutex<Vec<Event>>,
}
impl Host {
@ -57,6 +87,8 @@ impl Host {
subscribers: Subscribers::default(),
me: me.clone(),
picking: AtomicBool::new(false),
window_ready: AtomicBool::new(false),
early: Mutex::new(Vec::new()),
})
}
@ -71,11 +103,26 @@ impl Host {
self.engine.lock().unwrap_or_else(PoisonError::into_inner)
}
/// 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.
/// Locks the events kept for the window, recovering a poisoned lock.
fn early(&self) -> MutexGuard<'_, Vec<Event>> {
self.early.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Sends events to the control channel subscribers and the window, and
/// keeps the ones the window must not miss until it is ready. Callers
/// hold the engine lock. 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 !self.window_ready.load(Ordering::Acquire) {
let mut early = self.early();
for event in events.iter().filter(|e| kept_for_window(e)) {
if early.len() < EARLY_LIMIT {
early.push(event.clone());
}
}
}
if let Some(app) = self.app.get() {
for event in events {
let _ = app.emit(ENGINE_EVENT, event);
@ -100,6 +147,43 @@ impl Host {
Ok(outcome.value)
}
/// Publishes the events the engine queued while starting, such as the
/// warning about a corrupt settings file. The window receives the
/// notifications among them when it calls `engine_ready`.
pub fn publish_startup(&self, events: &[Event]) {
let _engine = self.engine();
self.publish(events);
}
/// Publishes a notification for an error that has no caller to return
/// to.
///
/// # Parameters
/// - `level`: severity.
/// - `key`: message-catalog key of the text.
/// - `message`: the English text, shown without a catalog entry.
/// - `params`: interpolation params for the catalog text.
pub fn notify(
&self,
level: NotificationLevel,
key: &str,
message: String,
params: Map<String, Value>,
) {
let mut engine = self.engine();
let events = engine.notify(level, Some(key), Some(message), Some(params));
self.publish(&events);
}
/// Reports that the folder at `path` could not be opened as the
/// project: a warning when buffers have unsaved changes (the user saves
/// or closes them and tries again), an error otherwise.
pub fn report_open_failure(&self, path: &Path, error: &EngineError) {
let shown = path.display().to_string();
let (level, key, params) = open_failure(&shown, error);
self.notify(level, key, format!("Cannot open {shown}: {error}"), params);
}
/// Lists every command with its current enabled state.
pub fn commands(&self) -> Vec<CommandInfo> {
self.engine().list_commands()
@ -122,38 +206,27 @@ impl Host {
}
/// 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.
/// project and its buffers), then the notifications and `watchFailed`
/// events published before it was ready, for a frontend that just
/// started listening and missed them. From then on nothing is kept for
/// the window. 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);
}
self.window_ready.store(true, Ordering::Release);
for event in state_events(&engine) {
let _ = app.emit(ENGINE_EVENT, &event);
}
let early = std::mem::take(&mut *self.early());
for event in &early {
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
/// with the host. A pump that panicked or failed is reported as one
/// warning notification until a pump succeeds again, and retried on the
/// next tick.
///
/// # Errors
@ -163,13 +236,29 @@ impl Host {
thread::Builder::new()
.name("lutra-vfs-pump".into())
.spawn(move || {
let mut failing = false;
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}"),
Ok(events) => {
failing = false;
host.publish(&events);
}
Err(e) if !failing => {
failing = true;
let mut params = Map::new();
params.insert("reason".into(), Value::String(e.to_string()));
let events = engine.notify(
NotificationLevel::Warning,
Some(KEY_PUMP_FAILED),
Some(format!("Applying changes on disk failed: {e}")),
Some(params),
);
host.publish(&events);
}
Err(_) => {}
}
}
})
@ -189,8 +278,8 @@ impl Host {
/// 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.
/// opened, for example because buffers have unsaved changes, is
/// reported as a notification.
fn pick_folder(&self, app: &AppHandle) {
if self.picking.swap(true, Ordering::AcqRel) {
return;
@ -206,17 +295,80 @@ impl Host {
let path: PathBuf = match folder.into_path() {
Ok(path) => path,
Err(e) => {
eprintln!("lutra: the picked folder is not a local path: {e}");
let mut params = Map::new();
params.insert("reason".into(), Value::String(e.to_string()));
host.notify(
NotificationLevel::Error,
KEY_NOT_LOCAL,
format!("The picked folder is not a local path: {e}"),
params,
);
return;
}
};
if let Err(e) = host.open_project(&path) {
eprintln!("lutra: cannot open {}: {e}", path.display());
host.report_open_failure(&path, &e);
}
});
}
}
/// Whether the window must see `event` even if it was published before the
/// frontend listened: notifications and `watchFailed`. The project and its
/// buffers are replayed from the engine state instead.
fn kept_for_window(event: &Event) -> bool {
matches!(
event,
Event::Notification { .. } | Event::WatchFailed { .. }
)
}
/// The events that describe the engine's current state: the open project
/// and its buffers; none without a project.
fn state_events(engine: &Engine) -> Vec<Event> {
let state = engine.state();
let Some(workspace) = &state.project else {
return Vec::new();
};
let root = workspace.project.root();
let mut events = vec![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()),
}];
for id in state.buffers.ids() {
if let Some(open) = state.buffers.get(id) {
events.push(Event::BufferOpened {
id,
path: lutra_engine::workspace::path_string(&open.path),
});
}
}
events
}
/// Level, catalog key and params of the notification for a folder at
/// `path` that could not be opened with `error`.
fn open_failure(
path: &str,
error: &EngineError,
) -> (NotificationLevel, &'static str, Map<String, Value>) {
let mut params = Map::new();
params.insert("path".into(), Value::String(path.to_string()));
match error {
EngineError::UnsavedChanges(what) => {
params.insert("what".into(), Value::String(what.clone()));
(NotificationLevel::Warning, KEY_UNSAVED_CHANGES, params)
}
_ => {
params.insert("reason".into(), Value::String(error.to_string()));
(NotificationLevel::Error, KEY_OPEN_FAILED, params)
}
}
}
impl Backend for Host {
fn execute(&self, command: &str, params: Value) -> Result<Value, EngineError> {
self.run(command, params)
@ -235,3 +387,50 @@ impl Backend for Host {
self.subscribers.add(sink);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unsaved_changes_are_a_warning() {
let (level, key, params) = open_failure("/p", &EngineError::UnsavedChanges("a.php".into()));
assert_eq!(level, NotificationLevel::Warning);
assert_eq!(key, KEY_UNSAVED_CHANGES);
assert_eq!(params["path"], "/p");
assert_eq!(params["what"], "a.php");
}
#[test]
fn other_open_failures_are_errors() {
let (level, key, params) = open_failure("/p", &EngineError::Failed("gone".into()));
assert_eq!(level, NotificationLevel::Error);
assert_eq!(key, KEY_OPEN_FAILED);
assert_eq!(params["reason"], "gone");
}
#[test]
fn notifications_wait_for_the_window() {
let host = Host::new(Engine::new().unwrap());
host.notify(NotificationLevel::Info, "k", "m".into(), Map::new());
host.publish_startup(&[
Event::WatchFailed {
message: "x".into(),
},
Event::ProjectClosed,
]);
let early = host.early();
assert_eq!(early.len(), 2);
assert!(matches!(early[0], Event::Notification { .. }));
assert!(matches!(early[1], Event::WatchFailed { .. }));
}
#[test]
fn early_events_are_capped() {
let host = Host::new(Engine::new().unwrap());
for _ in 0..EARLY_LIMIT + 5 {
host.notify(NotificationLevel::Info, "k", "m".into(), Map::new());
}
assert_eq!(host.early().len(), EARLY_LIMIT);
}
}

View file

@ -15,7 +15,7 @@ mod screenshot;
use std::process::ExitCode;
use std::sync::{Arc, OnceLock};
use lutra_engine::{CommandInfo, Engine, EngineConfig, ErrorPayload, Event, theme};
use lutra_engine::{CommandInfo, Engine, EngineConfig, ErrorPayload, theme};
use serde_json::Value;
use tauri::window::Color;
use tauri::{Manager, WebviewUrl, WebviewWindowBuilder};
@ -87,15 +87,16 @@ fn run(args: &args::Args) -> Result<(), String> {
if let Some(path) = &initial_path
&& let Err(e) = setup_host.open_project(path)
{
eprintln!("lutra: cannot open {}: {e}", path.display());
setup_host.report_open_failure(path, &e);
}
Ok(())
})
.build(tauri::generate_context!())
.map_err(|e| e.to_string())?;
let mut engine = Engine::with_config(engine_config(&app)?).map_err(|e| e.to_string())?;
log_startup_events(&engine.take_events());
let startup = engine.take_events();
let host = Host::new(engine);
host.publish_startup(&startup);
app.manage(host.clone());
if slot.set(host.clone()).is_err() {
return Err("the host was set twice".into());
@ -128,21 +129,6 @@ fn engine_config(app: &tauri::App) -> Result<EngineConfig, String> {
})
}
/// Logs the notifications the engine queued while starting, such as the
/// fallback to default settings, to stderr.
fn log_startup_events(events: &[Event]) {
for event in events {
if let Event::Notification {
level,
message: Some(message),
..
} = event
{
eprintln!("lutra: {level:?}: {message}");
}
}
}
/// The stored `appearance.theme` value, `system` if it cannot be read.
fn stored_theme(host: &Host) -> String {
host.run(
@ -199,7 +185,7 @@ fn engine_list_commands(host: tauri::State<'_, Arc<Host>>) -> Vec<CommandInfo> {
}
/// IPC: the frontend listens for engine events now; replays the current
/// project state it may have missed while loading.
/// project state and the notifications it may have missed while loading.
#[tauri::command]
fn engine_ready(host: tauri::State<'_, Arc<Host>>) {
host.replay_to_window();