repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/pulse/__tests__/index.test.ts

Raw
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { afterEach, describe, expect, it } from "vitest";

let completionText = '{"updates":[]}';
let completionTexts: string[] = [];
let completionCalls = 0;
let completionOptions: Record<string, unknown> | undefined;

const {
	default: pulse,
	parsePulseArgs,
	pulseArgumentCompletions,
	quotePulseArg,
	__setPulseModelClient,
} = await import("../index.ts");

__setPulseModelClient({
	complete: (async (_model: unknown, _context: unknown, options: unknown) => {
		completionCalls++;
		completionOptions = options as Record<string, unknown>;
		return {
			content: [
				{ type: "text", text: completionTexts.shift() ?? completionText },
			],
		};
	}) as never,
	getModel: ((provider: string, id: string) => ({ provider, id })) as never,
});

let tmp = "";
const supportsControlCharPaths = process.platform !== "win32";

const oldAgentDir = process.env.PI_CODING_AGENT_DIR;

function cwd(): string {
	tmp = fs.mkdtempSync(path.join(os.tmpdir(), "pulse-index-"));
	process.env.PI_CODING_AGENT_DIR = path.join(tmp, "agent");
	return tmp;
}

function write(root: string, rel: string, text = rel): void {
	const p = path.join(root, rel);
	fs.mkdirSync(path.dirname(p), { recursive: true });
	fs.writeFileSync(p, text);
}

function writeConfig(root: string, config: unknown): void {
	write(root, ".pi/settings.json", JSON.stringify({ pulse: config }, null, 2));
}

function readConfig(root: string): any {
	return JSON.parse(
		fs.readFileSync(path.join(root, ".pi/settings.json"), "utf8"),
	).pulse;
}

function writeGlobalConfig(root: string, config: unknown): void {
	write(
		path.join(root, "agent"),
		"settings.json",
		JSON.stringify({ pulse: config }, null, 2),
	);
}

function harness(root: string) {
	const commands = new Map<string, any>();
	const events = new Map<string, any>();
	const notifications: Array<{ message: string; level: string }> = [];
	const statuses: Array<{ key: string; value: string | undefined }> = [];
	const confirmations: string[] = [];
	const editors: Array<{ title: string; prefill: string }> = [];
	const autocompleteFactories: any[] = [];
	const entries: any[] = [];
	let confirmResult = true;
	let editorResult: string | undefined;
	const ctx: any = {
		cwd: root,
		model: { provider: "test", id: "model" },
		ui: {
			notify(message: string, level: string) {
				notifications.push({ message, level });
			},
			setStatus(key: string, value: string | undefined) {
				statuses.push({ key, value });
			},
			async confirm(title: string, message: string) {
				confirmations.push(`${title}\n${message}`);
				return confirmResult;
			},
			async editor(title: string, prefill: string) {
				editors.push({ title, prefill });
				return editorResult;
			},
			addAutocompleteProvider(factory: any) {
				autocompleteFactories.push(factory);
			},
		},
		modelRegistry: {
			async getApiKeyAndHeaders() {
				return { ok: true, apiKey: "test-key" };
			},
		},
		sessionManager: {
			getBranch() {
				return entries;
			},
			appendCustomEntry(customType: string, data: unknown) {
				entries.push({ type: "custom", customType, data });
				return String(entries.length);
			},
		},
		isIdle() {
			return true;
		},
	};
	const pi: any = {
		_cwd: root,
		registerCommand(name: string, command: unknown) {
			commands.set(name, command);
		},
		on(name: string, handler: unknown) {
			events.set(name, handler);
		},
		appendEntry(customType: string, data: unknown) {
			entries.push({ type: "custom", customType, data });
		},
	};
	pulse(pi);
	return {
		commands,
		events,
		ctx,
		pi,
		notifications,
		statuses,
		confirmations,
		editors,
		autocompleteFactories,
		entries,
		setConfirmResult(value: boolean) {
			confirmResult = value;
		},
		setEditorResult(value: string | undefined) {
			editorResult = value;
		},
	};
}

afterEach(() => {
	completionText = '{"updates":[]}';
	completionTexts = [];
	completionCalls = 0;
	completionOptions = undefined;
	__setPulseModelClient({
		complete: (async (_model: unknown, _context: unknown, options: unknown) => {
			completionCalls++;
			completionOptions = options as Record<string, unknown>;
			return {
				content: [
					{ type: "text", text: completionTexts.shift() ?? completionText },
				],
			};
		}) as never,
		getModel: ((provider: string, id: string) => ({ provider, id })) as never,
	});
	if (oldAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
	else process.env.PI_CODING_AGENT_DIR = oldAgentDir;
	if (tmp) fs.rmSync(tmp, { recursive: true, force: true });
	tmp = "";
});

describe("pulse argument parsing", () => {
	it("supports quoted paths with spaces", () => {
		expect(parsePulseArgs('add "my file.md" keep concise')).toEqual([
			"add",
			"my file.md",
			"keep",
			"concise",
		]);
		expect(quotePulseArg("my file.md")).toBe('"my file.md"');
	});
});

describe("pulse command UX", () => {
	it("adds and removes quoted paths with spaces", async () => {
		const root = cwd();
		write(root, "my file.md", "doc");
		writeConfig(root, { documents: [] });
		const h = harness(root);

		expect(
			h.commands.get("pulse").getArgumentCompletions("add my"),
		).toContainEqual({ value: 'add "my file.md"', label: "my file.md" });

		await h.commands
			.get("pulse")
			.handler('add "my file.md" keep concise', h.ctx);
		expect(readConfig(root).documents).toEqual([
			{ path: "my file.md", instruction: "keep concise" },
		]);

		await h.commands.get("pulse").handler('remove "my file.md"', h.ctx);
		expect(readConfig(root).documents).toEqual([]);
	});

	it("completes pulse args when explicit tab forces file completion", async () => {
		const root = cwd();
		writeConfig(root, { documents: [{ path: "README.md" }] });
		const h = harness(root);

		await h.events.get("session_start")({}, h.ctx);
		const provider = h.autocompleteFactories[0]({
			async getSuggestions() {
				return null;
			},
			applyCompletion() {
				throw new Error("unused");
			},
			shouldTriggerFileCompletion() {
				return false;
			},
		});
		const line = "/pulse remove ";

		expect(provider.shouldTriggerFileCompletion([line], 0, line.length)).toBe(
			true,
		);
		await expect(
			provider.getSuggestions([line], 0, line.length, {
				signal: new AbortController().signal,
				force: true,
			}),
		).resolves.toEqual({
			items: [{ value: "remove README.md", label: "README.md" }],
			prefix: "remove ",
		});
	});

	it("completes pulse arguments directly", () => {
		const root = cwd();
		writeConfig(root, { documents: [{ path: "README.md" }] });

		expect(pulseArgumentCompletions("remove ", root)).toEqual([
			{ value: "remove README.md", label: "README.md" },
		]);
	});

	it("rejects the removed config subcommand", async () => {
		const root = cwd();
		const h = harness(root);

		expect(h.commands.get("pulse").getArgumentCompletions("con") ?? []).toEqual(
			[],
		);
		await h.commands.get("pulse").handler("config", h.ctx);

		expect(h.notifications).toContainEqual({
			message: "Pulse: unknown command config",
			level: "warning",
		});
	});

	it("reports invalid settings instead of silently dropping docs", async () => {
		const root = cwd();
		writeConfig(root, { documents: [{ path: "README.md", model: "bad" }] });
		const h = harness(root);

		await h.commands.get("pulse").handler("status", h.ctx);

		expect(h.notifications).toContainEqual({
			message: "Pulse: invalid config: documents[0].model must be provider/id",
			level: "warning",
		});
	});

	it("merges global and project pulse settings", async () => {
		const root = cwd();
		write(root, "README.md", "doc");
		writeGlobalConfig(root, { model: "global/model", interval: 0 });
		writeConfig(root, { documents: [{ path: "README.md" }] });
		const h = harness(root);

		await h.commands.get("pulse").handler("status", h.ctx);

		expect(
			h.notifications.some((n) => n.message.includes("model: global/model")),
		).toBe(true);
		expect(
			h.notifications.some((n) => n.message.includes("periodic: off")),
		).toBe(true);
	});

	it("ignores legacy .pi/pulse.json", async () => {
		const root = cwd();
		write(root, "README.md", "doc");
		write(
			root,
			".pi/pulse.json",
			JSON.stringify({ documents: [{ path: "README.md" }] }),
		);
		const h = harness(root);

		await h.commands.get("pulse").handler("status", h.ctx);

		expect(h.notifications).toContainEqual({
			message: "Pulse: not initialized",
			level: "info",
		});
	});

	it("reports missing auth instead of saying nothing to update", async () => {
		const root = cwd();
		write(root, "README.md", "doc");
		writeConfig(root, { documents: [{ path: "README.md" }] });
		const h = harness(root);
		h.ctx.modelRegistry.getApiKeyAndHeaders = async () => ({ ok: false });
		await h.commands.get("pulse").handler("force", h.ctx);

		expect(
			h.notifications.some(
				(n) => n.message.includes("missing auth") && n.level === "warning",
			),
		).toBe(true);
		expect(
			h.notifications.some((n) => n.message.includes("nothing to update")),
		).toBe(false);
	});

	it("accepts header-only model auth", async () => {
		const root = cwd();
		write(root, "README.md", "doc");
		writeConfig(root, { documents: [{ path: "README.md" }] });
		const h = harness(root);
		h.ctx.modelRegistry.getApiKeyAndHeaders = async () => ({
			ok: true,
			headers: { authorization: "Bearer TOKEN" },
		});

		await h.commands.get("pulse").handler("force", h.ctx);

		expect(completionCalls).toBe(1);
		expect(completionOptions).toMatchObject({
			headers: { authorization: "Bearer TOKEN" },
		});
		expect(
			h.notifications.some((n) => n.message.includes("missing auth")),
		).toBe(false);
	});

	it("does not expose terminal controls in completions", () => {
		const root = cwd();
		if (supportsControlCharPaths) write(root, "bad\u001b[31m.md", "doc");
		writeConfig(root, { documents: [{ path: "bad\u001b[31m.md" }] });
		const h = harness(root);

		if (supportsControlCharPaths) {
			const add = h.commands.get("pulse").getArgumentCompletions("add ") ?? [];
			expect(
				add.some((item: any) => String(item.value).includes("\u001b")),
			).toBe(false);
			expect(
				add.some((item: any) => String(item.label).includes("\u001b")),
			).toBe(false);
		}

		const remove =
			h.commands.get("pulse").getArgumentCompletions("remove bad") ?? [];
		expect(
			remove.some((item: any) => String(item.value).includes("\u001b")),
		).toBe(false);
		expect(
			remove.some((item: any) => String(item.label).includes("\u001b")),
		).toBe(false);
	});
});

describe("pulse updater", () => {
	it("applies valid model proposals without injecting the main system prompt", async () => {
		const root = cwd();
		write(root, "README.md", "old");
		writeConfig(root, { documents: [{ path: "README.md" }] });
		completionText = JSON.stringify({
			updates: [{ path: "README.md", content: "new", summary: "refreshed" }],
		});
		const h = harness(root);

		await h.commands.get("pulse").handler("force", h.ctx);

		expect(fs.readFileSync(path.join(root, "README.md"), "utf8")).toBe("new");
		expect(h.events.has("before_agent_start")).toBe(false);
		expect(
			h.notifications.some((n) => n.message.includes("updated 1 doc")),
		).toBe(true);
	});

	it("reports an info no-op when the file already matches the proposal", async () => {
		const root = cwd();
		write(root, "README.md", "old");
		writeConfig(root, { documents: [{ path: "README.md" }] });
		__setPulseModelClient({
			complete: (async () => {
				fs.writeFileSync(path.join(root, "README.md"), "new", "utf8");
				return {
					content: [
						{
							type: "text",
							text: JSON.stringify({
								updates: [
									{
										path: "README.md",
										content: "new",
										summary: "already current",
									},
								],
							}),
						},
					],
				};
			}) as never,
			getModel: ((provider: string, id: string) => ({ provider, id })) as never,
		});
		const h = harness(root);

		await h.commands.get("pulse").handler("force", h.ctx);

		expect(fs.readFileSync(path.join(root, "README.md"), "utf8")).toBe("new");
		expect(h.notifications).toContainEqual({
			message: "Pulse: already current: README.md",
			level: "info",
		});
		expect(
			h.notifications.some((n) => n.message.includes("changed while updating")),
		).toBe(false);
	});

	it("persists run state through the fresh command context, not captured pi", async () => {
		const root = cwd();
		write(root, "README.md", "old");
		writeConfig(root, { documents: [{ path: "README.md" }] });
		completionText = JSON.stringify({ updates: [] });
		const h = harness(root);
		h.pi.appendEntry = () => {
			throw new Error("stale pi appendEntry");
		};

		await h.commands.get("pulse").handler("force", h.ctx);

		expect(h.entries.at(-1)).toEqual({
			type: "custom",
			customType: "pulse-state",
			data: {
				version: 1,
				lastRunAt: expect.any(Number),
				lastRunReason: "manual",
				lastResult: "up to date",
			},
		});
	});

	it("rejects model proposals for untracked paths", async () => {
		const root = cwd();
		write(root, "README.md", "old");
		write(root, ".env", "secret");
		writeConfig(root, { documents: [{ path: "README.md" }] });
		completionText = JSON.stringify({
			updates: [{ path: ".env", content: "stolen", summary: "bad" }],
		});
		const h = harness(root);

		await h.commands.get("pulse").handler("force", h.ctx);

		expect(fs.readFileSync(path.join(root, ".env"), "utf8")).toBe("secret");
		expect(
			h.notifications.some(
				(n) =>
					n.message.includes("invalid update proposal") &&
					n.level === "warning",
			),
		).toBe(true);
	});

	it("retries invalid JSON before aborting", async () => {
		const root = cwd();
		write(root, "README.md", "old");
		writeConfig(root, { documents: [{ path: "README.md" }] });
		completionTexts = [
			"not json",
			JSON.stringify({
				updates: [{ path: "README.md", content: "new", summary: "fixed json" }],
			}),
		];
		const h = harness(root);

		await h.commands.get("pulse").handler("force", h.ctx);

		expect(completionCalls).toBe(2);
		expect(fs.readFileSync(path.join(root, "README.md"), "utf8")).toBe("new");
	});

	it("supports confirm apply mode", async () => {
		const root = cwd();
		write(root, "README.md", "old");
		writeConfig(root, { apply: "confirm", documents: [{ path: "README.md" }] });
		completionText = JSON.stringify({
			updates: [{ path: "README.md", content: "new", summary: "needs review" }],
		});
		const h = harness(root);
		h.setConfirmResult(false);

		await h.commands.get("pulse").handler("force", h.ctx);

		expect(fs.readFileSync(path.join(root, "README.md"), "utf8")).toBe("old");
		expect(h.confirmations[0]).toContain("Apply 1 doc update");
		expect(h.notifications.some((n) => n.message === "Pulse: skipped")).toBe(
			true,
		);
	});

	it("supports review apply mode", async () => {
		const root = cwd();
		write(root, "README.md", "old");
		writeConfig(root, { apply: "review", documents: [{ path: "README.md" }] });
		completionText = JSON.stringify({
			updates: [{ path: "README.md", content: "new", summary: "reviewed" }],
		});
		const h = harness(root);
		h.setEditorResult("reviewed content");

		await h.commands.get("pulse").handler("force", h.ctx);

		expect(h.editors).toEqual([{ title: "Pulse: README.md", prefill: "new" }]);
		expect(fs.readFileSync(path.join(root, "README.md"), "utf8")).toBe(
			"reviewed content",
		);
	});

	it("runs a ready auto-sync on agent_end without session-start noise", async () => {
		const realNow = Date.now;
		let now = 0;
		Date.now = () => now;
		try {
			const root = cwd();
			write(root, "README.md", "old");
			writeConfig(root, { documents: [{ path: "README.md" }] });
			completionText = JSON.stringify({
				updates: [{ path: "README.md", content: "new", summary: "auto" }],
			});
			const h = harness(root);

			await h.events.get("session_start")({}, h.ctx);
			expect(h.notifications).toEqual([]);

			await h.events.get("tool_execution_end")(
				{ toolName: "edit", isError: false },
				h.ctx,
			);
			now = 6 * 60 * 1000;
			await h.events.get("agent_end")({}, h.ctx);

			expect(fs.readFileSync(path.join(root, "README.md"), "utf8")).toBe("new");
			expect(
				h.notifications.some((n) => n.message.includes("updated 1 doc")),
			).toBe(true);
			expect(h.entries.at(-1)).toEqual({
				type: "custom",
				customType: "pulse-state",
				data: {
					version: 1,
					lastRunAt: now,
					lastRunReason: "changes",
					lastResult: "updated 1",
				},
			});
			await h.events.get("session_shutdown")({}, h.ctx);
		} finally {
			Date.now = realNow;
		}
	});

	it("restores persisted last status on session_start", async () => {
		const root = cwd();
		write(root, "README.md", "old");
		writeConfig(root, { documents: [{ path: "README.md" }] });
		const h = harness(root);
		h.entries.push({
			type: "custom",
			customType: "pulse-state",
			data: {
				version: 1,
				lastRunAt: 123,
				lastRunReason: "periodic",
				lastResult: "up to date",
			},
		});

		await h.events.get("session_start")({}, h.ctx);
		await h.commands.get("pulse").handler("status", h.ctx);

		expect(
			h.notifications.some((n) =>
				n.message.includes("last: up to date (periodic)"),
			),
		).toBe(true);
	});
});