/** * 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 }[]; /** 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 = { 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): Promise { 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 }) => { 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(); }); });