repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/goldfish/__tests__/goldfish.test.ts

Raw
import { describe, expect, test } from "vitest";
import goldfishExtension, { __test } from "../index";

const {
	applyEvent,
	buildGuidance,
	createState,
	currentTask,
	executeTaskAction,
	gateToolCall,
	replayGoldfish,
	taskResultLines,
	taskResultTone,
	toolNamesForMode,
	widgetLines,
	widgetTone,
} = __test;

describe("goldfish state", () => {
	test("empty state is idle", () => {
		expect(currentTask(createState())).toBeUndefined();
	});

	test("create/done/abandon transitions are replayable", () => {
		const state = createState();
		applyEvent(state, {
			op: "create",
			id: 1,
			title: "Fix tests",
			doneCommand: "npm test",
			doneTimeoutSeconds: 60,
			createdAt: 1,
		});
		expect(currentTask(state)?.title).toBe("Fix tests");
		applyEvent(state, { op: "done", id: 1, result: "passed", updatedAt: 2 });
		expect(currentTask(state)).toBeUndefined();

		const replayed = replayGoldfish([
			{
				type: "custom",
				customType: "goldfish-state",
				data: {
					op: "create",
					id: 2,
					title: "Next",
					doneCommand: "true",
					doneTimeoutSeconds: 60,
					createdAt: 3,
				},
			},
			{
				type: "custom",
				customType: "goldfish-state",
				data: { op: "abandon", id: 2, reason: "bad check", updatedAt: 4 },
			},
		]);
		expect(currentTask(replayed)).toBeUndefined();
		expect(replayed.tasks.get(2)?.status).toBe("abandoned");
	});
});

describe("goldfish tool", () => {
	test("create creates active task and renders collapsed/expanded professionally", async () => {
		const state = createState();
		const result = await executeTaskAction(state, {
			action: "create",
			title: "Fix goldfish",
			doneCommand: "mise run test -- extensions/goldfish",
			doneTimeoutSeconds: 99,
		});

		expect(
			result.content[0]?.type === "text" ? result.content[0].text : "",
		).toBe("task active. Do work, then call task.check before final answer.");
		expect(currentTask(state)?.title).toBe("Fix goldfish");
		expect(taskResultLines(result, false)).toEqual([
			"◌ task active · #1 Fix goldfish · check: mise run test -- extensions/goldfish · timeout 99s · expand for context",
		]);
		expect(taskResultTone(result)).toBe("accent");
		expect(taskResultLines(result, true)).toContain("status: active");
		expect(taskResultLines(result, true)).toContain(
			"done: mise run test -- extensions/goldfish",
		);
	});

	test("check command exit contract closes, continues, or abandons", async () => {
		const done = createState();
		await executeTaskAction(done, {
			action: "create",
			title: "done",
			doneCommand: "x",
		});
		await executeTaskAction(done, { action: "check" }, async () => ({
			exitCode: 0,
			stdout: "ok",
			stderr: "",
		}));
		expect(done.tasks.get(1)?.status).toBe("done");
		expect(
			taskResultTone(
				await executeTaskAction(createState(), { action: "check" }),
			),
		).toBe("error");

		const active = createState();
		await executeTaskAction(active, {
			action: "create",
			title: "not yet",
			doneCommand: "x",
		});
		await executeTaskAction(active, { action: "check" }, async () => ({
			exitCode: 1,
			stdout: "no",
			stderr: "",
		}));
		expect(currentTask(active)?.status).toBe("active");

		const abandoned = createState();
		await executeTaskAction(abandoned, {
			action: "create",
			title: "bad",
			doneCommand: "x",
		});
		await executeTaskAction(abandoned, { action: "check" }, async () => ({
			exitCode: 2,
			stdout: "",
			stderr: "boom",
		}));
		expect(abandoned.tasks.get(1)?.status).toBe("abandoned");
		expect(
			taskResultTone(
				await executeTaskAction(abandoned, {
					action: "abandon",
					reason: "already abandoned",
				}),
			),
		).toBe("error");
	});

	test("timeout abandons", async () => {
		const state = createState();
		await executeTaskAction(state, {
			action: "create",
			title: "slow",
			doneCommand: "x",
		});
		await executeTaskAction(state, { action: "check" }, async () => ({
			exitCode: null,
			timedOut: true,
			stdout: "",
			stderr: "",
		}));
		expect(state.tasks.get(1)?.status).toBe("abandoned");
	});
});

describe("goldfish gates and guidance", () => {
	test("disabled mode restores normal tools and hides goldfish", () => {
		expect(toolNamesForMode(["read", "bash"], createState(), false)).toEqual([
			"read",
			"bash",
		]);
	});

	test("enabled tool visibility keeps normal tools visible for same-turn unlock", () => {
		expect(toolNamesForMode(["read", "bash"], createState(), true)).toEqual([
			"read",
			"bash",
			"task",
		]);
		const state = createState();
		applyEvent(state, {
			op: "create",
			id: 1,
			title: "x",
			doneCommand: "true",
			doneTimeoutSeconds: 60,
			createdAt: 1,
		});
		expect(toolNamesForMode(["read", "bash"], state, true)).toEqual([
			"read",
			"bash",
			"task",
		]);
	});

	test("hard gate blocks non-goldfish tools while idle", () => {
		expect(gateToolCall(createState(), "read")).toEqual({
			block: true,
			reason: "goldfish: call task with action=create before other tools",
		});
		expect(gateToolCall(createState(), "task")).toBeUndefined();
		const state = createState();
		applyEvent(state, {
			op: "create",
			id: 1,
			title: "x",
			doneCommand: "true",
			doneTimeoutSeconds: 60,
			createdAt: 1,
		});
		expect(gateToolCall(state, "read")).toBeUndefined();
	});

	test("guidance is short and stateful", () => {
		expect(buildGuidance(createState())).toContain(
			"Call `task` with action=create before using normal tools",
		);
		const state = createState();
		applyEvent(state, {
			op: "create",
			id: 1,
			title: "x",
			doneCommand: "true",
			doneTimeoutSeconds: 60,
			createdAt: 1,
		});
		expect(buildGuidance(state)).toContain("Active task #1: x");
		expect(buildGuidance(state).split("\n").length).toBeLessThanOrEqual(12);
	});
});

describe("goldfish widget", () => {
	test("widget shows persistent compact and expanded state", () => {
		expect(widgetLines(createState(), false, 120)).toEqual([
			"󰈸  blocked · create task to unlock tools",
		]);
		expect(widgetTone(createState())).toBe("warning");
		const state = createState();
		applyEvent(state, {
			op: "create",
			id: 1,
			title: "Fix widget",
			doneCommand: "mise run test",
			doneTimeoutSeconds: 60,
			createdAt: 1,
		});
		expect(widgetLines(state, false, 120)[0]).toContain(
			"active #1 · Fix widget",
		);
		expect(widgetTone(state)).toBe("accent");
		expect(widgetLines(state, true, 120)).toContain(
			"   done     mise run test",
		);
	});
});

describe("goldfish extension registration", () => {
	test("registers goldfish controls", () => {
		const tools: string[] = [];
		const events: string[] = [];
		const shortcuts: string[] = [];
		const commands: string[] = [];
		const flags: string[] = [];
		goldfishExtension({
			registerTool(tool: { name: string }) {
				tools.push(tool.name);
			},
			on(event: string) {
				events.push(event);
			},
			registerShortcut(key: string) {
				shortcuts.push(key);
			},
			registerCommand(name: string) {
				commands.push(name);
			},
			registerFlag(name: string) {
				flags.push(name);
			},
			getFlag() {
				return false;
			},
		} as any);
		expect(tools).toEqual(["task"]);
		expect(commands).toEqual(["goldfish"]);
		expect(flags).toEqual(["goldfish"]);
		expect(events).toEqual(
			expect.arrayContaining([
				"session_start",
				"tool_call",
				"before_agent_start",
			]),
		);
		expect(shortcuts).toEqual(["alt+t"]);
	});

	test("--goldfish starts enabled", () => {
		const handlers = new Map<string, Function>();
		const activeTools: string[][] = [];
		goldfishExtension({
			registerTool() {},
			registerCommand() {},
			registerShortcut() {},
			registerFlag() {},
			getFlag(name: string) {
				return name === "goldfish" ? "true" : undefined;
			},
			on(event: string, handler: Function) {
				handlers.set(event, handler);
			},
			getActiveTools() {
				return ["read", "bash", "task"];
			},
			setActiveTools(names: string[]) {
				activeTools.push(names);
			},
		} as any);

		handlers.get("session_start")?.(
			{},
			{
				hasUI: false,
				sessionManager: { getBranch: () => [] },
			},
		);

		expect(activeTools).toEqual([]);
	});

	test("OFF session start has no visible Pi changes except hiding goldfish tool", () => {
		const handlers = new Map<string, Function>();
		const activeTools: string[][] = [];
		const widgets: unknown[] = [];
		goldfishExtension({
			registerTool() {},
			registerCommand() {},
			registerShortcut() {},
			registerFlag() {},
			getFlag() {
				return false;
			},
			on(event: string, handler: Function) {
				handlers.set(event, handler);
			},
			getActiveTools() {
				return ["read", "bash", "task"];
			},
			setActiveTools(names: string[]) {
				activeTools.push(names);
			},
		} as any);

		handlers.get("session_start")?.(
			{},
			{
				hasUI: true,
				ui: { setWidget: (...args: unknown[]) => widgets.push(args) },
				sessionManager: { getBranch: () => [] },
			},
		);

		expect(activeTools).toEqual([["read", "bash"]]);
		expect(widgets).toEqual([]);
		expect(
			handlers.get("tool_call")?.({ toolName: "read" }, {}),
		).toBeUndefined();
		expect(
			handlers.get("before_agent_start")?.({ systemPrompt: "base" }, {}),
		).toBeUndefined();
	});
});