Lutra/ui/tests/editor/autosave.test.ts
danny e1dc24dc25 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>
2026-10-20 21:01:12 +02:00

273 lines
9.9 KiB
TypeScript

/**
* 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);
});
});