PM: merge M1.12 notifications
Some checks are pending
ci / ci (macos-15) (push) Waiting to run
ci / ci (ubuntu-24.04) (push) Waiting to run
ci / ci (windows-2025) (push) Waiting to run

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	docs/architecture.md
#	docs/gaps.md
#	docs/roadmap.md
#	docs/target-app-parity.md
#	docs/ui-parity.md
This commit is contained in:
danny 2026-10-16 16:22:14 +02:00
commit 2f8fef876b
21 changed files with 1178 additions and 94 deletions

View file

@ -2,7 +2,7 @@
**Stage: pre-alpha (M1 in progress)** · next: the rest of M1 (palette, settings, themes), then M2 syntax and search; 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-15 · **Last updated:** 2026-10-16 · **Change:** minor (M1.7: crash-recovery journal) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only
> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-16 · **Change:** minor (M1.12: notifications) · **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).
@ -77,6 +77,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a
| Date | What landed |
|---|---|
| 2026-10-16 | M1.12: errors and notices reach the user as toasts instead of stderr: a corrupt settings file or recovery entry, a folder that cannot be opened (also with unsaved changes when switching projects), stopped file watching and failed commands without their own UI. Info toasts go away after 5 s, warnings and errors stay. |
| 2026-10-16 | M1.7: unsaved text survives a crash. Dirty buffers are journaled about a second after the last edit; the next open offers them in a restore dialog (restore all, selected, or discard), with line endings and BOM kept. |
| 2026-10-16 | M1.10: Lutra Light next to Lutra Dark, switched live through the `appearance.theme` setting or following the OS (`system`); the window starts in the stored theme; the editor, tabs and notices get their own tokens; both themes pass a WCAG AA contrast test. |
| 2026-10-15 | M1.11: every interface string comes from an English message catalog (`ui/src/i18n/en.json`), enforced by a lint rule and a catalog test; the groundwork for German. |
@ -89,6 +90,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a
| Date | Change | Summary |
|---|---|---|
| 2026-10-16 | minor | M1.12: progress log (headline unchanged) |
| 2026-10-16 | minor | M1.7: Stability 8%, Editor core 9%, feature depth ~1.6% (with Settings 4% from M1.10) |
| 2026-10-16 | minor | M1.10: UI/UX fidelity 1%, Settings row 4% (estimates), progress log |
| 2026-10-15 | minor | M1.11: localization 5% (English UI catalog), progress log |

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();

View file

@ -156,6 +156,30 @@ impl Engine {
self.state.take_events()
}
/// Queues an [`crate::Event::Notification`] from the host, such as an
/// error after the folder picker closed, with a fresh id from the same
/// sequence as the engine's own notifications, and takes the queued
/// events.
///
/// # Parameters
/// - `level`: severity.
/// - `message_key`: message-catalog key of the text.
/// - `message`: English text, the fallback without a catalog entry.
/// - `params`: interpolation params for the catalog text.
///
/// # Returns
/// The queued events, oldest first, ending with the notification.
pub fn notify(
&mut self,
level: NotificationLevel,
message_key: Option<&str>,
message: Option<String>,
params: Option<serde_json::Map<String, Value>>,
) -> Vec<crate::Event> {
self.state.notify(level, message_key, message, params);
self.state.take_events()
}
/// Describes every command with its current enabled state. A command whose
/// `enabled` check panics is listed as disabled.
pub fn list_commands(&self) -> Vec<CommandInfo> {
@ -222,6 +246,26 @@ mod tests {
}
}
#[test]
fn host_notifications_get_fresh_ids() {
let mut engine = Engine::new().unwrap();
let first = engine.notify(
NotificationLevel::Error,
Some("notification.project.openFailed"),
Some("cannot open".into()),
None,
);
let second = engine.notify(NotificationLevel::Info, None, Some("hi".into()), None);
let id = |events: &[crate::Event]| match events.last() {
Some(crate::Event::Notification { id, .. }) => id.clone(),
other => panic!("not a notification: {other:?}"),
};
assert_eq!(first.len(), 1);
assert_eq!(id(&first), "n1");
assert_eq!(id(&second), "n2");
assert!(engine.take_events().is_empty());
}
#[test]
fn about_reports_product_information() {
let mut engine = Engine::new().unwrap();

View file

@ -1,6 +1,6 @@
# Architecture
> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes and the recovery journal documented · **Last updated:** 2026-10-16
> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal and notifications documented · **Last updated:** 2026-10-16
## Overview
@ -87,8 +87,8 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
### 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.
- `ui/src/ipc.ts` exposes `onEngineEvent(handler) => unsubscribe` with the typed union `EngineEventPayload`. Once the subscriptions started together (all of them while the page mounts) are registered, `ipc.ts` calls the IPC command `engine_ready` once; the host then replays `projectOpened` and `bufferOpened` for the current state, followed by the notifications and `watchFailed` events published before (M1.12), 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 becomes a `notification` (M1.12): `unsaved_changes` a warning, anything else an error.
- 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.
@ -111,7 +111,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
### Engine construction (M1.9a)
- `EngineConfig { config_dir, data_dir }` and `Engine::with_config(config) -> Result<Engine, EngineError>`. The desktop builds the Tauri app first, takes `app_config_dir()` and `app_data_dir()` from its path resolver, creates the engine, the host and the control channel, and creates the window in the setup hook. `Engine::new()` has no persistence (settings in memory only) and serves tests and the control test backend; `lutra_testkit::engine_config(root)` gives temp dirs for tests.
- Construction never fails because of the settings file. Problems are queued as a warning `notification` event; the desktop takes the startup events and logs them to stderr (the UI does not see startup notifications yet, M1.12).
- Construction never fails because of the settings file. Problems are queued as a warning `notification` event; the desktop takes the startup events and publishes them, and the window receives them on `engine_ready` (M1.12).
### Settings (M1.9a)
@ -121,6 +121,15 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
- Commands: `settings.list` → `[{key, type: enum|int, default, enumValues?, min?, max?, labelKey, descriptionKey, section}]` (catalog keys `settings.<key>.label` / `.description`; `section` is an id shown with `settings.section.<id>`), `settings.get {keys?}` → `{values}`, `settings.set {key, value}` → `{value}`, `settings.reset {key}` → `{value}`. Unknown keys and bad values fail with `invalid_params`; a write failure fails with `failed` and changes nothing.
- Events: `settingsChanged {keys}` when an effective value changes; `notification {id, level: info|warning|error, messageKey?, message?, params?}` (ids `n1`, `n2`…).
### Notifications (M1.12)
- **Event:** `notification {id, level: info|warning|error, messageKey?, message?, params?}`; ids `n1`, `n2`… from one sequence per engine. `messageKey` is a catalog key, `message` the English fallback. The engine emits them for settings (M1.9a) and journal (M1.7) problems; the host asks the engine for one with `Engine::notify` (same id sequence) for errors that have no caller to return to:
- folder picker and command-line path: `notification.project.unsavedChanges {path, what}` (warning) for `unsaved_changes`, `notification.project.openFailed {path, reason}` (error) otherwise, `notification.project.notLocal {reason}` (error) for a picked folder that is not a local path;
- pump: `notification.vfs.pumpFailed {reason}` (warning), once until a pump succeeds again.
- **Replay:** the host keeps notifications and `watchFailed` published before the window called `engine_ready` (at most 50) and sends them after the state replay; afterwards nothing is kept. The store ignores an id it already shows, so a second replay does not duplicate.
- **`watchFailed`** stays an engine event (control channel clients use it); the frontend maps it to a warning toast `notification.watch.failed {reason}`. `workspace.rs` is unchanged.
- **UI:** `ui/src/stores/notifications.ts` (Pinia) turns events into toasts (catalog text with params if the key exists, else `message`, else the key; untrusted fields checked, unknown levels count as errors) and offers `notify` / `notifyError(command, error)` to frontend code. Failed commands that have no UI of their own raise an error toast `notification.command.failed {command, message}` (today `theme.systemPreference` and loading the editor keymap); errors shown in place (tree listings, editor and project errors, the restore dialog) stay in place. `ui/src/components/notifications/NotificationStack.vue`, mounted in `App.vue`, stacks the toasts at the bottom right, newest at the bottom: info as `role="status"`, dismissed after 5 s; warnings and errors as `role="alert"`, until closed. Each toast has a close button and closes with Escape while focused; at most 5 show, older ones collapse into a "+n more" button that expands the stack; at most 100 are kept. Colours are the editor notices' (`--lt-notice-bg`, error tint), with a level stripe (muted, accent, error).
### Themes (M1.10)
- `lutra_engine::theme` defines `DARK` (`lutra-dark`) and `LIGHT` (`lutra-light`) with the same token names, plus shared font tokens. Besides the base colours (`bg`, `editor-bg`, `fg`, `fg-muted`, `border`, `accent`, `error`, `statusbar-*`) both define `editor-selection-bg`, `editor-active-line-bg`, `editor-cursor`, `editor-gutter-bg`, `editor-gutter-fg`, `editor-match-bg`, `tab-active-bg`, `tab-modified`, `notice-bg`; `font-size-editor` is shared (14px). Values are opaque `#rrggbb` derived from the palette (selection, match and notice are the accent mixed into the background); the designer may change values, never names.
@ -159,6 +168,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
| Date | Change | Summary |
|---|---|---|
| 2026-10-16 | minor | M1.12: notifications (host emission, early-event replay, toast store and stack, deferred engine_ready) |
| 2026-10-16 | minor | M1.13: open buffers pin their parent directory in the watcher, `bufferFocused`, truncated listing row |
| 2026-10-16 | minor | M1.7: recovery journal (storage, debounce, removal, commands, recoveryAvailable, restore dialog) |
| 2026-10-16 | minor | M1.10: themes (light theme, editor tokens, theme.list, theme.systemPreference, themeChanged, init script from the setting, live switch, contrast test) |

View file

@ -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 with tabs, undo, multi-caret~~ (M1.6, CodeMirror basics), ~~recovery journal~~ (M1.7), tab management (preview, pin, split, close others, reopen), conflict UI for files changed on disk, autosave option | M1 | ~16 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~~ (M1.13), error notifications for the folder picker, ~~tabs~~ (M1.6); command palette, settings (backend: M1.9a; dialog: M1.9b), ~~theme switching~~ (M1.10: light/dark, live, system mode; picker comes with the dialog) | M1 | ~24 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~~ (M1.13), ~~error notifications for the folder picker~~ (M1.12), ~~tabs~~ (M1.6); command palette, settings (backend: M1.9a; dialog: M1.9b), ~~theme switching~~ (M1.10: light/dark, live, system mode; picker comes with the dialog) | 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 |
@ -42,6 +42,7 @@ Known smaller items from M0:
| 2026-10-16 | minor | G2/G3: re-open focuses the tab, open buffers' folders watched, truncated listings shown (M1.13) |
| 2026-10-15 | minor | G14 note: English message catalog (M1.11) |
| 2026-10-15 | minor | G2 shrunk: tabs and editor (M1.6) |
| 2026-10-16 | minor | G3: folder-picker error notifications (M1.12) |
| 2026-10-16 | minor | G2 shrunk, G11 note: recovery journal (M1.7) |
| 2026-10-16 | minor | G3: theme switching (M1.10) |
| 2026-10-16 | minor | G3: settings backend (M1.9a) |

View file

@ -1,10 +1,10 @@
# Localization checklist
> **Status:** English catalog covers 100% of UI strings (M1.11); German not started · **Last updated:** 2026-10-15
> **Status:** English catalog covers 100% of UI strings (M1.11); German not started · **Last updated:** 2026-10-16
| Language | Code | Status | Translated |
|---|---|---|---:|
| English | `en` | source catalog (`ui/src/i18n/en.json`) | 100% of UI strings (20 keys, measured by the catalog test) |
| English | `en` | source catalog (`ui/src/i18n/en.json`) | 100% of UI strings (46 keys, measured by the catalog test) |
| German | `de` | planned (G14) | 0% |
All interface strings go through the message catalog: `t(key, params?)` from `ui/src/i18n`, flat dotted keys grouped by area (`app.*`, `project.*`, `editor.*`, `common.*`), `{name}` placeholders. Lint (`vue/no-bare-strings-in-template`, error) rejects bare text in templates; a Vitest scan checks that every key passed to `t` exists in `en.json` and that the catalog has no unused keys.
@ -14,6 +14,7 @@ All interface strings go through the message catalog: `t(key, params?)` from `ui
- [x] English message catalog and `t` helper (M1.11)
- [x] Lint rule against bare template strings (M1.11)
- [x] Every UI string in `ui/src` from the catalog: templates, `title` and `aria-label` attributes, notices, frontend error texts (M1.11)
- [x] Notification texts: engine and host notifications carry a `messageKey` with params; all 12 notification message keys are in the catalog (M1.7, M1.12), `message` is only the English fallback
- [ ] Engine messages: `EngineError.message` and other texts the engine sends are English only; they need message keys and params (G14)
- [ ] Setting labels and descriptions from `settings.list` (`labelKey`, `descriptionKey`) in the catalog (M1.9b)
- [ ] Language switch through `ui.language`; the catalog becomes reactive (G14)
@ -25,5 +26,6 @@ All interface strings go through the message catalog: `t(key, params?)` from `ui
| Date | Change | Summary |
|---|---|---|
| 2026-10-16 | minor | M1.12: notification keys, key count 46 |
| 2026-10-15 | minor | M1.11: English catalog, lint rule, checklist; engine-message gap |
| 2026-10-13 | major | Baseline |

View file

@ -7,7 +7,7 @@ Hours are agent wall-clock hours for one agent; M0 and M1 so far are measured, t
| 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: hosted on Forgejo, runners unknown) | ~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, M1.4 desktop bridge, M1.6 tabs and editor, M1.11 message catalog, M1.9a settings backend, M1.10 themes, M1.7 recovery journal, M1.13 C1 follow-ups) | ~6 (2.5 measured for M1.1–M1.6) |
| 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, M1.6 tabs and editor, M1.11 message catalog, M1.9a settings backend, M1.10 themes, M1.7 recovery journal, M1.12 notifications, M1.13 C1 follow-ups) | ~6 (2.5 measured for M1.1–M1.6) |
| M2 | Syntax and search: highlighting, structure, find in files, go to file/class/symbol | not started | ~5 |
| M3 | LSP, terminal, CLI: completion, diagnostics, go to definition, hover, rename; terminal; `lutra` CLI and MCP — **MVP** | not started | ~8 |
| M4 | Git: status, diff, commit, branches, log, blame, conflicts | not started | ~150 |
@ -31,6 +31,7 @@ By the raw estimates the alpha gate needs M1–M4 plus cross-platform verificati
| Date | Change | Summary |
|---|---|---|
| 2026-10-16 | minor | M1.12 notifications |
| 2026-10-16 | minor | M1.13 C1 follow-ups |
| 2026-10-16 | minor | M1.7 recovery journal |
| 2026-10-16 | minor | M1.9a settings backend, M1.10 themes |

View file

@ -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 | 9% (est.) | syntax highlighting (M2), code folding, soft wrap and other editor settings, preview tab, pinned/split/reordered tabs, close others/all, reopen closed tab, tab limit, conflict UI for files changed on disk, autosave, local history, encodings other than UTF-8, large-file mode, column selection and multi-caret checked against the docs; recovery journal not yet checked in the running app (gaming mode) | ~106 (est.) | M1.13: opening a file that is already open switches to its tab (`bufferFocused`; engine test, Vitest, control-channel test; live check pending (gaming mode)); files in folders the tree never expanded still reload or report changes on disk, because the parent directory of every open buffer stays watched (engine tests). M1.7: crash-recovery journal (`crates/engine/src/journal.rs`, `cmd/recovery.rs`): dirty buffers are written atomically to `<data_dir>/recovery/<project-id>/` about 1 s after the last edit (at least every 2 s while typing), never per keystroke; removed on save, close and discard; `recoveryAvailable` after `project.open`, `recovery.list/restore/discard`; restored buffers are dirty and keep line ending and BOM; corrupt entries are moved aside with a warning. Restore dialog (`ui/src/components/recovery/`: Restore all / selected / Discard, time, changed-on-disk hint). Tests: engine dropped mid-edit and a new engine restores the exact CRLF + BOM text, corrupt entries, removal paths, a property test of random edit sequences → crash → restore equals the buffer (`crates/engine/tests/recovery.rs`, 10 tests), the same flow headless over the control channel (`crates/control/tests/recovery.rs`), 10 Vitest tests for the dialog. 1 MiB entry write: 8.5 ms median (release, measured). Graded against `plan/phpstorm/04-recovery.md`. M1.6: tabs and a CodeMirror 6 editor in the app (`ui/src/components/editor/`, `ui/src/stores/editor.ts`): open from the project tree or engine events, activate, close by button, middle click or `Mod+W`, dirty dot, Save / Don't Save / Cancel on closing a dirty tab, `Mod+S` / `Mod+Alt+S` from engine command specs, non-blocking notice for a dirty file changed or deleted on disk; local edits go to `buffer.edit` with version-based resync, CRLF files keep `\r\n`; undo/redo, multiple selections, search and bracket matching from CodeMirror's basic setup. Vitest: a burst of 400 keystrokes with stale versions and remote edits loses none, a CRLF burst with deletions converges, store and component tests against a fake engine (`ui/tests/editor/`, 22 tests). Checked in the app on Windows 11 with `--control` and `ui.screenshot`: typing via the UI and via `buffer.edit`, save to disk, close question, middle click, disk-change notice. 1 MB file (16,385 lines): engine `file.open` 80 ms over the control channel (debug build, measured), editor state 1–6 ms and first rendered view 4–11 ms in Chromium (measured), ≈ 90 ms in total (estimated, budget 150 ms). Graded against `plan/phpstorm/03-editor-tabs.md`. `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 | 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 | ~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`). M1.13: a directory listed only partly (more than 100,000 entries) ends with a "Listing truncated" note row (Vitest). 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 |
| 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 | ~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`). M1.13: a directory listed only partly (more than 100,000 entries) ends with a "Listing truncated" note row (Vitest). M1.12: a folder that cannot be opened from the picker or the command line (including `unsaved_changes` when switching projects) and stopped file watching show as toasts instead of stderr (`apps/lutra-desktop/src/host.rs`, `ui/src/stores/notifications.ts`, `ui/tests/notifications/`, 19 Vitest tests; live check pending, gaming mode); score unchanged. 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.) | — |
@ -62,6 +62,7 @@ The project tree is the first user-visible feature (Project view 8%, estimated);
| Date | Change | Summary |
|---|---|---|
| 2026-10-16 | minor | M1.12: Project view evidence (picker errors as toasts), scores unchanged |
| 2026-10-16 | minor | M1.13: Editor core and Project view evidence (focus on re-open, watched buffer folders, truncated note), scores unchanged |
| 2026-10-16 | minor | M1.7: Editor core 8% → 9% (est.), crash-recovery journal and restore dialog |
| 2026-10-16 | minor | M1.10: Settings row 2% → 4% (est.), light/dark themes with live switching |

View file

@ -1,6 +1,6 @@
# UI parity checklist
> **Status:** main window layout (M1.5), project tree running against the engine (M1.4), editor tabs with a CodeMirror editor (M1.6), light and dark themes (M1.10), restore dialog for unsaved changes (M1.7) · **Last updated:** 2026-10-16
> **Status:** main window layout (M1.5), project tree running against the engine (M1.4), editor tabs with a CodeMirror editor (M1.6), light and dark themes (M1.10), restore dialog for unsaved changes (M1.7), notification toasts (M1.12) · **Last updated:** 2026-10-16
- [ ] 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).
@ -17,6 +17,7 @@
- [ ] Light and dark themes from theme tokens
- M1.10 (2026-10-16): Lutra Dark and Lutra Light from Rust tokens, switched live through `appearance.theme` (no reload), `system` follows the OS preference, the first frame uses the stored theme; the editor (selection, active line, cursor, gutter, matches), tabs and notices have their own tokens; WCAG AA contrast checked by Vitest for every text pair in both themes. Covered by Vitest DOM and control-channel tests; live check pending (gaming mode). Missing: a theme picker (settings dialog, M1.9b; command palette, M1.8), the native title bar following the theme, editor font size from `editor.fontSize`, colour scheme editor, high-contrast theme, design review of the values.
- [ ] Notifications and background task indicator
- M1.12 (2026-10-16): toasts at the bottom right for engine and host notifications (corrupt settings and journal entries at startup, folder that cannot be opened, `unsaved_changes` when switching projects, file watching stopped, failed commands without their own UI): info dismissed after 5 s, warnings and errors stay until closed, close button and Escape, at most 5 visible with "+n more", `role="status"`/`role="alert"`; startup notifications are replayed when the page starts listening. Vitest (19 store and component tests); live check pending (gaming mode). Missing: a notification log / Notifications tool window, actions inside a toast, balloon grouping, "don't show again", background task indicator with progress.
- [ ] Structure tool window
- [ ] Problems tool window
- [ ] Find tool window
@ -27,6 +28,7 @@
| Date | Change | Summary |
|---|---|---|
| 2026-10-16 | minor | Notifications partial (M1.12) |
| 2026-10-16 | minor | Truncated listing note, re-open switches tab (M1.13) |
| 2026-10-16 | minor | Restore dialog (M1.7) |
| 2026-10-16 | minor | Themes partial (M1.10) |

View file

@ -2,29 +2,36 @@
/**
* Root component: mounts the main window layout with the editor area; the
* slogan shows while no tab is open, and the restore dialog for unsaved
* texts from the recovery journal. Loads product information from the
* engine on mount and starts following the theme (see `theme.ts`).
* texts from the recovery journal, and the toast stack. Loads product
* information from the engine on mount, starts showing notifications and
* following the theme (see `theme.ts`); a failed theme report raises an
* error toast.
*/
import { onMounted, onUnmounted } from "vue";
import EditorArea from "./components/editor/EditorArea.vue";
import MainLayout from "./components/layout/MainLayout.vue";
import NotificationStack from "./components/notifications/NotificationStack.vue";
import RecoveryDialog from "./components/recovery/RecoveryDialog.vue";
import { useAppStore } from "./stores/app";
import { useNotificationsStore } from "./stores/notifications";
import { startTheme } from "./theme";
const app = useAppStore();
const notifications = useNotificationsStore();
/** Stops following the theme; set while mounted. */
let stopTheme: (() => void) | null = null;
onMounted(() => {
stopTheme = startTheme();
notifications.start();
stopTheme = startTheme((error) => notifications.notifyError("theme.systemPreference", error));
void app.loadAbout();
});
onUnmounted(() => {
stopTheme?.();
stopTheme = null;
notifications.stop();
});
</script>
@ -37,6 +44,7 @@ onUnmounted(() => {
</EditorArea>
</MainLayout>
<RecoveryDialog />
<NotificationStack />
</template>
<style scoped>

View file

@ -5,17 +5,20 @@
*
* Shortcuts come from the engine's command specs (see `shortcuts.ts`); the
* area listens on the window in the capture phase so they also work while
* CodeMirror has the focus.
* CodeMirror has the focus. A keymap that cannot be loaded raises an
* error toast.
*/
import { onBeforeUnmount, onMounted } from "vue";
import { t } from "../../i18n";
import { useEditorStore } from "../../stores/editor";
import { useNotificationsStore } from "../../stores/notifications";
import ClosePrompt from "./ClosePrompt.vue";
import CodeEditor from "./CodeEditor.vue";
import EditorTabs from "./EditorTabs.vue";
import { commandFor, loadEditorKeymap, type EditorKeymap } from "./shortcuts";
const editor = useEditorStore();
const notifications = useNotificationsStore();
/** Keymap loaded from the engine, empty until loaded. */
let keymap: EditorKeymap = [];
@ -52,7 +55,7 @@ onMounted(() => {
if (result.ok) {
keymap = result.value;
} else {
editor.lastError = result.error;
notifications.notifyError("listCommands", result.error);
}
});
});

View file

@ -0,0 +1,168 @@
<script setup lang="ts">
/**
* The toast stack at the bottom right of the window, newest at the bottom.
*
* Shows the toasts of the notifications store: info toasts as
* `role="status"`, warnings and errors as `role="alert"`. Each toast has a
* close button and closes with Escape while focus is inside it; older
* toasts beyond the visible limit collapse into a "+n more" button. The
* colours match the editor's in-place notices (`--lt-notice-bg`, the error
* tint).
*/
import { CircleAlert, Info, TriangleAlert, X } from "@lucide/vue";
import { t } from "../../i18n";
import { useNotificationsStore, type NotificationLevel } from "../../stores/notifications";
const notifications = useNotificationsStore();
/** Icon of each level. */
const ICONS = { info: Info, warning: TriangleAlert, error: CircleAlert } as const;
/**
* ARIA role of a toast: errors and warnings interrupt, info is polite.
*
* @param level - the toast's level.
*/
function roleOf(level: NotificationLevel): "status" | "alert" {
return level === "info" ? "status" : "alert";
}
</script>
<template>
<section
v-if="notifications.toasts.length > 0"
class="toasts"
:aria-label="t('notification.stack.label')"
data-test="toasts"
>
<button
v-if="notifications.hiddenCount > 0"
type="button"
class="toasts__more"
data-test="toasts-more"
@click="notifications.expand()"
>
{{ t("notification.stack.more", { count: notifications.hiddenCount }) }}
</button>
<div
v-for="toast in notifications.visible"
:key="toast.id"
class="toast"
:class="`toast--${toast.level}`"
:role="roleOf(toast.level)"
data-test="toast"
:data-level="toast.level"
@keydown.escape.stop="notifications.dismiss(toast.id)"
>
<component
:is="ICONS[toast.level]"
class="toast__icon"
:size="16"
aria-hidden="true"
/>
<span
class="toast__text"
data-test="toast-text"
>{{ toast.text }}</span>
<button
type="button"
class="toast__close"
:aria-label="t('notification.close')"
:title="t('notification.close')"
data-test="toast-close"
@click="notifications.dismiss(toast.id)"
>
<X
:size="14"
aria-hidden="true"
/>
</button>
</div>
</section>
</template>
<style scoped>
.toasts {
position: fixed;
right: 16px;
bottom: 36px;
z-index: 100;
display: flex;
flex-direction: column;
align-items: flex-end;
gap: 8px;
width: min(420px, calc(100vw - 32px));
max-height: calc(100vh - 72px);
overflow-y: auto;
user-select: text;
}
.toast {
display: flex;
align-items: flex-start;
gap: 8px;
width: 100%;
box-sizing: border-box;
padding: 8px 8px 8px 12px;
color: var(--lt-fg);
background: var(--lt-notice-bg);
border: 1px solid var(--lt-border);
border-left: 3px solid var(--lt-fg-muted);
border-radius: 4px;
}
.toast--warning {
border-left-color: var(--lt-accent);
}
.toast--error {
background: color-mix(in srgb, var(--lt-error) 15%, var(--lt-bg));
border-left-color: var(--lt-error);
}
.toast__icon {
flex-shrink: 0;
margin-top: 2px;
color: var(--lt-fg-muted);
}
.toast--warning .toast__icon {
color: var(--lt-accent);
}
.toast--error .toast__icon {
color: var(--lt-error);
}
.toast__text {
flex: 1;
min-width: 0;
overflow-wrap: anywhere;
}
.toast__close,
.toasts__more {
font: inherit;
color: var(--lt-fg);
background: transparent;
border: 1px solid var(--lt-border);
border-radius: 3px;
}
.toast__close {
display: inline-flex;
flex-shrink: 0;
padding: 2px;
}
.toasts__more {
padding: 2px 8px;
background: var(--lt-notice-bg);
}
.toast__close:focus-visible,
.toasts__more:focus-visible {
outline: 2px solid var(--lt-accent);
outline-offset: 1px;
}
</style>

View file

@ -16,9 +16,21 @@
"editor.tabs.close": "Close {name}",
"editor.tabs.label": "Editor tabs",
"editor.tabs.unsaved": "unsaved changes",
"notification.close": "Close notification",
"notification.command.failed": "{command} failed: {message}",
"notification.project.notLocal": "The chosen folder is not on this computer: {reason}",
"notification.project.openFailed": "Cannot open {path}: {reason}",
"notification.project.unsavedChanges": "Cannot open {path} while {what} has unsaved changes. Save or close it first.",
"notification.recovery.corrupt": "Skipped an unreadable recovery file ({file}): {reason}",
"notification.recovery.unavailable": "Could not read the recovery journal: {reason}",
"notification.recovery.writeFailed": "Could not keep a recovery copy of {path}: {reason}",
"notification.settings.corrupt": "Your settings file could not be read ({reason}). It was moved to {backup} and the defaults are used.",
"notification.settings.corruptNotMoved": "Your settings file could not be read ({reason}) or moved aside ({error}). The defaults are used and changes are not saved.",
"notification.settings.unavailable": "Settings cannot be loaded ({error}). The defaults are used and changes are not saved.",
"notification.stack.label": "Notifications",
"notification.stack.more": "+{count} more",
"notification.vfs.pumpFailed": "Applying changes on disk failed: {reason}",
"notification.watch.failed": "Lutra stopped watching the project for changes on disk: {reason}",
"project.empty.noFolder": "No folder is open.",
"project.openFolder": "Open Folder…",
"project.toolWindow.title": "Project",

View file

@ -31,6 +31,19 @@ export type EngineEventPayload =
| {
kind: "recoveryAvailable";
entries: { path: string; savedAt: number; diskChanged: boolean }[];
}
| {
kind: "notification";
/** Unique id (`n1`, `n2`…); unchecked, it comes from the engine. */
id: unknown;
/** `info`, `warning` or `error`; unchecked. */
level: unknown;
/** Catalog key of the text; unchecked. */
messageKey?: unknown;
/** English fallback text; unchecked. */
message?: unknown;
/** Placeholder values; unchecked. */
params?: unknown;
};
/** Callback receiving engine events. */
@ -39,11 +52,35 @@ export type EngineEventHandler = (event: EngineEventPayload) => void;
/** Whether the shell was told that the frontend listens (`engine_ready`). */
let announced = false;
/** Subscriptions started but not yet registered with the shell. */
let pending = 0;
/** Subscriptions registered with the shell and not ended. */
let live = 0;
/**
* 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.
* Tells the shell that the frontend listens, once, as soon as a
* subscription is live and no started one is still being registered.
* Subscriptions made while the page mounts all start in the same tick, so
* every one of them receives the replay. A failed announcement is retried
* by the next subscription.
*/
function announce(): void {
if (announced || pending > 0 || live === 0) {
return;
}
announced = true;
invoke("engine_ready").catch(() => {
announced = false;
});
}
/**
* Subscribes to engine events. Once the subscriptions started together are
* registered, the shell is told that the frontend listens, so it replays
* the current project state and the notifications 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.
@ -51,27 +88,31 @@ let announced = false;
export function onEngineEvent(handler: EngineEventHandler): () => void {
let unlisten: UnlistenFn | null = null;
let cancelled = false;
pending += 1;
listen<EngineEventPayload>(ENGINE_EVENT, (event) => {
handler(event.payload);
})
.then((fn) => {
pending -= 1;
if (cancelled) {
fn();
return;
}
unlisten = fn;
if (!announced) {
announced = true;
invoke("engine_ready").catch(() => {
announced = false;
});
} else {
unlisten = fn;
live += 1;
}
announce();
})
.catch(() => undefined);
.catch(() => {
pending -= 1;
announce();
});
return () => {
cancelled = true;
unlisten?.();
unlisten = null;
if (unlisten) {
unlisten();
unlisten = null;
live -= 1;
}
};
}

View file

@ -0,0 +1,274 @@
/**
* Notifications shown as toasts at the bottom right of the window.
*
* Toasts come from the engine's `notification` events (startup, journal,
* picker and pump errors, replayed by the shell on `engine_ready`), from
* `watchFailed` events, which the frontend maps to a warning, and from
* frontend code through {@link useNotificationsStore}'s `notify` and
* `notifyError` for failed commands that have no UI of their own.
*
* Info toasts dismiss themselves after {@link INFO_TIMEOUT_MS}; warnings
* and errors stay until closed. At most {@link MAX_VISIBLE} toasts show;
* older ones collapse into a "+n more" entry.
*/
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { hasMessage, t, type MessageParams } from "../i18n";
import { onEngineEvent, type EngineError, type EngineEventPayload } from "../ipc";
/** Severity of a toast. */
export type NotificationLevel = "info" | "warning" | "error";
/** Time after which an info toast dismisses itself, in milliseconds. */
export const INFO_TIMEOUT_MS = 5000;
/** Most toasts shown at once; older ones collapse into "+n more". */
export const MAX_VISIBLE = 5;
/** Most toasts kept; the oldest are dropped beyond that. */
export const MAX_KEPT = 100;
/** Catalog key of the toast for a `watchFailed` event. Params: `reason`. */
export const KEY_WATCH_FAILED = "notification.watch.failed";
/** Catalog key of the toast for a failed command. Params: `command`, `message`. */
export const KEY_COMMAND_FAILED = "notification.command.failed";
/** A toast as the stack shows it. */
export interface Toast {
/** Unique id: the engine's (`n1`…) or a frontend one (`ui1`…). */
id: string;
/** Severity. */
level: NotificationLevel;
/** The text, already looked up in the catalog. */
text: string;
}
/** What a notification says, before it is turned into a toast. */
export interface NotificationInput {
/** Id from the engine; a frontend id is made when absent. */
id?: string | undefined;
/** Severity. */
level: NotificationLevel;
/** Catalog key of the text. */
messageKey?: string | undefined;
/** English text, used when the key is absent or not in the catalog. */
message?: string | undefined;
/** Values for the catalog text's placeholders. */
params?: MessageParams | undefined;
}
/**
* The text of a notification: the catalog message for its key if the
* catalog has it, else the English text, else the key.
*
* @param input - the notification.
*/
export function notificationText(input: NotificationInput): string {
if (input.messageKey !== undefined && hasMessage(input.messageKey)) {
return t(input.messageKey, input.params);
}
return input.message ?? input.messageKey ?? "";
}
/**
* Reads untrusted params from the engine: string and number values are
* kept, anything else is shown as JSON.
*
* @param raw - the `params` field of the event.
*/
function toParams(raw: unknown): MessageParams | undefined {
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
return undefined;
}
const params: Record<string, string | number> = {};
for (const [name, value] of Object.entries(raw)) {
params[name] = typeof value === "string" || typeof value === "number" ? value : JSON.stringify(value);
}
return params;
}
/**
* Checks the level of an untrusted event; an unknown level counts as an
* error so that it is not missed.
*
* @param raw - the `level` field of the event.
*/
function toLevel(raw: unknown): NotificationLevel {
return raw === "info" || raw === "warning" ? raw : "error";
}
/**
* The notification an engine event asks for, or null for other events.
*
* @param event - the engine event.
*/
export function notificationFromEvent(event: EngineEventPayload): NotificationInput | null {
if (event.kind === "notification") {
return {
id: typeof event.id === "string" ? event.id : undefined,
level: toLevel(event.level),
messageKey: typeof event.messageKey === "string" ? event.messageKey : undefined,
message: typeof event.message === "string" ? event.message : undefined,
params: toParams(event.params),
};
}
if (event.kind === "watchFailed") {
return {
level: "warning",
messageKey: KEY_WATCH_FAILED,
message: event.message,
params: { reason: event.message },
};
}
return null;
}
/** Store of the toast stack. */
export const useNotificationsStore = defineStore("notifications", () => {
/** Every toast not yet dismissed, oldest first. */
const toasts = ref<Toast[]>([]);
/** Whether the collapsed older toasts are shown. */
const expanded = ref(false);
/** Number of frontend ids handed out. */
let made = 0;
/** Auto-dismiss timers of info toasts, by id. */
const timers = new Map<string, ReturnType<typeof setTimeout>>();
/** Ends the engine event subscription; set while started. */
let unsubscribe: (() => void) | null = null;
/** The toasts shown: the newest {@link MAX_VISIBLE}, or all when expanded. */
const visible = computed(() =>
expanded.value ? toasts.value : toasts.value.slice(-MAX_VISIBLE),
);
/** Number of older toasts collapsed into "+n more". */
const hiddenCount = computed(() => toasts.value.length - visible.value.length);
/**
* Shows a toast. A notification whose id is already shown (an engine
* replay after a reload) is ignored.
*
* @param input - the notification.
* @returns the toast's id.
*/
function notify(input: NotificationInput): string {
made += 1;
const id = input.id ?? `ui${String(made)}`;
if (toasts.value.some((toast) => toast.id === id)) {
return id;
}
toasts.value.push({ id, level: input.level, text: notificationText(input) });
while (toasts.value.length > MAX_KEPT) {
const dropped = toasts.value.shift();
if (dropped) {
clearTimer(dropped.id);
}
}
if (input.level === "info") {
timers.set(
id,
setTimeout(() => {
dismiss(id);
}, INFO_TIMEOUT_MS),
);
}
return id;
}
/**
* Shows an error toast for a failed command that has no UI of its own.
*
* @param command - the command id.
* @param error - the error it failed with.
* @returns the toast's id.
*/
function notifyError(command: string, error: EngineError): string {
return notify({
level: "error",
messageKey: KEY_COMMAND_FAILED,
message: error.message,
params: { command, message: error.message },
});
}
/**
* Stops the auto-dismiss timer of a toast, if it has one.
*
* @param id - the toast's id.
*/
function clearTimer(id: string): void {
const timer = timers.get(id);
if (timer !== undefined) {
clearTimeout(timer);
timers.delete(id);
}
}
/**
* Closes a toast. Once nothing is collapsed any more, the stack folds
* again.
*
* @param id - the toast's id; an unknown id does nothing.
*/
function dismiss(id: string): void {
clearTimer(id);
toasts.value = toasts.value.filter((toast) => toast.id !== id);
if (toasts.value.length <= MAX_VISIBLE) {
expanded.value = false;
}
}
/** Closes every toast. */
function dismissAll(): void {
for (const id of timers.keys()) {
clearTimer(id);
}
toasts.value = [];
expanded.value = false;
}
/** Shows the toasts collapsed into "+n more". */
function expand(): void {
expanded.value = true;
}
/**
* Applies one engine event: notifications and `watchFailed` become
* toasts, other events are ignored.
*
* @param event - the event.
*/
function handleEvent(event: EngineEventPayload): void {
const input = notificationFromEvent(event);
if (input) {
notify(input);
}
}
/** Starts showing engine notifications. Calling it again does nothing. */
function start(): void {
unsubscribe ??= onEngineEvent(handleEvent);
}
/** Stops showing engine notifications; shown toasts stay. */
function stop(): void {
unsubscribe?.();
unsubscribe = null;
}
return {
toasts,
visible,
hiddenCount,
expanded,
notify,
notifyError,
dismiss,
dismissAll,
expand,
handleEvent,
start,
stop,
};
});

View file

@ -6,7 +6,7 @@
* resolves the theme from the OS preference that {@link startTheme} reports
* with `theme.systemPreference` whenever it changes.
*/
import { onEngineEvent, run } from "./ipc";
import { onEngineEvent, run, type EngineError } from "./ipc";
/** A resolved theme as the engine sends it. */
export interface ResolvedTheme {
@ -68,10 +68,15 @@ export function applyTheme(theme: ResolvedTheme, root: HTMLElement = document.do
* resolves. A failed call keeps the current theme.
*
* @param dark - whether the OS prefers a dark theme.
* @param onError - called with the error of a failed call.
*/
export async function reportSystemPreference(dark: boolean): Promise<void> {
export async function reportSystemPreference(
dark: boolean,
onError?: (error: EngineError) => void,
): Promise<void> {
const result = await run("theme.systemPreference", { dark });
if (!result.ok) {
onError?.(result.error);
return;
}
const theme = toResolvedTheme(result.value);
@ -85,9 +90,10 @@ export async function reportSystemPreference(dark: boolean): Promise<void> {
* reports the OS preference now and whenever it changes. Outside a browser
* with `matchMedia` the OS preference counts as dark.
*
* @param onError - called when reporting the OS preference fails.
* @returns a function that stops following.
*/
export function startTheme(): () => void {
export function startTheme(onError?: (error: EngineError) => void): () => void {
const unsubscribe = onEngineEvent((event) => {
if (event.kind === "themeChanged") {
const theme = toResolvedTheme(event);
@ -98,10 +104,10 @@ export function startTheme(): () => void {
});
const query = typeof window.matchMedia === "function" ? window.matchMedia(DARK_QUERY) : null;
const onChange = (event: MediaQueryListEvent): void => {
void reportSystemPreference(event.matches);
void reportSystemPreference(event.matches, onError);
};
query?.addEventListener("change", onChange);
void reportSystemPreference(query?.matches ?? true);
void reportSystemPreference(query?.matches ?? true, onError);
return () => {
unsubscribe();
query?.removeEventListener("change", onChange);

View file

@ -37,13 +37,23 @@ const usedKeys = sourceFiles(SRC).flatMap((file) =>
/**
* Keys the source never passes to `t` literally because they arrive at
* runtime from the engine: theme labels from `theme.list` and the
* `messageKey` of `notification` events.
* runtime: theme labels from `theme.list`, the `messageKey` of
* `notification` events (engine and desktop host), and the keys the
* notifications store passes through a constant.
*/
const RUNTIME_KEYS = new Set([
"notification.command.failed",
"notification.project.notLocal",
"notification.project.openFailed",
"notification.project.unsavedChanges",
"notification.recovery.corrupt",
"notification.recovery.unavailable",
"notification.recovery.writeFailed",
"notification.settings.corrupt",
"notification.settings.corruptNotMoved",
"notification.settings.unavailable",
"notification.vfs.pumpFailed",
"notification.watch.failed",
"theme.lutraDark",
"theme.lutraLight",
]);

View file

@ -41,6 +41,39 @@ describe("onEngineEvent", () => {
expect(unlisten).toHaveBeenCalledTimes(2);
});
it("announces readiness only after every subscription started together is registered", async () => {
const resolvers: ((fn: () => void) => void)[] = [];
listen.mockImplementation(
() =>
new Promise<() => void>((resolve) => {
resolvers.push(resolve);
}),
);
const { onEngineEvent } = await import("../src/ipc");
onEngineEvent(() => undefined);
const stopSecond = onEngineEvent(() => undefined);
resolvers[0]?.(() => undefined);
await flushPromises();
expect(invoke).not.toHaveBeenCalled();
stopSecond();
resolvers[1]?.(() => undefined);
await flushPromises();
expect(invoke).toHaveBeenCalledTimes(1);
expect(invoke).toHaveBeenCalledWith("engine_ready");
});
it("does not announce readiness without a live subscription", async () => {
listen.mockResolvedValue(() => undefined);
const { onEngineEvent } = await import("../src/ipc");
const stop = onEngineEvent(() => undefined);
stop();
await flushPromises();
expect(invoke).not.toHaveBeenCalled();
onEngineEvent(() => undefined);
await flushPromises();
expect(invoke).toHaveBeenCalledTimes(1);
});
it("unlistens a subscription that was cancelled before it started", async () => {
const unlisten = vi.fn();
listen.mockResolvedValue(unlisten);

View file

@ -0,0 +1,279 @@
/**
* Tests for the notifications store and the toast stack: the lifecycle of
* a toast, auto-dismiss of info toasts with fake timers, the overflow into
* "+n more", ARIA roles, keyboard closing, engine `notification` and
* `watchFailed` events (including untrusted fields), and the replay
* duplicate guard.
*/
import { mount, type VueWrapper } from "@vue/test-utils";
import { createPinia, setActivePinia, type Pinia } from "pinia";
import { afterEach, 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 }));
import NotificationStack from "../../src/components/notifications/NotificationStack.vue";
import {
INFO_TIMEOUT_MS,
MAX_KEPT,
MAX_VISIBLE,
notificationFromEvent,
notificationText,
useNotificationsStore,
} from "../../src/stores/notifications";
/** Pinia of the current test. */
let pinia: Pinia;
/** The mounted stack of the current test, unmounted afterwards. */
let wrapper: VueWrapper | null = null;
/** Mounts the stack. */
function mountStack(): VueWrapper {
wrapper = mount(NotificationStack, { attachTo: document.body, global: { plugins: [pinia] } });
return wrapper;
}
beforeEach(() => {
vi.useFakeTimers();
pinia = createPinia();
setActivePinia(pinia);
invoke.mockReset();
listen.mockReset();
invoke.mockResolvedValue(null);
});
afterEach(() => {
wrapper?.unmount();
wrapper = null;
vi.useRealTimers();
});
describe("notifications store", () => {
it("shows a toast until it is dismissed", () => {
const store = useNotificationsStore();
const id = store.notify({ level: "warning", message: "careful" });
expect(store.toasts).toEqual([{ id, level: "warning", text: "careful" }]);
vi.advanceTimersByTime(INFO_TIMEOUT_MS * 10);
expect(store.toasts).toHaveLength(1);
store.dismiss(id);
expect(store.toasts).toEqual([]);
});
it("dismisses info toasts after five seconds", () => {
const store = useNotificationsStore();
store.notify({ level: "info", message: "saved" });
store.notify({ level: "error", message: "broken" });
vi.advanceTimersByTime(INFO_TIMEOUT_MS - 1);
expect(store.toasts).toHaveLength(2);
vi.advanceTimersByTime(1);
expect(store.toasts.map((toast) => toast.text)).toEqual(["broken"]);
});
it("stops the timer of an info toast closed early", () => {
const store = useNotificationsStore();
const first = store.notify({ level: "info", message: "a" });
store.dismiss(first);
expect(vi.getTimerCount()).toBe(0);
});
it("ignores a notification id that is already shown", () => {
const store = useNotificationsStore();
store.notify({ id: "n1", level: "warning", message: "a" });
store.notify({ id: "n1", level: "warning", message: "a" });
expect(store.toasts).toHaveLength(1);
});
it("collapses older toasts beyond the visible limit", () => {
const store = useNotificationsStore();
for (let i = 1; i <= MAX_VISIBLE + 2; i += 1) {
store.notify({ level: "error", message: `e${String(i)}` });
}
expect(store.visible.map((toast) => toast.text)).toEqual(["e3", "e4", "e5", "e6", "e7"]);
expect(store.hiddenCount).toBe(2);
store.expand();
expect(store.visible).toHaveLength(MAX_VISIBLE + 2);
expect(store.hiddenCount).toBe(0);
store.dismiss(store.toasts[0]?.id ?? "");
store.dismiss(store.toasts[0]?.id ?? "");
expect(store.expanded).toBe(false);
});
it("keeps at most MAX_KEPT toasts", () => {
const store = useNotificationsStore();
for (let i = 0; i < MAX_KEPT + 3; i += 1) {
store.notify({ level: "info", message: `i${String(i)}` });
}
expect(store.toasts).toHaveLength(MAX_KEPT);
expect(store.toasts[0]?.text).toBe("i3");
vi.advanceTimersByTime(INFO_TIMEOUT_MS);
expect(store.toasts).toEqual([]);
expect(vi.getTimerCount()).toBe(0);
});
it("turns a failed command into an error toast", () => {
const store = useNotificationsStore();
store.notifyError("theme.systemPreference", { code: "internal", message: "boom" });
expect(store.toasts[0]).toMatchObject({
level: "error",
text: "theme.systemPreference failed: boom",
});
});
it("dismisses everything", () => {
const store = useNotificationsStore();
store.notify({ level: "info", message: "a" });
store.notify({ level: "error", message: "b" });
store.dismissAll();
expect(store.toasts).toEqual([]);
expect(vi.getTimerCount()).toBe(0);
});
});
describe("notification text", () => {
it("uses the catalog message with params", () => {
expect(
notificationText({
level: "warning",
messageKey: "notification.settings.corrupt",
message: "english",
params: { reason: "bad JSON", backup: "settings.json.bad-1" },
}),
).toBe(
"Your settings file could not be read (bad JSON). It was moved to settings.json.bad-1 and the defaults are used.",
);
});
it("falls back to the English text, then the key", () => {
vi.spyOn(console, "warn").mockImplementation(() => undefined);
expect(notificationText({ level: "error", messageKey: "no.such.key", message: "raw" })).toBe("raw");
expect(notificationText({ level: "error", messageKey: "no.such.key" })).toBe("no.such.key");
expect(notificationText({ level: "error" })).toBe("");
});
});
describe("engine events", () => {
it("reads notification events and checks untrusted fields", () => {
expect(
notificationFromEvent({
kind: "notification",
id: "n3",
level: "warning",
messageKey: "notification.recovery.corrupt",
message: "Skipped",
params: { file: "a.json", reason: "bad", extra: { deep: 1 } },
}),
).toEqual({
id: "n3",
level: "warning",
messageKey: "notification.recovery.corrupt",
message: "Skipped",
params: { file: "a.json", reason: "bad", extra: '{"deep":1}' },
});
expect(
notificationFromEvent({ kind: "notification", id: 7, level: "loud", params: [1] }),
).toEqual({ id: undefined, level: "error", messageKey: undefined, message: undefined, params: undefined });
});
it("maps watchFailed to a warning", () => {
const input = notificationFromEvent({ kind: "watchFailed", message: "too many watches" });
expect(input?.level).toBe("warning");
expect(input && notificationText(input)).toBe(
"Lutra stopped watching the project for changes on disk: too many watches",
);
});
it("ignores other events", () => {
expect(notificationFromEvent({ kind: "projectClosed" })).toBeNull();
});
it("shows engine notifications once started", async () => {
const callbacks: ((event: { payload: unknown }) => void)[] = [];
const unlisten = vi.fn();
listen.mockImplementation((_name: string, callback: (event: { payload: unknown }) => void) => {
callbacks.push(callback);
return Promise.resolve(unlisten);
});
const store = useNotificationsStore();
store.start();
store.start();
await vi.runAllTimersAsync();
expect(listen).toHaveBeenCalledTimes(1);
callbacks[0]?.({
payload: {
kind: "notification",
id: "n1",
level: "warning",
messageKey: "notification.project.unsavedChanges",
params: { path: "/other", what: "a.php" },
},
});
expect(store.toasts[0]?.text).toBe(
"Cannot open /other while a.php has unsaved changes. Save or close it first.",
);
store.stop();
expect(unlisten).toHaveBeenCalledTimes(1);
});
});
describe("NotificationStack", () => {
it("renders nothing without toasts", () => {
const stack = mountStack();
expect(stack.find('[data-test="toasts"]').exists()).toBe(false);
});
it("uses status for info and alert for warnings and errors", async () => {
const store = useNotificationsStore();
store.notify({ level: "info", message: "i" });
store.notify({ level: "warning", message: "w" });
store.notify({ level: "error", message: "e" });
const stack = mountStack();
await stack.vm.$nextTick();
const roles = stack.findAll('[data-test="toast"]').map((t) => t.attributes("role"));
expect(roles).toEqual(["status", "alert", "alert"]);
expect(stack.get('[data-test="toasts"]').attributes("aria-label")).toBe("Notifications");
});
it("closes a toast with its button and with Escape", async () => {
const store = useNotificationsStore();
store.notify({ level: "error", message: "one" });
store.notify({ level: "error", message: "two" });
const stack = mountStack();
await stack.vm.$nextTick();
const close = stack.get('[data-test="toast-close"]');
expect(close.attributes("type")).toBe("button");
expect(close.attributes("aria-label")).toBe("Close notification");
await close.trigger("click");
expect(store.toasts.map((t) => t.text)).toEqual(["two"]);
await stack.get('[data-test="toast"]').trigger("keydown", { key: "Escape" });
expect(store.toasts).toEqual([]);
});
it("collapses older toasts into +n more and expands them", async () => {
const store = useNotificationsStore();
for (let i = 1; i <= MAX_VISIBLE + 3; i += 1) {
store.notify({ level: "warning", message: `w${String(i)}` });
}
const stack = mountStack();
await stack.vm.$nextTick();
expect(stack.findAll('[data-test="toast"]')).toHaveLength(MAX_VISIBLE);
const more = stack.get('[data-test="toasts-more"]');
expect(more.text()).toBe("+3 more");
await more.trigger("click");
expect(stack.findAll('[data-test="toast"]')).toHaveLength(MAX_VISIBLE + 3);
expect(stack.find('[data-test="toasts-more"]').exists()).toBe(false);
});
it("removes an info toast from the screen after five seconds", async () => {
const store = useNotificationsStore();
store.notify({ level: "info", message: "done" });
const stack = mountStack();
await stack.vm.$nextTick();
expect(stack.get('[data-test="toast-text"]').text()).toBe("done");
vi.advanceTimersByTime(INFO_TIMEOUT_MS);
await stack.vm.$nextTick();
expect(stack.find('[data-test="toast"]').exists()).toBe(false);
});
});

View file

@ -141,11 +141,13 @@ describe("startTheme", () => {
stop();
});
it("keeps the current theme when the engine call fails", async () => {
it("keeps the current theme and reports the error when the engine call fails", async () => {
invoke.mockRejectedValue({ code: "internal", message: "down" });
const stop = startTheme();
const onError = vi.fn();
const stop = startTheme(onError);
await flushPromises();
expect(root.dataset.theme).toBeUndefined();
expect(onError).toHaveBeenCalledWith({ code: "internal", message: "down" });
stop();
});
});