Skip to content

Open-source, local-first AI agent for real work.

9.9 KB
Raw Blame
import { execFileSync } from "node:child_process";
import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { PluginCommandApi } from "@vetta-org/plugin-sdk";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { setGitCommand, setStorageApi } from "../src/git/runtime";
import {
	addReviewComment,
	applyTurnFiles,
	flushTurnReviewSaves,
	getTurnReview,
	handleConversationEvent,
	hydrateTurnReviews,
	resetTurnReviews,
	setReviewNote,
} from "../src/git/turnReview";
import { parseNumstatZ, snapshotFileDiff } from "../src/git/turnSnapshot";

const PREFIX = join(tmpdir(), "vetta-git-turn-");
let root: string;
/** Plugin storage kept in memory; it outlives `resetTurnReviews`, as the disk outlives a restart. */
const storageFiles = new Map<string, string>();

const git = (...args: string[]): string =>
	execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
const write = (path: string, content: string): void => writeFileSync(join(root, path), content);
const read = (path: string): string => readFileSync(join(root, path), "utf8");

/** Runs real git inside the fixture repository, honouring `env` like the host does. */
function fixtureCommand(): PluginCommandApi {
	return {
		appIcon: async () => null,
		spawn: async () => {
			throw new Error("not used");
		},
		run: async (_file, args = [], options) => {
			if (options?.cwd !== root) throw new Error("Fixture command escaped temporary repository");
			try {
				const stdout = execFileSync("git", args, {
					cwd: root,
					encoding: "utf8",
					env: { ...process.env, ...options.env },
					stdio: ["ignore", "pipe", "pipe"],
				});
				return { exitCode: 0, stdout, stderr: "" };
			} catch (error) {
				const failed = error as { status?: number; stdout?: string; stderr?: string };
				return { exitCode: failed.status ?? 1, stdout: failed.stdout ?? "", stderr: failed.stderr ?? "" };
			}
		},
	};
}

async function startTurn(): Promise<void> {
	await handleConversationEvent({ type: "turn-start" });
}

async function endTurn(): Promise<void> {
	await handleConversationEvent({ type: "turn-end", stopReason: "stop" });
}

beforeEach(async () => {
	root = realpathSync(mkdtempSync(PREFIX));
	git("init", "-b", "main");
	git("config", "user.name", "Fixture");
	git("config", "user.email", "[email protected]");
	git("config", "core.hooksPath", join(root, "no-hooks"));
	git("config", "commit.gpgsign", "false");
	git("config", "core.autocrlf", "false");
	write("app.ts", "one\ntwo\nthree\n");
	write("old-name.ts", "keep me\n");
	write("gone.ts", "bye\n");
	git("add", "--", "app.ts", "old-name.ts", "gone.ts");
	git("commit", "-m", "initial");
	setGitCommand(fixtureCommand());
	storageFiles.clear();
	setStorageApi({
		readFile: async (path: string) => storageFiles.get(path) ?? null,
		writeFile: async (path: string, data: string) => {
			storageFiles.set(path, data);
			return { revision: "1", changedPaths: [path] };
		},
	} as never);
	resetTurnReviews();
	await handleConversationEvent({
		type: "conversation-changed",
		conversation: { id: "s1", cwd: root, sessionPath: null, model: null, isStreaming: false },
	});
});

afterEach(() => {
	resetTurnReviews();
	if (root.startsWith(realpathSync(tmpdir()))) rmSync(root, { recursive: true, force: true });
});

describe("turn review over real snapshots", () => {
	it("lists what the turn changed even in files that were already modified", async () => {
		// The user had unfinished work in app.ts before asking the agent anything.
		write("app.ts", "one\nTWO (user)\nthree\n");
		await startTurn();
		write("app.ts", "one\nTWO (user)\nthree\nfour (agent)\n");
		await endTurn();

		const review = getTurnReview(root);
		expect(review?.files).toEqual([
			expect.objectContaining({ path: "app.ts", code: "M", additions: 1, deletions: 0 }),
		]);
		// The diff is the turn's own edit, not the user's earlier one.
		const patch = await snapshotFileDiff(root, review!.before, review!.after, review!.files[0]!);
		expect(patch).toContain("+four (agent)");
		expect(patch).not.toContain("+TWO (user)");
	});

	it("reverts a whole turn and restores it again without touching the index", async () => {
		write("staged-by-user.ts", "mine\n");
		git("add", "--", "staged-by-user.ts");
		await startTurn();
		write("app.ts", "one\nchanged\nthree\n");
		git("mv", "old-name.ts", "new-name.ts");
		rmSync(join(root, "gone.ts"));
		write("fresh.ts", "brand new\n");
		await endTurn();

		const review = getTurnReview(root)!;
		const listed = review.files.map((file) => `${file.code} ${file.origPath ? `${file.origPath} -> ` : ""}${file.path}`);
		expect(listed.sort()).toEqual(["A fresh.ts", "D gone.ts", "M app.ts", "R old-name.ts -> new-name.ts"]);
		const indexBefore = git("diff", "--cached", "--name-status");

		const all = review.files.map((file) => file.path);
		expect(await applyTurnFiles(root, all, "revert")).toEqual({ status: "done" });
		expect(read("app.ts")).toBe("one\ntwo\nthree\n");
		expect(read("gone.ts")).toBe("bye\n");
		expect(read("old-name.ts")).toBe("keep me\n");
		expect(existsSync(join(root, "new-name.ts"))).toBe(false);
		expect(existsSync(join(root, "fresh.ts"))).toBe(false);
		// Work the user staged before the turn is untouched, and so is the index.
		expect(read("staged-by-user.ts")).toBe("mine\n");
		expect(git("diff", "--cached", "--name-status")).toBe(indexBefore);
		expect(getTurnReview(root)?.reverted.size).toBe(4);

		expect(await applyTurnFiles(root, all, "restore")).toEqual({ status: "done" });
		expect(read("app.ts")).toBe("one\nchanged\nthree\n");
		expect(read("fresh.ts")).toBe("brand new\n");
		expect(read("new-name.ts")).toBe("keep me\n");
		expect(existsSync(join(root, "gone.ts"))).toBe(false);
		expect(getTurnReview(root)?.reverted.size).toBe(0);
	});

	it("refuses to overwrite edits made after the turn unless forced", async () => {
		await startTurn();
		write("app.ts", "agent\n");
		await endTurn();
		write("app.ts", "user fixed it afterwards\n");

		expect(await applyTurnFiles(root, ["app.ts"], "revert")).toEqual({ status: "conflict", paths: ["app.ts"] });
		expect(read("app.ts")).toBe("user fixed it afterwards\n");

		expect(await applyTurnFiles(root, ["app.ts"], "revert", true)).toEqual({ status: "done" });
		expect(read("app.ts")).toBe("one\ntwo\nthree\n");
	});

	it("shows nothing for a turn that changed no files, and hides the card while a turn runs", async () => {
		await startTurn();
		write("app.ts", "edited\n");
		await endTurn();
		expect(getTurnReview(root)).not.toBeNull();

		await startTurn();
		expect(getTurnReview(root)).toBeNull();
		await endTurn();
		expect(getTurnReview(root)).toBeNull();
	});

	it("never leaves the snapshot in git's own index", async () => {
		await startTurn();
		write("untracked.ts", "x\n");
		await endTurn();
		expect(getTurnReview(root)?.files.map((file) => file.path)).toEqual(["untracked.ts"]);
		expect(git("status", "--porcelain")).toBe("?? untracked.ts");
	});
});

describe("turn review across an app restart", () => {
	/** Forget everything in memory, as quitting the app does, and read the saved state back. */
	async function restart(): Promise<void> {
		await flushTurnReviewSaves();
		resetTurnReviews();
		await hydrateTurnReviews();
	}

	it("brings back the files, what was put back and the unsent comments", async () => {
		await startTurn();
		write("app.ts", "one\nchanged\nthree\n");
		write("fresh.ts", "brand new\n");
		await endTurn();
		expect(await applyTurnFiles(root, ["fresh.ts"], "revert")).toEqual({ status: "done" });
		addReviewComment(root, { path: "app.ts", side: "additions", start: 2, end: 2, body: "why?", excerpt: ["changed"] });
		setReviewNote(root, "overall");

		await restart();

		const review = getTurnReview(root);
		expect(review?.files.map((file) => file.path).sort()).toEqual(["app.ts", "fresh.ts"]);
		expect([...review!.reverted]).toEqual(["fresh.ts"]);
		expect(review?.comments).toEqual([expect.objectContaining({ id: "c1", body: "why?" })]);
		expect(review?.note).toBe("overall");
		// The restored review still drives the worktree: put the reverted file forward again.
		expect(await applyTurnFiles(root, ["fresh.ts"], "restore")).toEqual({ status: "done" });
		expect(read("fresh.ts")).toBe("brand new\n");
		// Ids keep counting past the saved ones, so removing one never removes another.
		addReviewComment(root, { path: "app.ts", side: "additions", start: 1, end: 1, body: "more", excerpt: ["one"] });
		expect(getTurnReview(root)?.comments.map((comment) => comment.id)).toEqual(["c1", "c2"]);
	});

	it("does not bring back a review the next turn already replaced", async () => {
		await startTurn();
		write("app.ts", "edited\n");
		await endTurn();
		await flushTurnReviewSaves();
		resetTurnReviews();
		await handleConversationEvent({
			type: "conversation-changed",
			conversation: { id: "s1", cwd: root, sessionPath: null, model: null, isStreaming: false },
		});
		// A turn starts before the saved state has been read back.
		await startTurn();
		await hydrateTurnReviews();
		expect(getTurnReview(root)).toBeNull();
	});

	it("drops a saved review whose snapshots git no longer has", async () => {
		await startTurn();
		write("app.ts", "edited\n");
		await endTurn();
		await flushTurnReviewSaves();
		const saved = storageFiles.get("turn-reviews.json")!;
		const missing = "0".repeat(40);
		storageFiles.set("turn-reviews.json", saved.replaceAll(getTurnReview(root)!.before, missing));

		resetTurnReviews();
		await hydrateTurnReviews();
		expect(getTurnReview(root)).toBeNull();
	});
});

describe("parseNumstatZ", () => {
	it("reads plain rows, renames and binary files", () => {
		const raw = "2\t1\tsrc/a.ts\0" + "0\t0\t\0old.ts\0new.ts\0" + "-\t-\timg.png\0";
		expect([...parseNumstatZ(raw)]).toEqual([
			["src/a.ts", { additions: 2, deletions: 1, binary: false }],
			["new.ts", { additions: 0, deletions: 0, binary: false }],
			["img.png", { additions: 0, deletions: 0, binary: true }],
		]);
	});
});