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

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

@ -30,6 +30,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. */
@ -38,11 +51,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.
@ -50,27 +87,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();
});
});