M3.10: autosave and flushDirty
Autosave saves dirty buffers when the window loses focus (DOM blur and
visibilitychange), when the active tab changes and after
editor.autosave.idleSeconds (default 15) without an edit; three settings,
all on by default. flushDirty() in ui/src/stores/autosave.ts is the one
save-all-dirty-and-wait entry point for later deployment, run and
terminal features: it waits for pending buffer sync, then runs
file.saveAll {skipConflicts: true}; one toast per failed file.
Engine: file.saveAll takes skipConflicts and returns skipped; Buffers
tracks buffers in conflict with their file and the hash of the last
read/written content, so our own save reported late is not a conflict.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
228669036c
commit
e1dc24dc25
18 changed files with 996 additions and 37 deletions
|
|
@ -8,6 +8,7 @@
|
|||
* `theme.ts`; a failed theme report raises an error toast) and the global
|
||||
* keymap with the UI commands (see `commands/store.ts`), and loads the settings so the
|
||||
* editor font size applies from the start (see `stores/settings.ts`).
|
||||
* Starts autosave (see `stores/autosave.ts`).
|
||||
*/
|
||||
import { onMounted, onUnmounted } from "vue";
|
||||
import { useCommandsStore } from "./commands/store";
|
||||
|
|
@ -19,6 +20,7 @@ import NotificationStack from "./components/notifications/NotificationStack.vue"
|
|||
import RecoveryDialog from "./components/recovery/RecoveryDialog.vue";
|
||||
import SettingsDialog from "./components/settings/SettingsDialog.vue";
|
||||
import { useAppStore } from "./stores/app";
|
||||
import { useAutosaveStore } from "./stores/autosave";
|
||||
import { useNotificationsStore } from "./stores/notifications";
|
||||
import { useSettingsStore } from "./stores/settings";
|
||||
import { startTheme } from "./theme";
|
||||
|
|
@ -27,6 +29,7 @@ const app = useAppStore();
|
|||
const notifications = useNotificationsStore();
|
||||
const commands = useCommandsStore();
|
||||
const settings = useSettingsStore();
|
||||
const autosave = useAutosaveStore();
|
||||
|
||||
/** Stops following the theme; set while mounted. */
|
||||
let stopTheme: (() => void) | null = null;
|
||||
|
|
@ -36,6 +39,7 @@ onMounted(() => {
|
|||
stopTheme = startTheme((error) => notifications.notifyError("theme.systemPreference", error));
|
||||
void commands.start();
|
||||
void settings.start();
|
||||
autosave.start();
|
||||
void app.loadAbout();
|
||||
});
|
||||
|
||||
|
|
@ -43,6 +47,7 @@ onUnmounted(() => {
|
|||
stopTheme?.();
|
||||
stopTheme = null;
|
||||
commands.stop();
|
||||
autosave.stop();
|
||||
settings.stop();
|
||||
notifications.stop();
|
||||
});
|
||||
|
|
|
|||
|
|
@ -84,6 +84,7 @@
|
|||
"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.save.failed": "{name} could not be saved: {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.",
|
||||
|
|
@ -123,6 +124,12 @@
|
|||
"settings.dialog.search": "Search settings",
|
||||
"settings.dialog.sections": "Settings sections",
|
||||
"settings.dialog.title": "Settings",
|
||||
"settings.editor.autosave.idleSeconds.description": "Save changed files after this many seconds without typing. 0 turns idle saving off.",
|
||||
"settings.editor.autosave.idleSeconds.label": "Autosave after idle (seconds)",
|
||||
"settings.editor.autosave.onBlur.description": "Save changed files when the Lutra window loses focus, for example when you switch to a browser or a terminal.",
|
||||
"settings.editor.autosave.onBlur.label": "Autosave when leaving the window",
|
||||
"settings.editor.autosave.onTabSwitch.description": "Save changed files when you switch to another editor tab.",
|
||||
"settings.editor.autosave.onTabSwitch.label": "Autosave on tab switch",
|
||||
"settings.editor.fontSize.description": "Size of the text in the editor, in pixels.",
|
||||
"settings.editor.fontSize.label": "Editor font size",
|
||||
"settings.error.int": "Enter a whole number",
|
||||
|
|
|
|||
353
ui/src/stores/autosave.ts
Normal file
353
ui/src/stores/autosave.ts
Normal file
|
|
@ -0,0 +1,353 @@
|
|||
/**
|
||||
* Autosave and the one "save every dirty buffer and wait" entry point.
|
||||
*
|
||||
* {@link useAutosaveStore}'s `flushDirty()` waits until every tab's local
|
||||
* edits reached the engine (`editor.settleAll`), then runs
|
||||
* `file.saveAll {skipConflicts: true}` and resolves with what was saved,
|
||||
* what failed and what was skipped. It never rejects. Buffers whose file
|
||||
* changed or disappeared on disk are skipped, because only the user can
|
||||
* settle that (the tab shows the notice). The engine has no untitled
|
||||
* buffers yet; every buffer has a path. Each failed file gets one error
|
||||
* toast (`notification.save.failed`). Calls are serialised: a call made
|
||||
* while a flush runs queues one more flush, and calls made while that one
|
||||
* waits share it. Autosave uses it, and so must anything that needs the
|
||||
* files on disk first (deployment, run configurations, terminal commands).
|
||||
* Nothing is uploaded on save.
|
||||
*
|
||||
* Autosave triggers, each with a setting (all on by default):
|
||||
* - `editor.autosave.onBlur`: the window loses focus. Lutra listens to the
|
||||
* DOM `blur` event of `window` and to `visibilitychange` (hidden). In the
|
||||
* Tauri WebView these fire when the native window loses focus or is
|
||||
* minimised, they need no extra Tauri capability, and they work the same
|
||||
* in Vitest; Tauri's own window events would add a permission and an
|
||||
* IPC hop for the same signal.
|
||||
* - `editor.autosave.onTabSwitch`: the active tab changes.
|
||||
* - `editor.autosave.idleSeconds` (0 = off): no edit for that many seconds.
|
||||
* Edits are seen as engine events (`bufferChanged`, `dirtyChanged`), so
|
||||
* edits from the control channel or an agent count too.
|
||||
*
|
||||
* Triggers do nothing while no tab has unsaved changes. An autosave toasts
|
||||
* a failure only once until that file saves again, so a file that cannot be
|
||||
* written does not raise a toast on every blur. The recovery journal stays
|
||||
* the safety net for anything not saved yet.
|
||||
*/
|
||||
import { defineStore } from "pinia";
|
||||
import { shallowRef, watch } from "vue";
|
||||
import { run, type EngineError } from "../ipc";
|
||||
import { onEditorEvent, type EditorEvent } from "../components/editor/engineEvents";
|
||||
import { baseName, EDITOR_COMMANDS, useEditorStore } from "./editor";
|
||||
import { useNotificationsStore } from "./notifications";
|
||||
import { useSettingsStore } from "./settings";
|
||||
|
||||
/** Setting keys of autosave. */
|
||||
export const AUTOSAVE_SETTINGS = {
|
||||
/** Save when the window loses focus (bool, default true). */
|
||||
onBlur: "editor.autosave.onBlur",
|
||||
/** Save when the active tab changes (bool, default true). */
|
||||
onTabSwitch: "editor.autosave.onTabSwitch",
|
||||
/** Save after this many seconds without an edit (int 0–600, default 15; 0 = off). */
|
||||
idleSeconds: "editor.autosave.idleSeconds",
|
||||
} as const;
|
||||
|
||||
/** Defaults used until the settings are loaded. */
|
||||
export const AUTOSAVE_DEFAULTS = { onBlur: true, onTabSwitch: true, idleSeconds: 15 } as const;
|
||||
|
||||
/** Largest idle time accepted, in seconds (the setting's maximum). */
|
||||
const MAX_IDLE_SECONDS = 600;
|
||||
|
||||
/** Catalog key of the toast for a file that could not be saved. Params: `name`, `reason`. */
|
||||
export const KEY_SAVE_FAILED = "notification.save.failed";
|
||||
|
||||
/** What made an autosave run. */
|
||||
export type AutosaveTrigger = "blur" | "tabSwitch" | "idle";
|
||||
|
||||
/** A buffer that could not be saved. */
|
||||
export interface FlushFailure {
|
||||
/** Buffer id. */
|
||||
id: number;
|
||||
/** Project-relative path; empty when the engine did not say. */
|
||||
path: string;
|
||||
/** Why. */
|
||||
message: string;
|
||||
}
|
||||
|
||||
/** What {@link useAutosaveStore}'s `flushDirty` did. */
|
||||
export interface FlushResult {
|
||||
/** Ids of the buffers written. */
|
||||
saved: number[];
|
||||
/** Buffers that could not be written. */
|
||||
failed: FlushFailure[];
|
||||
/** Ids of dirty buffers left alone because their file changed on disk. */
|
||||
skipped: number[];
|
||||
/** Set when `file.saveAll` itself failed (no project, IPC); nothing was saved then. */
|
||||
error: EngineError | null;
|
||||
}
|
||||
|
||||
/** Options of `flushDirty`. */
|
||||
export interface FlushOptions {
|
||||
/**
|
||||
* Toast a failure again even if the same file failed with the same
|
||||
* message before (default true). Autosave passes false.
|
||||
*/
|
||||
repeatErrors?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* The ids in a list, ignoring entries that are not numbers.
|
||||
*
|
||||
* @param raw - an array from the engine, unchecked.
|
||||
*/
|
||||
function ids(raw: unknown): number[] {
|
||||
return Array.isArray(raw) ? raw.filter((v): v is number => typeof v === "number") : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the result of `file.saveAll`.
|
||||
*
|
||||
* @param raw - `{saved, failed, skipped}`, unchecked.
|
||||
*/
|
||||
export function toFlushResult(raw: unknown): FlushResult {
|
||||
const value = (typeof raw === "object" && raw !== null ? raw : {}) as Record<string, unknown>;
|
||||
const failed = Array.isArray(value.failed) ? value.failed : [];
|
||||
return {
|
||||
saved: ids(value.saved),
|
||||
skipped: ids(value.skipped),
|
||||
failed: failed.flatMap((f: unknown) => {
|
||||
const entry = (typeof f === "object" && f !== null ? f : {}) as Record<string, unknown>;
|
||||
return typeof entry.id === "number"
|
||||
? [
|
||||
{
|
||||
id: entry.id,
|
||||
path: typeof entry.path === "string" ? entry.path : "",
|
||||
message: typeof entry.message === "string" ? entry.message : "",
|
||||
},
|
||||
]
|
||||
: [];
|
||||
}),
|
||||
error: null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Store of autosave and `flushDirty`. */
|
||||
export const useAutosaveStore = defineStore("autosave", () => {
|
||||
const editor = useEditorStore();
|
||||
const settings = useSettingsStore();
|
||||
const notifications = useNotificationsStore();
|
||||
|
||||
/** Result of the last flush, null before the first. */
|
||||
const lastResult = shallowRef<FlushResult | null>(null);
|
||||
/** End of the chain of flushes; each starts after the previous one. */
|
||||
let tail: Promise<unknown> = Promise.resolve();
|
||||
/** A flush queued behind a running one and not started yet; later calls share it. */
|
||||
let waiting: Promise<FlushResult> | null = null;
|
||||
/** Failures already toasted, as message by buffer id (`""` for the command itself). */
|
||||
const reported = new Map<string, string>();
|
||||
/** Idle timer, null when none runs. */
|
||||
let idleTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
/** Cleanups of the started listeners. */
|
||||
let cleanups: (() => void)[] = [];
|
||||
|
||||
/**
|
||||
* A boolean setting, its default until the settings are loaded.
|
||||
*
|
||||
* @param key - setting key.
|
||||
* @param fallback - default.
|
||||
*/
|
||||
function flag(key: string, fallback: boolean): boolean {
|
||||
const value = settings.values[key];
|
||||
return typeof value === "boolean" ? value : fallback;
|
||||
}
|
||||
|
||||
/** The idle time in milliseconds, 0 when idle saving is off. */
|
||||
function idleMs(): number {
|
||||
const value = settings.values[AUTOSAVE_SETTINGS.idleSeconds];
|
||||
const seconds = typeof value === "number" && Number.isFinite(value) ? value : AUTOSAVE_DEFAULTS.idleSeconds;
|
||||
return Math.min(Math.max(Math.trunc(seconds), 0), MAX_IDLE_SECONDS) * 1000;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows a failure unless it was shown already and repeats are off.
|
||||
*
|
||||
* @param key - buffer id as text, or `""` for the command.
|
||||
* @param message - the failure.
|
||||
* @param repeat - show it even if shown before.
|
||||
* @param show - shows the toast.
|
||||
*/
|
||||
function report(key: string, message: string, repeat: boolean, show: () => void): void {
|
||||
if (!repeat && reported.get(key) === message) {
|
||||
return;
|
||||
}
|
||||
reported.set(key, message);
|
||||
show();
|
||||
}
|
||||
|
||||
/**
|
||||
* One flush: settle, save, toast the failures. A sync that cannot settle
|
||||
* is ignored: the engine's text is still saved, and the sync reports its
|
||||
* own error on the tab.
|
||||
*
|
||||
* @param options - see {@link FlushOptions}.
|
||||
*/
|
||||
async function flushNow(options: FlushOptions): Promise<FlushResult> {
|
||||
const repeat = options.repeatErrors ?? true;
|
||||
await editor.settleAll().catch(() => undefined);
|
||||
const outcome = await run<unknown>(EDITOR_COMMANDS.saveAll, { skipConflicts: true });
|
||||
if (!outcome.ok) {
|
||||
const result: FlushResult = { saved: [], failed: [], skipped: [], error: outcome.error };
|
||||
report("", outcome.error.message, repeat, () => notifications.notifyError(EDITOR_COMMANDS.saveAll, outcome.error));
|
||||
lastResult.value = result;
|
||||
return result;
|
||||
}
|
||||
reported.delete("");
|
||||
const result = toFlushResult(outcome.value);
|
||||
for (const id of result.saved) {
|
||||
reported.delete(String(id));
|
||||
}
|
||||
for (const failure of result.failed) {
|
||||
const path = failure.path || (editor.tabs.find((tab) => tab.id === failure.id)?.path ?? "");
|
||||
const name = path ? baseName(path) : String(failure.id);
|
||||
report(String(failure.id), failure.message, repeat, () =>
|
||||
notifications.notify({
|
||||
level: "error",
|
||||
messageKey: KEY_SAVE_FAILED,
|
||||
message: `${name}: ${failure.message}`,
|
||||
params: { name, reason: failure.message },
|
||||
}),
|
||||
);
|
||||
}
|
||||
lastResult.value = result;
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves every dirty buffer once the pending edits reached the engine and
|
||||
* resolves when that is done or failed; never rejects. Buffers in
|
||||
* conflict with the disk are skipped. Call it before anything that needs
|
||||
* the files on disk (deployment, run configurations, terminal commands).
|
||||
*
|
||||
* @param options - see {@link FlushOptions}.
|
||||
* @returns what was saved, failed and skipped.
|
||||
*/
|
||||
function flushDirty(options: FlushOptions = {}): Promise<FlushResult> {
|
||||
if (waiting) {
|
||||
return waiting;
|
||||
}
|
||||
const job = tail.then(() => {
|
||||
waiting = null;
|
||||
return flushNow(options);
|
||||
});
|
||||
waiting = job;
|
||||
tail = job;
|
||||
return job;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs an autosave if its trigger is on and a tab has unsaved changes.
|
||||
*
|
||||
* @param trigger - what happened.
|
||||
* @returns the flush, or null when nothing ran.
|
||||
*/
|
||||
function autosave(trigger: AutosaveTrigger): Promise<FlushResult> | null {
|
||||
if (trigger === "blur" && !flag(AUTOSAVE_SETTINGS.onBlur, AUTOSAVE_DEFAULTS.onBlur)) {
|
||||
return null;
|
||||
}
|
||||
if (trigger === "tabSwitch" && !flag(AUTOSAVE_SETTINGS.onTabSwitch, AUTOSAVE_DEFAULTS.onTabSwitch)) {
|
||||
return null;
|
||||
}
|
||||
if (trigger === "idle" && idleMs() === 0) {
|
||||
return null;
|
||||
}
|
||||
if (!editor.hasUnsaved()) {
|
||||
return null;
|
||||
}
|
||||
return flushDirty({ repeatErrors: false });
|
||||
}
|
||||
|
||||
/** Stops the idle timer. */
|
||||
function cancelIdle(): void {
|
||||
if (idleTimer !== null) {
|
||||
clearTimeout(idleTimer);
|
||||
idleTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** (Re)starts the idle timer after an edit, if idle saving is on. */
|
||||
function restartIdle(): void {
|
||||
cancelIdle();
|
||||
const ms = idleMs();
|
||||
if (ms > 0) {
|
||||
idleTimer = setTimeout(() => {
|
||||
idleTimer = null;
|
||||
void autosave("idle");
|
||||
}, ms);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Restarts the idle timer for an edit seen as an engine event.
|
||||
*
|
||||
* @param event - an editor event.
|
||||
*/
|
||||
function handleEvent(event: EditorEvent): void {
|
||||
if (event.kind === "bufferChanged" || (event.kind === "dirtyChanged" && event.dirty)) {
|
||||
restartIdle();
|
||||
} else if (event.kind === "projectClosed" || event.kind === "projectOpened") {
|
||||
cancelIdle();
|
||||
}
|
||||
}
|
||||
|
||||
/** The window lost focus. */
|
||||
function onBlur(): void {
|
||||
void autosave("blur");
|
||||
}
|
||||
|
||||
/** The page became hidden (minimised, another desktop). */
|
||||
function onVisibility(): void {
|
||||
if (document.visibilityState === "hidden") {
|
||||
void autosave("blur");
|
||||
}
|
||||
}
|
||||
|
||||
/** Starts the triggers; calling it again has no effect. */
|
||||
function start(): void {
|
||||
if (cleanups.length > 0) {
|
||||
return;
|
||||
}
|
||||
window.addEventListener("blur", onBlur);
|
||||
document.addEventListener("visibilitychange", onVisibility);
|
||||
const stopTabs = watch(
|
||||
() => editor.activeId,
|
||||
(now, before) => {
|
||||
if (before !== null && now !== before) {
|
||||
void autosave("tabSwitch");
|
||||
}
|
||||
},
|
||||
);
|
||||
const stopIdleSetting = watch(
|
||||
() => settings.values[AUTOSAVE_SETTINGS.idleSeconds],
|
||||
() => {
|
||||
if (idleTimer !== null) {
|
||||
restartIdle();
|
||||
}
|
||||
},
|
||||
);
|
||||
cleanups = [
|
||||
() => { window.removeEventListener("blur", onBlur); },
|
||||
() => { document.removeEventListener("visibilitychange", onVisibility); },
|
||||
stopTabs,
|
||||
stopIdleSetting,
|
||||
onEditorEvent(handleEvent),
|
||||
cancelIdle,
|
||||
];
|
||||
}
|
||||
|
||||
/** Stops the triggers. */
|
||||
function stop(): void {
|
||||
for (const cleanup of cleanups) {
|
||||
cleanup();
|
||||
}
|
||||
cleanups = [];
|
||||
}
|
||||
|
||||
return { lastResult, flushDirty, autosave, handleEvent, start, stop };
|
||||
});
|
||||
|
|
@ -26,7 +26,10 @@ export const EDITOR_COMMANDS = {
|
|||
get: "buffer.get",
|
||||
/** Saves a buffer: params `{ id }`. */
|
||||
save: "file.save",
|
||||
/** Saves every dirty buffer: result `{ saved, failed: [{ id, message }] }`. */
|
||||
/**
|
||||
* Saves every dirty buffer: params `{ skipConflicts? }`, result
|
||||
* `{ saved, failed: [{ id, path, message }], skipped }`.
|
||||
*/
|
||||
saveAll: "file.saveAll",
|
||||
/** Closes a buffer: params `{ id, force }`; fails with `unsaved_changes`. */
|
||||
close: "buffer.close",
|
||||
|
|
@ -274,6 +277,19 @@ export const useEditorStore = defineStore("editor", () => {
|
|||
await syncs.get(id)?.idle();
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits until the local edits of every tab reached the engine, so a
|
||||
* following save writes what the user sees (autosave, `flushDirty`).
|
||||
*/
|
||||
async function settleAll(): Promise<void> {
|
||||
await Promise.all([...syncs.values()].map((sync) => sync.idle()));
|
||||
}
|
||||
|
||||
/** Whether any tab has unsaved changes or edits still on the way. */
|
||||
function hasUnsaved(): boolean {
|
||||
return tabs.value.some((t) => t.dirty) || [...syncs.values()].some((sync) => sync.pending);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs `buffer.close`.
|
||||
*
|
||||
|
|
@ -517,6 +533,8 @@ export const useEditorStore = defineStore("editor", () => {
|
|||
resolveClose,
|
||||
save,
|
||||
saveAll,
|
||||
settleAll,
|
||||
hasUnsaved,
|
||||
dismissNotice,
|
||||
markShown,
|
||||
handleEvent,
|
||||
|
|
|
|||
273
ui/tests/editor/autosave.test.ts
Normal file
273
ui/tests/editor/autosave.test.ts
Normal file
|
|
@ -0,0 +1,273 @@
|
|||
/**
|
||||
* Tests of autosave and `flushDirty` (`stores/autosave.ts`) with fake
|
||||
* timers: saving after idle, on window blur and hidden pages, on a tab
|
||||
* switch, the settings that turn each off, waiting for pending buffer sync,
|
||||
* skipped conflicts, one toast per failed file (not repeated by autosave)
|
||||
* and serialised flushes. The engine is a fake behind the mocked Tauri
|
||||
* `invoke`; the editor's syncs use a fake transport whose edits resolve
|
||||
* when the test says so.
|
||||
*/
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
import { nextTick } from "vue";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const invoke = vi.hoisted(() => vi.fn());
|
||||
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
|
||||
|
||||
import { emitEditorEvent } from "../../src/components/editor/engineEvents";
|
||||
import type { EditParams, EditResult, SyncTransport } from "../../src/components/editor/bufferSync";
|
||||
import type { RunResult } from "../../src/ipc";
|
||||
import { AUTOSAVE_SETTINGS, KEY_SAVE_FAILED, useAutosaveStore } from "../../src/stores/autosave";
|
||||
import { useEditorStore } from "../../src/stores/editor";
|
||||
import { useNotificationsStore } from "../../src/stores/notifications";
|
||||
import { useSettingsStore } from "../../src/stores/settings";
|
||||
|
||||
/** Every `engine_execute` call, in order. */
|
||||
let calls: { command: string; params: Record<string, unknown> }[];
|
||||
/** Next result of `file.saveAll`. */
|
||||
let saveAllResult: unknown;
|
||||
/** Edits the fake transport received and has not answered yet. */
|
||||
let pendingEdits: { params: EditParams; resolve: (r: RunResult<EditResult>) => void }[];
|
||||
|
||||
/** Latest version the fake engine reported per buffer, for `buffer.get`. */
|
||||
let versions: Map<number, number>;
|
||||
|
||||
/** Fake sync transport: edits wait for the test; `get` returns the latest version. */
|
||||
const transport: SyncTransport = {
|
||||
edit: (params) =>
|
||||
new Promise((resolve) => {
|
||||
pendingEdits.push({ params, resolve });
|
||||
}),
|
||||
get: (id) =>
|
||||
Promise.resolve({
|
||||
ok: true,
|
||||
value: { id, path: "x", text: "abc", version: versions.get(id) ?? 1, dirty: true, lineEnding: "lf" },
|
||||
}),
|
||||
};
|
||||
|
||||
/** Answers every pending edit with success. */
|
||||
function confirmEdits(): void {
|
||||
for (const edit of pendingEdits.splice(0)) {
|
||||
versions.set(edit.params.id, edit.params.baseVersion + 1);
|
||||
edit.resolve({ ok: true, value: { id: edit.params.id, version: edit.params.baseVersion + 1, dirty: true } });
|
||||
}
|
||||
}
|
||||
|
||||
/** The `file.saveAll` calls so far. */
|
||||
function saveAllCalls(): Record<string, unknown>[] {
|
||||
return calls.filter((c) => c.command === "file.saveAll").map((c) => c.params);
|
||||
}
|
||||
|
||||
/** Lets promises and Vue watchers run. */
|
||||
async function settle(): Promise<void> {
|
||||
for (let i = 0; i < 5; i += 1) {
|
||||
await Promise.resolve();
|
||||
await nextTick();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a tab for a fake buffer.
|
||||
*
|
||||
* @param id - buffer id.
|
||||
* @param path - project-relative path.
|
||||
* @param dirty - whether it starts dirty.
|
||||
*/
|
||||
async function openTab(id: number, path: string, dirty = false): Promise<void> {
|
||||
const editor = useEditorStore();
|
||||
invoke.mockImplementationOnce(() => Promise.resolve({ id, path, text: "abc", version: 1, dirty, lineEnding: "lf" }));
|
||||
await editor.openFile(path);
|
||||
}
|
||||
|
||||
/** Marks buffer `id` edited the way the engine reports it. */
|
||||
function engineEdit(id: number, version = 2): void {
|
||||
versions.set(id, version);
|
||||
emitEditorEvent({ kind: "bufferChanged", id, version });
|
||||
emitEditorEvent({ kind: "dirtyChanged", id, dirty: true });
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
setActivePinia(createPinia());
|
||||
calls = [];
|
||||
pendingEdits = [];
|
||||
versions = new Map();
|
||||
saveAllResult = { saved: [], failed: [], skipped: [] };
|
||||
invoke.mockReset();
|
||||
invoke.mockImplementation((cmd: string, args: { command?: string; params?: Record<string, unknown> }) => {
|
||||
if (cmd !== "engine_execute") {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
const command = args.command ?? "";
|
||||
calls.push({ command, params: args.params ?? {} });
|
||||
if (command === "file.saveAll") {
|
||||
return Promise.resolve(saveAllResult);
|
||||
}
|
||||
return Promise.resolve(null);
|
||||
});
|
||||
useEditorStore().configure(transport, () => []);
|
||||
useEditorStore().start();
|
||||
useAutosaveStore().start();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
useAutosaveStore().stop();
|
||||
useEditorStore().stop();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("autosave triggers", () => {
|
||||
it("saves after the idle time without edits, counting from the last edit", async () => {
|
||||
await openTab(1, "a.php");
|
||||
engineEdit(1);
|
||||
await vi.advanceTimersByTimeAsync(10_000);
|
||||
engineEdit(1, 3);
|
||||
await vi.advanceTimersByTimeAsync(14_000);
|
||||
expect(saveAllCalls()).toHaveLength(0);
|
||||
await vi.advanceTimersByTimeAsync(1_000);
|
||||
await settle();
|
||||
expect(saveAllCalls()).toEqual([{ skipConflicts: true }]);
|
||||
});
|
||||
|
||||
it("follows the idle setting, and 0 turns idle saving off", async () => {
|
||||
const settings = useSettingsStore();
|
||||
settings.values[AUTOSAVE_SETTINGS.idleSeconds] = 3;
|
||||
await openTab(1, "a.php");
|
||||
engineEdit(1);
|
||||
await vi.advanceTimersByTimeAsync(3_000);
|
||||
await settle();
|
||||
expect(saveAllCalls()).toHaveLength(1);
|
||||
settings.values[AUTOSAVE_SETTINGS.idleSeconds] = 0;
|
||||
engineEdit(1, 3);
|
||||
await vi.advanceTimersByTimeAsync(700_000);
|
||||
await settle();
|
||||
expect(saveAllCalls()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("does nothing while no tab has unsaved changes", async () => {
|
||||
await openTab(1, "a.php");
|
||||
versions.set(1, 2);
|
||||
emitEditorEvent({ kind: "bufferChanged", id: 1, version: 2 });
|
||||
await vi.advanceTimersByTimeAsync(20_000);
|
||||
window.dispatchEvent(new Event("blur"));
|
||||
await settle();
|
||||
expect(saveAllCalls()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("saves when the window loses focus or the page is hidden", async () => {
|
||||
await openTab(1, "a.php", true);
|
||||
window.dispatchEvent(new Event("blur"));
|
||||
await settle();
|
||||
expect(saveAllCalls()).toHaveLength(1);
|
||||
const visibility = vi.spyOn(document, "visibilityState", "get").mockReturnValue("hidden");
|
||||
document.dispatchEvent(new Event("visibilitychange"));
|
||||
await settle();
|
||||
expect(saveAllCalls()).toHaveLength(2);
|
||||
visibility.mockReturnValue("visible");
|
||||
document.dispatchEvent(new Event("visibilitychange"));
|
||||
await settle();
|
||||
expect(saveAllCalls()).toHaveLength(2);
|
||||
visibility.mockRestore();
|
||||
});
|
||||
|
||||
it("does not save on blur when that setting is off", async () => {
|
||||
useSettingsStore().values[AUTOSAVE_SETTINGS.onBlur] = false;
|
||||
await openTab(1, "a.php", true);
|
||||
window.dispatchEvent(new Event("blur"));
|
||||
await settle();
|
||||
expect(saveAllCalls()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("saves when the active tab changes, unless that setting is off", async () => {
|
||||
await openTab(1, "a.php");
|
||||
await openTab(2, "b.php");
|
||||
await settle();
|
||||
engineEdit(2);
|
||||
expect(saveAllCalls()).toHaveLength(0);
|
||||
const editor = useEditorStore();
|
||||
editor.activate(1);
|
||||
await settle();
|
||||
expect(saveAllCalls()).toHaveLength(1);
|
||||
useSettingsStore().values[AUTOSAVE_SETTINGS.onTabSwitch] = false;
|
||||
editor.activate(2);
|
||||
await settle();
|
||||
expect(saveAllCalls()).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("flushDirty", () => {
|
||||
it("waits until pending edits reached the engine before saving", async () => {
|
||||
await openTab(1, "a.php");
|
||||
const editor = useEditorStore();
|
||||
editor.syncOf(1)?.dispatch({ changes: { from: 3, insert: "d" } });
|
||||
expect(pendingEdits).toHaveLength(1);
|
||||
const done = useAutosaveStore().flushDirty();
|
||||
await settle();
|
||||
expect(saveAllCalls()).toHaveLength(0);
|
||||
confirmEdits();
|
||||
await settle();
|
||||
expect(saveAllCalls()).toHaveLength(1);
|
||||
await expect(done).resolves.toMatchObject({ error: null });
|
||||
});
|
||||
|
||||
it("reports skipped conflicts without a toast", async () => {
|
||||
saveAllResult = { saved: [1], failed: [], skipped: [2] };
|
||||
const result = await useAutosaveStore().flushDirty();
|
||||
expect(result).toEqual({ saved: [1], failed: [], skipped: [2], error: null });
|
||||
expect(useNotificationsStore().toasts).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("shows one toast per failed file, and autosave does not repeat it", async () => {
|
||||
await openTab(1, "src/a.php", true);
|
||||
saveAllResult = {
|
||||
saved: [],
|
||||
failed: [
|
||||
{ id: 1, path: "src/a.php", message: "access denied" },
|
||||
{ id: 2, message: "disk full" },
|
||||
],
|
||||
skipped: [],
|
||||
};
|
||||
const notifications = useNotificationsStore();
|
||||
const result = await useAutosaveStore().flushDirty();
|
||||
expect(result.failed).toEqual([
|
||||
{ id: 1, path: "src/a.php", message: "access denied" },
|
||||
{ id: 2, path: "", message: "disk full" },
|
||||
]);
|
||||
expect(notifications.toasts.map((t) => t.text)).toEqual([
|
||||
"a.php could not be saved: access denied",
|
||||
"2 could not be saved: disk full",
|
||||
]);
|
||||
expect(notifications.toasts.every((t) => t.level === "error")).toBe(true);
|
||||
window.dispatchEvent(new Event("blur"));
|
||||
await settle();
|
||||
expect(saveAllCalls()).toHaveLength(2);
|
||||
expect(notifications.toasts).toHaveLength(2);
|
||||
await useAutosaveStore().flushDirty();
|
||||
expect(notifications.toasts).toHaveLength(4);
|
||||
expect(KEY_SAVE_FAILED).toBe("notification.save.failed");
|
||||
});
|
||||
|
||||
it("toasts a failure of the command itself and resolves with the error", async () => {
|
||||
invoke.mockImplementation(() => Promise.reject(Object.assign(new Error("disabled"), { code: "disabled", message: "no project" })));
|
||||
const result = await useAutosaveStore().flushDirty();
|
||||
expect(result.error?.code).toBe("disabled");
|
||||
expect(result.saved).toEqual([]);
|
||||
expect(useNotificationsStore().toasts).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("serialises flushes and lets waiting callers share one", async () => {
|
||||
await openTab(1, "a.php");
|
||||
const editor = useEditorStore();
|
||||
editor.syncOf(1)?.dispatch({ changes: { from: 0, insert: "x" } });
|
||||
const autosave = useAutosaveStore();
|
||||
const first = autosave.flushDirty();
|
||||
await settle();
|
||||
const second = autosave.flushDirty();
|
||||
const third = autosave.flushDirty();
|
||||
await settle();
|
||||
expect(saveAllCalls()).toHaveLength(0);
|
||||
confirmEdits();
|
||||
await Promise.all([first, second, third]);
|
||||
expect(saveAllCalls()).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
|
@ -54,6 +54,7 @@ const RUNTIME_KEYS = new Set([
|
|||
"notification.recovery.corrupt",
|
||||
"notification.recovery.unavailable",
|
||||
"notification.recovery.writeFailed",
|
||||
"notification.save.failed",
|
||||
"notification.settings.corrupt",
|
||||
"notification.settings.corruptNotMoved",
|
||||
"notification.settings.unavailable",
|
||||
|
|
@ -68,6 +69,12 @@ const RUNTIME_KEYS = new Set([
|
|||
"settings.appearance.theme.value.lutraDark",
|
||||
"settings.appearance.theme.value.lutraLight",
|
||||
"settings.appearance.theme.value.system",
|
||||
"settings.editor.autosave.idleSeconds.description",
|
||||
"settings.editor.autosave.idleSeconds.label",
|
||||
"settings.editor.autosave.onBlur.description",
|
||||
"settings.editor.autosave.onBlur.label",
|
||||
"settings.editor.autosave.onTabSwitch.description",
|
||||
"settings.editor.autosave.onTabSwitch.label",
|
||||
"settings.editor.fontSize.description",
|
||||
"settings.editor.fontSize.label",
|
||||
"settings.php.executable.description",
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue