Lutra/ui/tests/editor/diskConflicts.test.ts
danny d2344bf216 A2: disk-conflict banner, overwrite question and Local History dialog
- Banner inside the editor pane for a dirty tab whose file changed
  (Reload (discard mine) / Keep mine / Compare) or was deleted (Keep as
  unsaved / Close); state in stores/diskConflicts.ts, the old notice is gone.
- Save and save all ask Overwrite / Cancel when the engine refuses with
  disk_changed.
- Diff tabs against the disk text (file.readDisk) and a Local History
  entry (history.read); "Revert to This" in the caption.
- Show Local History dialog (history.show: tree context menu, palette,
  File menu) with Show Diff and an undoable Revert to This.
- History failures warn once until a snapshot works again.
- Docs: docs/local-history.md, G2 in gaps.md, ui-parity, architecture.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 12:55:04 +01:00

225 lines
8.8 KiB
TypeScript

/**
* Tests for files changed on disk (C10 A2) in the editor area: the banner
* for a changed and a deleted file and its actions (Reload, Keep mine,
* Compare, Keep as unsaved, Close), the overwrite question after the
* engine refuses a save with `disk_changed`, and the diff tab against the
* disk. The engine is a fake behind the mocked Tauri `invoke`.
*/
import { flushPromises, 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());
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
import { useCommandsStore } from "../../src/commands/store";
import EditorArea from "../../src/components/editor/EditorArea.vue";
import { emitEditorEvent } from "../../src/components/editor/engineEvents";
import { useDiffStore } from "../../src/components/vcs/diff/diff";
import { useDiskConflictsStore } from "../../src/stores/diskConflicts";
import { useEditorStore } from "../../src/stores/editor";
/** Every `engine_execute` call, in order. */
let calls: { command: string; params: Record<string, unknown> }[];
/** The text the fake buffer holds. */
let bufferText: string;
/** The text on the fake disk. */
let diskText: string;
/** Whether the next plain `file.save` is refused with `disk_changed`. */
let newerOnDisk: boolean;
/** Pinia of the current test. */
let pinia: Pinia;
/** Mounted components. */
let mounted: VueWrapper[] = [];
/** The buffer as `file.open` and `buffer.get` describe it. */
function info(): unknown {
return { id: 1, path: "src/a.php", text: bufferText, version: 1, dirty: true, lineEnding: "lf" };
}
/**
* Rejects like the shell does with an engine error.
*
* @param code - error code.
*/
function fail(code: string): Promise<never> {
return Promise.reject(Object.assign(new Error(code), { code, message: `${code} message` }));
}
/**
* The fake engine.
*
* @param command - command id.
* @param p - params.
*/
function execute(command: string, p: Record<string, unknown>): Promise<unknown> {
switch (command) {
case "file.open":
case "buffer.get":
return Promise.resolve(info());
case "file.save":
if (newerOnDisk && p.overwrite !== true) {
return fail("disk_changed");
}
diskText = bufferText;
return Promise.resolve({ id: 1, version: 1 });
case "file.saveAll":
return Promise.resolve({ saved: [], failed: [], skipped: [], diskChanged: newerOnDisk ? [1] : [] });
case "file.reload":
bufferText = diskText;
emitEditorEvent({ kind: "diskConflictResolved", id: 1 });
return Promise.resolve({ id: 1, version: 2, dirty: false });
case "file.readDisk":
return Promise.resolve({ text: diskText, binary: false, tooLarge: false });
case "buffer.close":
emitEditorEvent({ kind: "bufferClosed", id: 1 });
return Promise.resolve(null);
default:
return Promise.resolve(null);
}
}
/** Mounts the editor area with `src/a.php` open. */
async function mountWithFile(): Promise<VueWrapper> {
await useCommandsStore(pinia).start();
const wrapper = mount(EditorArea, { attachTo: document.body, global: { plugins: [pinia] } });
mounted.push(wrapper);
await useEditorStore(pinia).openFile("src/a.php");
await flushPromises();
return wrapper;
}
/**
* The commands the fake engine received, without reads.
*/
function commandsRun(): string[] {
return calls.map((c) => c.command).filter((c) => c !== "buffer.get" && c !== "file.open");
}
beforeEach(() => {
pinia = createPinia();
setActivePinia(pinia);
calls = [];
bufferText = "mine";
diskText = "theirs";
newerOnDisk = false;
invoke.mockReset();
invoke.mockImplementation((cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
if (cmd === "engine_list_commands") {
return Promise.resolve([]);
}
if ((cmd === "engine_execute" || cmd === "engine_execute_waiting") && args) {
calls.push({ command: args.command, params: args.params });
return execute(args.command, args.params);
}
return Promise.reject(new Error(`unexpected ${cmd}`));
});
});
afterEach(async () => {
await flushPromises();
useCommandsStore(pinia).stop();
for (const wrapper of mounted) {
wrapper.unmount();
}
mounted = [];
});
describe("files changed on disk", () => {
it("offers Reload, Keep mine and Compare for a changed file", async () => {
const area = await mountWithFile();
emitEditorEvent({ kind: "fileChangedOnDisk", id: 1, path: "src/a.php", removed: false });
await flushPromises();
const banner = area.find("[data-test=disk-banner]");
expect(banner.attributes("data-kind")).toBe("changed");
expect(banner.text()).toContain("a.php was changed by another program");
expect(banner.findAll("button").map((b) => b.text())).toEqual(["Reload (discard mine)", "Keep mine", "Compare"]);
await area.find("[data-test=disk-reload]").trigger("click");
await flushPromises();
expect(commandsRun()).toContain("file.reload");
expect(area.find("[data-test=disk-banner]").exists()).toBe(false);
});
it("compares the disk text with the buffer in a diff tab", async () => {
const area = await mountWithFile();
emitEditorEvent({ kind: "fileChangedOnDisk", id: 1, path: "src/a.php", removed: false });
await flushPromises();
await area.find("[data-test=disk-compare]").trigger("click");
await flushPromises();
const diff = useDiffStore(pinia);
expect(diff.activeTab?.key).toBe("disk:src/a.php");
expect(diff.activeContent?.phase).toBe("ready");
expect(diff.activeContent?.left).toBe("theirs");
expect(diff.activeContent?.bufferId).toBe(1);
expect(calls.find((c) => c.command === "file.readDisk")?.params).toEqual({ path: "src/a.php" });
});
it("asks once more when a kept buffer is saved over the newer file", async () => {
const area = await mountWithFile();
const editor = useEditorStore(pinia);
emitEditorEvent({ kind: "fileChangedOnDisk", id: 1, path: "src/a.php", removed: false });
await flushPromises();
await area.find("[data-test=disk-keep]").trigger("click");
expect(area.find("[data-test=disk-banner]").exists()).toBe(false);
newerOnDisk = true;
expect(await editor.save(1)).toBe(false);
await flushPromises();
expect(editor.lastError).toBeNull();
const prompt = area.find("[data-test=overwrite-prompt]");
expect(prompt.text()).toContain("a.php was changed by another program");
expect(document.activeElement?.getAttribute("data-test")).toBe("overwrite-cancel");
await area.find("[data-test=overwrite-cancel]").trigger("click");
await flushPromises();
expect(diskText).toBe("theirs");
expect(area.find("[data-test=overwrite-prompt]").exists()).toBe(false);
await editor.save(1);
await flushPromises();
await area.find("[data-test=overwrite-confirm]").trigger("click");
await flushPromises();
expect(calls.filter((c) => c.command === "file.save").map((c) => c.params)).toEqual([
{ id: 1 },
{ id: 1 },
{ id: 1, overwrite: true },
]);
expect(diskText).toBe("mine");
});
it("asks for buffers that save all left unsaved because their file is newer", async () => {
const area = await mountWithFile();
newerOnDisk = true;
await useEditorStore(pinia).saveAll();
await flushPromises();
expect(area.find("[data-test=overwrite-prompt]").exists()).toBe(true);
expect(useDiskConflictsStore(pinia).prompts).toHaveLength(1);
});
it("offers Keep as unsaved and Close for a deleted file", async () => {
const area = await mountWithFile();
emitEditorEvent({ kind: "fileChangedOnDisk", id: 1, path: "src/a.php", removed: true });
await flushPromises();
const banner = area.find("[data-test=disk-banner]");
expect(banner.attributes("data-kind")).toBe("removed");
expect(banner.findAll("button").map((b) => b.text())).toEqual(["Keep as unsaved", "Close"]);
await area.find("[data-test=disk-close]").trigger("click");
await flushPromises();
expect(calls.find((c) => c.command === "buffer.close")?.params).toEqual({ id: 1, force: true });
expect(useEditorStore(pinia).tabs).toEqual([]);
});
it("drops the banner when the engine settles the conflict", async () => {
const area = await mountWithFile();
emitEditorEvent({ kind: "fileChangedOnDisk", id: 1, path: "src/a.php", removed: true });
await flushPromises();
await area.find("[data-test=disk-keep]").trigger("click");
emitEditorEvent({ kind: "fileChangedOnDisk", id: 1, path: "src/a.php", removed: false });
await flushPromises();
expect(area.find("[data-test=disk-banner]").attributes("data-kind")).toBe("changed");
emitEditorEvent({ kind: "diskConflictResolved", id: 1 });
await flushPromises();
expect(area.find("[data-test=disk-banner]").exists()).toBe(false);
});
});