repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/pulse/__tests__/harness.test.ts

Raw
File outline
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { createTestSession, type TestSession } from "../../../test/harness";
import pulse, { __setPulseModelClient } from "../index.ts";

let t: TestSession | undefined;

afterEach(() => {
	t?.dispose();
	t = undefined;
});

function pulsePath(): string {
	return path.resolve(import.meta.dirname, "../index.ts");
}

function pulseCommand() {
	const [extension] = t?.session.extensionRunner.extensions ?? [];
	return extension?.commands.get("pulse");
}

function ctx(): any {
	return t?.session.extensionRunner.createCommandContext();
}

function settingsPath(): string {
	return path.join(t?.cwd, ".pi/settings.json");
}

function writeConfig(config: unknown): void {
	mkdirSync(path.dirname(settingsPath()), { recursive: true });
	writeFileSync(
		settingsPath(),
		JSON.stringify({ pulse: config }, null, 2),
		"utf8",
	);
}

function readConfig(): any {
	return JSON.parse(readFileSync(settingsPath(), "utf8")).pulse;
}

function notifyText(): string[] {
	return t?.events.uiCallsFor("notify").map((c) => String(c.args[0]));
}

function statusText(): string[] {
	return t?.events
		.uiCallsFor("setStatus")
		.filter((c) => c.args[0] === "pulse")
		.map((c) => String(c.args[1]));
}

async function waitFor(
	fn: () => boolean,
	setTimeoutFn: typeof setTimeout,
	nowFn: () => number,
	timeoutMs = 2000,
): Promise<void> {
	const started = nowFn();
	while (!fn() && nowFn() - started < timeoutMs) {
		await new Promise((resolve) => setTimeoutFn(resolve, 25));
	}
}

describe("pulse pi-test-harness integration", () => {
	it("runs init/list/status/pause/resume via real command context", async () => {
		t = await createTestSession({ extensions: [pulsePath()] });
		const [extension] = t.session.extensionRunner.extensions;
		expect(extension.path).toBe(pulsePath());
		expect([...extension.commands.keys()]).toEqual(["pulse"]);
		expect([...extension.tools.keys()]).toEqual([]);
		expect(typeof pulseCommand().handler).toBe("function");
		writeFileSync(path.join(t.cwd, "README.md"), "# Test\n", "utf8");

		await pulseCommand().handler("init", ctx());
		expect(existsSync(settingsPath())).toBe(true);
		expect(readConfig().documents).toEqual([{ path: "README.md" }]);

		await pulseCommand().handler("help", ctx());
		await pulseCommand().handler("list", ctx());
		await pulseCommand().handler("status", ctx());
		await pulseCommand().handler("pause", ctx());
		await pulseCommand().handler("resume", ctx());

		expect(notifyText()).toContain("Pulse: initialized 1 doc(s)");
		expect(
			notifyText().some((m) => m.startsWith("Pulse — auto-sync tracked docs")),
		).toBe(true);
		expect(notifyText().some((m) => m.startsWith("Pulse: 1 doc(s)"))).toBe(
			true,
		);
		expect(notifyText().some((m) => m.startsWith("Pulse\ndocs: 1"))).toBe(true);
		expect(notifyText()).toContain("Pulse: paused");
		expect(notifyText()).toContain("Pulse: resumed");
		expect(statusText().some((s) => s === "󰐰 paused")).toBe(true);
		expect(pulseCommand().getArgumentCompletions("con") ?? []).toEqual([]);
	});

	it("handles add/add-dir/add-glob/remove completions with real runtime", async () => {
		t = await createTestSession({ extensions: [pulsePath()] });
		writeFileSync(path.join(t.cwd, "my file.md"), "doc", "utf8");
		writeFileSync(path.join(t.cwd, "README.md"), "doc", "utf8");
		mkdirSync(path.join(t.cwd, "docs"), { recursive: true });
		writeFileSync(path.join(t.cwd, "docs/a.md"), "doc", "utf8");
		mkdirSync(path.join(t.cwd, "adr"), { recursive: true });
		writeFileSync(path.join(t.cwd, "adr/001.md"), "adr", "utf8");
		writeConfig({ documents: [] });

		await pulseCommand().handler('add "my file.md" note here', ctx());
		await pulseCommand().handler("add-dir docs **/*.md docs note", ctx());
		await pulseCommand().handler("add-glob adr/**/*.md adr note", ctx());
		expect(readConfig().documents).toEqual([
			{ path: "my file.md", instruction: "note here" },
			{ path: "docs", type: "dir", glob: "**/*.md", instruction: "docs note" },
			{ path: "adr/**/*.md", type: "glob", instruction: "adr note" },
		]);

		const addCompletions = pulseCommand().getArgumentCompletions("add my");
		expect(addCompletions).toContainEqual({
			value: 'add "my file.md"',
			label: "my file.md",
		});
		const removeCompletions =
			pulseCommand().getArgumentCompletions("remove my");
		expect(removeCompletions).toContainEqual({
			value: 'remove "my file.md"',
			label: "my file.md",
		});

		await pulseCommand().handler('remove "my file.md"', ctx());
		expect(readConfig().documents.map((d: { path: string }) => d.path)).toEqual(
			["docs", "adr/**/*.md"],
		);
	});

	it("starts cleanly on session_start without notification spam and reports status", async () => {
		t = await createTestSession({ extensions: [pulsePath()] });
		writeFileSync(path.join(t.cwd, "README.md"), "doc", "utf8");
		writeConfig({ documents: [{ path: "README.md" }] });

		await t.session.extensionRunner.emit({
			type: "session_start",
			reason: "startup",
		});

		expect(notifyText()).toEqual([]);
		expect(statusText()).toContain("󰐰 1");

		await t.session.extensionRunner.emit({
			type: "session_shutdown",
			reason: "quit",
		});
	});

	it("marks workspace changes from real tool events and keeps force feedback", async () => {
		t = await createTestSession({ extensions: [pulsePath()] });
		writeConfig({ documents: [{ path: "README.md" }] });
		await t.session.extensionRunner.emit({
			type: "session_start",
			reason: "startup",
		});

		await t.session.extensionRunner.emit({
			type: "tool_execution_end",
			toolCallId: "edit-1",
			toolName: "edit",
			input: { path: "README.md" },
			content: [{ type: "text", text: "edited" }],
			details: {},
			isError: false,
		});
		expect(statusText().some((s) => s.includes("sync in"))).toBe(true);

		await pulseCommand().handler("force", ctx());
		expect(notifyText().some((m) => m.startsWith("Pulse: "))).toBe(true);

		await t.session.extensionRunner.emit({
			type: "session_shutdown",
			reason: "quit",
		});
	});

	it("runs periodic idle checks from the timer", async () => {
		const realSetInterval = globalThis.setInterval;
		const realClearInterval = globalThis.clearInterval;
		const realSetTimeout = globalThis.setTimeout;
		const realNow = Date.now;
		let tick: (() => void) | undefined;
		let now = 0;
		globalThis.setInterval = ((fn: () => void) => {
			tick = fn;
			return 1 as never;
		}) as never;
		globalThis.clearInterval = (() => {}) as never;
		Date.now = () => now;

		try {
			__setPulseModelClient({
				complete: (async () => ({
					content: [
						{
							type: "text",
							text: '{"updates":[{"path":"README.md","content":"new","summary":"changed"}]}',
						},
					],
				})) as never,
				getModel: ((provider: string, id: string) => ({
					provider,
					id,
				})) as never,
			});
			t = await createTestSession({ extensionFactories: [pulse] });
			writeFileSync(path.join(t.cwd, "README.md"), "old", "utf8");
			writeConfig({ interval: 1, documents: [{ path: "README.md" }] });

			await t.session.extensionRunner.emit({
				type: "session_start",
				reason: "startup",
			});
			expect(tick).toBeDefined();

			now = 6 * 60 * 1000;
			tick?.();
			await waitFor(
				() => notifyText().some((m) => m.startsWith("Pulse: ")),
				realSetTimeout,
				realNow,
			);

			expect(notifyText().some((m) => m.startsWith("Pulse: "))).toBe(true);
			await t.session.extensionRunner.emit({
				type: "session_shutdown",
				reason: "quit",
			});
		} finally {
			__setPulseModelClient();
			globalThis.setInterval = realSetInterval;
			globalThis.clearInterval = realClearInterval;
			Date.now = realNow;
		}
	});
});