/** * 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; 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; 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(null); /** End of the chain of flushes; each starts after the previous one. */ let tail: Promise = Promise.resolve(); /** A flush queued behind a running one and not started yet; later calls share it. */ let waiting: Promise | null = null; /** Failures already toasted, as message by buffer id (`""` for the command itself). */ const reported = new Map(); /** Idle timer, null when none runs. */ let idleTimer: ReturnType | 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 { const repeat = options.repeatErrors ?? true; await editor.settleAll().catch(() => undefined); const outcome = await run(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 { 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 | 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 }; });