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,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue