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>
This commit is contained in:
danny 2026-11-08 12:23:14 +01:00
parent dfe2f19ca5
commit d2344bf216
29 changed files with 1999 additions and 52 deletions

View file

@ -4,7 +4,7 @@
* `buffer.edit`, the dirty marker, closing (middle click, shortcut, the
* Save / Don't Save / Cancel question), saving through the global keymap
* (`commands/store.ts`) with shortcuts loaded from the engine's command
* list, the notice for files changed on disk, and the UI command
* list, the banner for files changed on disk, and the UI command
* `editor.reveal` (open and closed files, CRLF text, bad params).
* The engine is a fake behind the mocked Tauri `invoke`.
*/
@ -482,16 +482,16 @@ describe("EditorArea", () => {
expect(editor.activeId).toBe(1);
});
it("shows a notice when a dirty file changes on disk, and an open error", async () => {
it("shows the disk banner when a dirty file changes on disk, and an open error", async () => {
const area = await mountArea();
const editor = useEditorStore(pinia);
await editor.openFile("a.php");
await flushPromises();
emitEditorEvent({ kind: "fileChangedOnDisk", id: 1, path: "a.php", removed: false });
await flushPromises();
expect(area.find("[data-test=editor-notice]").text()).toContain("changed on disk");
await area.find("[data-test=notice-dismiss]").trigger("click");
expect(area.find("[data-test=editor-notice]").exists()).toBe(false);
expect(area.find("[data-test=disk-banner]").text()).toContain("changed by another program");
await area.find("[data-test=disk-keep]").trigger("click");
expect(area.find("[data-test=disk-banner]").exists()).toBe(false);
await editor.openFile("missing.php");
await flushPromises();

View file

@ -0,0 +1,225 @@
/**
* 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);
});
});

View file

@ -0,0 +1,220 @@
/**
* Tests for the Local History dialog (C10 A2): `history.show` from the
* palette (active tab) and with a path, the list with time and reason,
* keyboard selection, Show Diff (a diff tab of the entry against the
* buffer), Revert to This (`history.revert`, undoable in the editor), the
* empty and failed states, and the checks of untrusted input. The engine
* is a fake behind the mocked Tauri `invoke`.
*/
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
import { EditorView } from "@codemirror/view";
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 LocalHistoryDialog from "../../src/components/history/LocalHistoryDialog.vue";
import { parseShowParams, toEntries, useLocalHistoryStore } from "../../src/components/history/localHistory";
import { useDiffStore } from "../../src/components/vcs/diff/diff";
import { useEditorStore } from "../../src/stores/editor";
/** Every `engine_execute` call, in order. */
let calls: { command: string; params: Record<string, unknown> }[];
/** The fake buffer. */
let buffer: { text: string; version: number };
/** Entries `history.list` returns. */
let listed: unknown;
/** Pinia of the current test. */
let pinia: Pinia;
/** Mounted components. */
let mounted: VueWrapper[] = [];
/** Snapshot texts by id. */
const TEXTS: Record<number, string> = { 2: "second", 1: "first" };
/** 2026-11-08 10:15 and 09:00 local time. */
const T2 = new Date(2026, 10, 8, 10, 15).getTime();
const T1 = new Date(2026, 10, 8, 9, 0).getTime();
/**
* The fake engine.
*
* @param command - command id.
* @param p - params.
*/
function execute(command: string, p: Record<string, unknown>): Promise<unknown> {
const describe = { id: 1, path: "src/a.php", text: buffer.text, version: buffer.version, dirty: false, lineEnding: "lf" };
switch (command) {
case "file.open":
case "buffer.get":
return Promise.resolve(describe);
case "buffer.edit": {
let out = "";
let pos = 0;
for (const e of p.edits as { from: number; to: number; insert: string }[]) {
out += buffer.text.slice(pos, e.from) + e.insert;
pos = e.to;
}
buffer.text = out + buffer.text.slice(pos);
buffer.version += 1;
return Promise.resolve({ id: 1, version: buffer.version, dirty: true });
}
case "history.list":
return Promise.resolve(listed);
case "history.read":
return Promise.resolve({ text: TEXTS[Number(p.id)] ?? "", binary: false, tooLarge: false });
case "history.revert":
buffer.text = TEXTS[Number(p.id)] ?? "";
buffer.version += 1;
emitEditorEvent({ kind: "bufferChanged", id: 1, version: buffer.version });
return Promise.resolve({ id: 1, version: buffer.version, dirty: true });
default:
return Promise.resolve(null);
}
}
/** Mounts the editor area (with `src/a.php` open) and the dialog. */
async function mountAll(): Promise<{ area: VueWrapper; dialog: VueWrapper }> {
await useCommandsStore(pinia).start();
const area = mount(EditorArea, { attachTo: document.body, global: { plugins: [pinia] } });
const dialog = mount(LocalHistoryDialog, { attachTo: document.body, global: { plugins: [pinia] } });
mounted.push(area, dialog);
await useEditorStore(pinia).openFile("src/a.php");
await flushPromises();
return { area, dialog };
}
beforeEach(() => {
pinia = createPinia();
setActivePinia(pinia);
calls = [];
buffer = { text: "current", version: 1 };
listed = {
path: "src/a.php",
entries: [
{ id: 2, time: T2, reason: "save", size: 6 },
{ id: 1, time: T1, reason: "externalChange", size: 2048 },
],
};
invoke.mockReset();
invoke.mockImplementation((cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
if (cmd === "engine_list_commands") {
return Promise.resolve([
{ id: "history.list", label: "List", menuPath: null, defaultShortcut: null, params: "", enabled: true },
]);
}
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("Local History dialog", () => {
it("lists the active tab's entries with time, reason and size", async () => {
const { dialog } = await mountAll();
await useCommandsStore(pinia).execute("history.show", {});
await flushPromises();
expect(calls.find((c) => c.command === "history.list")?.params).toEqual({ path: "src/a.php" });
expect(dialog.find("#lt-history-title").text()).toBe("Local History of a.php");
const rows = dialog.findAll("[data-test=history-row]");
expect(rows.map((r) => r.text())).toEqual([
"2026-11-08 10:15Saved6 B",
"2026-11-08 09:00Changed by another program2 KiB",
]);
expect(document.activeElement?.getAttribute("data-test")).toBe("history-list");
await dialog.find("[data-test=history-list]").trigger("keydown", { key: "ArrowDown" });
expect(useLocalHistoryStore(pinia).current?.id).toBe(1);
});
it("opens an entry against the buffer in a diff tab", async () => {
const { dialog } = await mountAll();
await useCommandsStore(pinia).execute("history.show", { path: "src/a.php" });
await flushPromises();
await dialog.find("[data-test=history-list]").trigger("keydown", { key: "Enter" });
await flushPromises();
expect(dialog.find("[data-test=local-history]").exists()).toBe(false);
const diff = useDiffStore(pinia);
expect(diff.activeTab?.key).toBe("history:2:src/a.php");
expect(diff.activeContent?.left).toBe("second");
expect(calls.find((c) => c.command === "history.read")?.params).toEqual({ path: "src/a.php", id: 2 });
});
it("reverts through the engine, undoably in the editor", async () => {
const { area, dialog } = await mountAll();
await useCommandsStore(pinia).execute("history.show", {});
await flushPromises();
await dialog.findAll("[data-test=history-row]")[1]?.trigger("click");
await dialog.find("[data-test=history-revert]").trigger("click");
await flushPromises();
expect(calls.find((c) => c.command === "history.revert")?.params).toEqual({ path: "src/a.php", id: 1 });
expect(dialog.find("[data-test=local-history]").exists()).toBe(false);
const view = EditorView.findFromDOM(area.find(".cm-editor").element as HTMLElement);
expect(view?.state.doc.toString()).toBe("first");
view?.contentDOM.dispatchEvent(new KeyboardEvent("keydown", { key: "z", ctrlKey: true, bubbles: true, cancelable: true }));
await flushPromises();
expect(view?.state.doc.toString()).toBe("current");
});
it("says when there are no entries or the list failed", async () => {
const { dialog } = await mountAll();
listed = { path: "src/a.php", entries: [] };
await useLocalHistoryStore(pinia).show("src/a.php");
await flushPromises();
expect(dialog.find("[data-test=history-hint]").text()).toContain("No Local History");
expect(dialog.find("[data-test=history-diff]").attributes("disabled")).toBeDefined();
listed = { nope: true };
await useLocalHistoryStore(pinia).show("src/a.php");
await flushPromises();
expect(dialog.find("[data-test=history-error]").text()).toContain("history.list");
await dialog.find("[data-test=history-cancel]").trigger("click");
expect(dialog.find("[data-test=local-history]").exists()).toBe(false);
});
it("refuses bad params and runs without a file", async () => {
await mountAll();
const history = useLocalHistoryStore(pinia);
await expect(history.showCommand({ path: 3 })).rejects.toThrow("Show Local History takes");
useEditorStore(pinia).activeId = null;
await expect(history.showCommand({})).rejects.toThrow("Open or select a file");
});
});
describe("untrusted input", () => {
it("checks list entries field by field", () => {
expect(toEntries(null)).toBeNull();
expect(toEntries({ entries: "x" })).toBeNull();
expect(
toEntries({
entries: [
{ id: 1, time: 2, reason: "save", size: 3 },
{ id: "1", time: 2, reason: "save", size: 3 },
{ id: 2, time: 2, reason: "unknown", size: 3 },
null,
],
}),
).toEqual([{ id: 1, time: 2, reason: "save", size: 3 }]);
});
it("reads the params of history.show", () => {
expect(parseShowParams(null)).toBe("");
expect(parseShowParams({})).toBe("");
expect(parseShowParams({ path: "a.php" })).toBe("a.php");
expect(parseShowParams({ path: "" })).toBeNull();
expect(parseShowParams([])).toBeNull();
});
});

View file

@ -178,7 +178,7 @@ describe("en.json", () => {
it("uses flat dotted keys of known areas with string values", () => {
for (const [key, value] of Object.entries(en)) {
expect(key).toMatch(
/^(app|command|project|editor|common|palette|theme|recovery|notification|settings|find|goto|structure|menu|terminal|problems|nav|vcs|deploy)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/,
/^(app|command|project|editor|common|palette|theme|recovery|notification|settings|find|goto|structure|menu|terminal|problems|nav|vcs|deploy|history)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/,
);
expect(typeof value).toBe("string");
expect(value.trim()).not.toBe("");

View file

@ -272,6 +272,7 @@ describe("AppMenu", () => {
"project.openDialog",
"file.save",
"file.saveAll",
"history.show",
"buffer.close",
"project.close",
"app.quit",

View file

@ -475,7 +475,7 @@ describe("project tree context menu", () => {
await tree.find("[data-path='a.php']").trigger("contextmenu", { clientX: 40, clientY: 50 });
const menu = document.querySelector("[data-test=tree-menu]");
expect(menu).not.toBeNull();
expect([...document.querySelectorAll("[data-test=tree-menu-item]")].map((item) => item.textContent.trim())).toEqual(["Open", "Show Diff", "Show History", "Upload to Server", "Compare with Server", "Download from Server"]);
expect([...document.querySelectorAll("[data-test=tree-menu-item]")].map((item) => item.textContent.trim())).toEqual(["Open", "Show Diff", "Show History", "Show Local History", "Upload to Server", "Compare with Server", "Download from Server"]);
(document.querySelector("[data-item=showDiff]") as HTMLElement).click();
await flushPromises();
await flushPromises();