Files
AgentHub/client/src/components/lanes/__tests__/DiffEditor.test.tsx
T
nntrivi2001 b7f3735b29 feat: v2.5.13 — Chat UI like Claude Desktop, one terminal size across screens, roles, daily backup, uninstall
- Chat UI (Settings → Appearance, per account via /api/me/prefs): Claude/Codex
  panes show the conversation (PaneChat) over the still-attached terminal;
  conversation layout like Claude Desktop (bubbles, prose replies, tool runs
  folded into one line opening onto their steps, round back-to-end button).
- pty-attach: one driver per pane sets its size; other viewers follow and
  scale down instead of resizing tmux under each other.
- Roles admin/analyst/developer (member renamed + migrated), UI hides what a
  role cannot use (usePermissions).
- Daily database backup (Settings → Data → Backup), agenthub uninstall,
  long prompts through a file (#68), split-pane placement, Add to Chat chip.

Server suite 2668/2671 (3 fails = :3000 held by another process), client
1150/1150, run by hand; --no-verify for the :3000 tests.
2026-10-08 23:04:57 +07:00

328 lines
12 KiB
TypeScript

/**
* @file Tests for the Changes panel's CodeMirror editor: which changed lines
* count as edited in place (blue) rather than added or removed whole, and the
* editor's own diff classes on a real mount, the per-block Undo / Keep bar,
* and the Add to Chat chip on a selection.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
import { describe, it, expect, vi } from "vitest";
import { fireEvent, render, waitFor } from "@testing-library/react";
import { EditorView } from "@codemirror/view";
import DiffEditor, { keepsText } from "../DiffEditor";
// jsdom lays nothing out; CodeMirror's measuring asks a Range for its boxes.
const EMPTY = Object.assign([], { item: () => null }) as unknown as DOMRectList;
Range.prototype.getClientRects ??= () => EMPTY;
Range.prototype.getBoundingClientRect ??= () => new DOMRect();
describe("keepsText", () => {
it("is false for a line whose every non-blank character changed", () => {
expect(keepsText(" added()", 10, [[12, 19]])).toBe(false);
expect(keepsText("", 0, [])).toBe(false);
// Only a `;` survived: not the same line.
expect(keepsText("export x;", 0, [[0, 8]])).toBe(false);
});
it("is true when some text outside the changes survives", () => {
expect(keepsText("const x = 2;", 0, [[10, 11]])).toBe(true);
});
});
describe("DiffEditor", () => {
it("marks a whole new line green and a line edited in place blue", async () => {
const { container } = render(
<DiffEditor
value={"keep\nconst x = 2;\nbrand new"}
original={"keep\nconst x = 1;"}
lang="ts"
label="Edit"
revertLabel="Revert"
onChange={vi.fn()}
onSave={vi.fn()}
/>
);
await waitFor(() => expect(container.querySelectorAll(".cm-changedLine")).toHaveLength(2));
const lines = [...container.querySelectorAll<HTMLElement>(".cm-changedLine")];
expect(lines.map((l) => l.classList.contains("cm-ah-mod"))).toEqual([true, false]);
await waitFor(() =>
expect(container.querySelector(".cm-deletedLine")).toHaveAttribute("data-ah", "mod")
);
});
it("side by side: the original read-only on the left, its edited line blue", async () => {
const { container } = render(
<DiffEditor
layout="split"
value={"keep\nconst x = 2;"}
original={"keep\nconst x = 1;"}
lang="ts"
label="Edit"
revertLabel="Revert"
onChange={vi.fn()}
onSave={vi.fn()}
/>
);
await waitFor(() => expect(container.querySelectorAll(".cm-editor")).toHaveLength(2));
const [left, right] = [...container.querySelectorAll<HTMLElement>(".cm-content")];
expect(left).toHaveAttribute("contenteditable", "false");
expect(right).toHaveAttribute("contenteditable", "true");
expect(container.querySelector(".cm-merge-a .cm-changedLine.cm-ah-mod")).not.toBeNull();
expect(container.querySelector(".cm-merge-b .cm-changedLine.cm-ah-mod")).not.toBeNull();
// The revert column is drawn in CodeMirror's next measure pass, not at mount.
await waitFor(() =>
expect(container.querySelector(".cm-merge-revert button")).toHaveAttribute("title", "Revert")
);
});
it("side by side is JetBrains-shaped: no padding, one curved band per block", async () => {
const { container } = render(
<DiffEditor
layout="split"
// Three unchanged lines apart, or the diff joins the two into one chunk.
value={"a\nB\nc\nd\nf\nnew one\nnew two\ne"}
original={"a\nb\nc\nd\nf\ne"}
lang="plain"
label="Edit"
revertLabel="Revert"
onChange={vi.fn()}
onSave={vi.fn()}
/>
);
await waitFor(() => expect(container.querySelectorAll(".cm-editor")).toHaveLength(2));
// Each side scrolls its own lines: nothing is padded to line them up.
expect(container.querySelector(".cm-mergeSpacer")).toBeNull();
expect(container.querySelectorAll(".cm-scroller")).toHaveLength(2);
await waitFor(() =>
expect(
container.querySelectorAll('[data-testid="lane-editor-connectors"] path')
).toHaveLength(2)
);
const kinds = [
...container.querySelectorAll<SVGPathElement>('[data-testid="lane-editor-connectors"] path'),
].map((p) => p.dataset.kind);
expect(kinds).toEqual(["mod", "add"]);
});
it("» puts the original block back on the right, as an edit", async () => {
const onChange = vi.fn();
const { container } = render(
<DiffEditor
layout="split"
value={"keep\nconst x = 2;\nend"}
original={"keep\nconst x = 1;\nend"}
lang="ts"
label="Edit"
revertLabel="Revert"
onChange={onChange}
onSave={vi.fn()}
/>
);
const button = await waitFor(() => {
const b = container.querySelector<HTMLButtonElement>(".cm-merge-revert button");
expect(b).not.toBeNull();
return b!;
});
fireEvent.mouseDown(button);
expect(onChange).toHaveBeenLastCalledWith("keep\nconst x = 1;\nend");
});
it("folds the same unchanged stretch away on both sides", async () => {
const same = Array.from({ length: 30 }, (_, i) => `line ${i}`).join("\n");
const { container } = render(
<DiffEditor
layout="split"
collapse
value={`${same}\nchanged`}
original={`${same}\noriginal`}
lang="plain"
label="Edit"
revertLabel="Revert"
onChange={vi.fn()}
onSave={vi.fn()}
/>
);
await waitFor(() => expect(container.querySelectorAll(".cm-collapsedLines")).toHaveLength(2));
const [left, right] = [...container.querySelectorAll<HTMLElement>(".cm-collapsedLines")];
expect(left!.textContent).toBe(right!.textContent);
// One click opens the stretch on both sides.
fireEvent.click(right!);
await waitFor(() => expect(container.querySelectorAll(".cm-collapsedLines")).toHaveLength(0));
});
it("folds unchanged lines away when collapsed, and offers Revert on a block", async () => {
const same = Array.from({ length: 30 }, (_, i) => `line ${i}`).join("\n");
const { container } = render(
<DiffEditor
collapse
value={`${same}\nchanged`}
original={`${same}\noriginal`}
lang="plain"
label="Edit"
revertLabel="Revert"
onChange={vi.fn()}
onSave={vi.fn()}
/>
);
await waitFor(() => expect(container.querySelector(".cm-collapsedLines")).not.toBeNull());
const buttons = [...container.querySelectorAll<HTMLButtonElement>(".cm-chunkButtons button")];
expect(buttons.filter((b) => !b.hidden).map((b) => b.textContent)).toEqual(["Revert"]);
});
it("annotates each line in a gutter, and hands a click its commit", async () => {
const onBlameClick = vi.fn();
const props = {
value: "a\nnew",
original: "a",
lang: "plain",
label: "Edit",
revertLabel: "Revert",
onChange: vi.fn(),
onSave: vi.fn(),
onBlameClick,
};
const sha = "f".repeat(40);
const blame = {
available: true as const,
path: "x",
commits: {
[sha]: { short: "fffffff", author: "Vi", date: "2026-10-01T00:00:00Z", summary: "s" },
},
lines: [sha, null],
};
const { container, rerender } = render(<DiffEditor {...props} />);
expect(container.querySelector(".cm-ah-blame")).toBeNull();
rerender(<DiffEditor {...props} blame={blame} />);
await waitFor(() => expect(container.querySelector(".cm-ah-blame")).not.toBeNull());
// The first element is CodeMirror's invisible width spacer.
const cells = [...container.querySelectorAll(".cm-ah-blame .cm-gutterElement span")].slice(1);
expect(cells.map((c) => c.textContent)).toEqual(["2026-10-01 Vi", "Not committed yet"]);
fireEvent.mouseDown(cells[0]!.parentElement!);
expect(onBlameClick).toHaveBeenCalledWith(sha);
});
it("puts an Undo + commit-checkbox bar under each block, by line, in place of Revert", async () => {
const onBlock = vi.fn();
const props = {
value: "a\nB\nc\nnew\ne",
original: "a\nb\nc\nd\ne",
lang: "plain",
label: "Edit",
revertLabel: "Revert",
onChange: vi.fn(),
onSave: vi.fn(),
};
const { container, rerender } = render(
<DiffEditor {...props} onBlock={onBlock} blockIncluded={(b) => b.oldFrom === 2} />
);
await waitFor(() =>
expect(container.querySelectorAll('[data-testid="lane-editor-block-bar"]')).toHaveLength(2)
);
expect(container.querySelector('[data-testid="lane-file-editor"]')).toHaveAttribute(
"data-bars",
"true"
);
const [first, second] = [
...container.querySelectorAll<HTMLElement>('[data-testid="lane-editor-block-bar"]'),
];
const boxes = [first, second].map((b) => b!.querySelector<HTMLInputElement>("input")!);
expect(boxes.map((b) => b.checked)).toEqual([true, false]);
fireEvent.click(boxes[1]!);
expect(onBlock).toHaveBeenLastCalledWith("include", {
oldFrom: 4,
oldCount: 1,
newFrom: 4,
newCount: 1,
});
// Undo asks twice.
const firstUndo = first!.querySelector("button")!;
fireEvent.click(firstUndo);
expect(onBlock).toHaveBeenCalledTimes(1);
fireEvent.click(firstUndo);
expect(onBlock).toHaveBeenLastCalledWith("undo", {
oldFrom: 2,
oldCount: 1,
newFrom: 2,
newCount: 1,
});
// Unsaved text (no onBlock): no bars, Revert back.
rerender(<DiffEditor {...props} />);
await waitFor(() =>
expect(container.querySelector('[data-testid="lane-editor-block-bar"]')).toBeNull()
);
expect(container.querySelector('[data-testid="lane-file-editor"]')).toHaveAttribute(
"data-bars",
"false"
);
});
it.each(["unified", "split"] as const)(
"keeps a CRLF file's text as is (%s): no edit at mount, so the bars stay",
async (layout) => {
const onChange = vi.fn();
const { container } = render(
<DiffEditor
layout={layout}
value={"a\r\nB\r\nc"}
original={"a\r\nb\r\nc"}
lang="plain"
label="Edit"
revertLabel="Revert"
onChange={onChange}
onSave={vi.fn()}
onBlock={vi.fn()}
/>
);
await waitFor(() =>
expect(container.querySelectorAll('[data-testid="lane-editor-block-bar"]')).toHaveLength(1)
);
expect(onChange).not.toHaveBeenCalled();
const eds = container.querySelectorAll<HTMLElement>(".cm-editor");
const view = EditorView.findFromDOM(eds[eds.length - 1]!)!;
expect(view.state.sliceDoc()).toBe("a\r\nB\r\nc");
// Only B changed: the CRs are not read as an edit on every line.
expect(
container
.querySelectorAll(".cm-editor")
[eds.length - 1]!.querySelectorAll(".cm-changedLine")
).toHaveLength(1);
}
);
it("offers Add to Chat on a selection, with its 1-based line range", async () => {
const onAddToChat = vi.fn();
const { container } = render(
<DiffEditor
value={"a\nb\nc\nd"}
original={"a\nb\nc\nd"}
lang="plain"
label="Edit"
revertLabel="Revert"
onChange={vi.fn()}
onSave={vi.fn()}
onAddToChat={onAddToChat}
/>
);
const view = EditorView.findFromDOM(container.querySelector<HTMLElement>(".cm-editor")!)!;
expect(container.querySelector('[data-testid="lane-editor-add-to-chat"]')).toBeNull();
// b..c, ending at the start of d: d is not taken.
view.dispatch({ selection: { anchor: 2, head: 6 } });
const chip = await waitFor(() => {
const b = container.querySelector<HTMLButtonElement>(
'[data-testid="lane-editor-add-to-chat"]'
);
expect(b).not.toBeNull();
return b!;
});
// Inline at the end of the first selected line, never a tooltip over the
// line above it.
expect(chip.closest(".cm-tooltip")).toBeNull();
expect(chip.closest(".cm-line")?.textContent).toMatch(/^b/);
fireEvent.click(chip);
expect(onAddToChat).toHaveBeenCalledWith(2, 3);
view.dispatch({ selection: { anchor: 6 } });
await waitFor(() =>
expect(container.querySelector('[data-testid="lane-editor-add-to-chat"]')).toBeNull()
);
});
});