repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by admin
extensions/loop/__tests__/kitten.test.ts
Rawimport {
mkdir,
mkdtemp,
readdir,
readFile,
rm,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join, relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import type { Theme } from "@earendil-works/pi-coding-agent";
import { rgbColor, TuiAltScreen, visibleWidth } from "@earendil-works/pi-tui";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
createPiSession,
type PiSession,
} from "../../../test/fixture/create-pi-session.ts";
import * as vixen from "../src/companion.ts";
import type { LoopSnapshot } from "../src/controller.ts";
import { createKitten, type KittenPose, kittenPixels } from "../src/kitten.ts";
import { resolveSetting } from "../src/pi-ext-settings.ts";
import { ANIM_SETTING, resolveKitten } from "../src/settings.ts";
import { createLoopWidget } from "../src/widget.ts";
import { MemoryTerminal } from "./terminal.ts";
const themes = await import(
new URL(
"./modes/interactive/theme/theme.js",
import.meta.resolve("@earendil-works/pi-coding-agent"),
).href
);
let box: PiSession | undefined;
let root: string | undefined;
afterEach(async () => {
vi.restoreAllMocks();
await box?.dispose();
box = undefined;
if (root) await rm(root, { recursive: true, force: true });
root = undefined;
vi.useRealTimers();
});
const run = (): LoopSnapshot => ({
id: "kitten",
goal: "Watch gates",
gates: [{ command: "unused" }],
cwd: ".",
budgets: { minutes: null, turns: 30, attempts: 10 },
status: "active",
reason: "",
turns: 6,
attempts: 3,
createdAt: 0,
updatedAt: 0,
deadline: null,
lastPass: null,
runningGate: 0,
runningSince: 0,
liveOutput: null,
pending: true,
pendingAudit: 0,
storageError: null,
});
describe("loop.anim real resolution and native widget paint", () => {
it.each([
[undefined, undefined, undefined, false, false, "default"],
["", false, false, true, true, "env"],
["0", false, false, true, true, "env"],
["false", false, false, true, true, "env"],
["anything", false, false, true, true, "env"],
[undefined, true, undefined, false, true, "user"],
[undefined, true, false, true, false, "project"],
[undefined, false, true, true, true, "project"],
[undefined, false, true, false, false, "user"],
[undefined, false, "false", true, true, "project"],
] as const)(
"env=%s user=%s project=%s trust=%s → kitten=%s",
async (env, user, project, trusted, expected, source) => {
root = await mkdtemp(join(tmpdir(), "loop-kitten-"));
await mkdir(join(root, ".pi"));
await writeFile(
join(root, ".pi", "settings.json"),
JSON.stringify({ loop: { anim: project } }),
);
box = await createPiSession({
cwd: root,
projectTrusted: trusted,
userSettings: { loop: { anim: user } },
env: { PI_LOOP_ANIM: env },
});
const ctx = box.session.extensionRunner.createContext();
const notify = vi.spyOn(ctx.ui, "notify");
const pi = { getFlag: () => undefined };
const resolution = resolveSetting(pi, ctx, ANIM_SETTING);
expect(resolution.source).toBe(source);
const chosen = resolveKitten(pi, ctx);
expect(chosen).toBe(expected);
expect(notify).toHaveBeenCalledTimes(project === "false" ? 1 : 0);
// This spy observes the actual imported factory, not a substituted renderer.
const constructVixen = vi.spyOn(vixen, "createCompanion");
vi.useFakeTimers();
vi.setSystemTime(0);
const tui = new TuiAltScreen(new MemoryTerminal());
const theme: Theme = themes.getThemeByName("light");
const current = {
run: run(),
baseline: true,
agentRunning: false,
vixen: true,
};
const widget = createLoopWidget(tui, theme, () => current, chosen);
const frames: string[][] = [];
const show = tui.showOverlay.bind(tui);
tui.showOverlay = (component, options) => {
frames.push(component.render(48));
return show(component, options);
};
try {
widget.render(120);
current.vixen = false;
widget.render(120);
current.vixen = true;
widget.render(120);
expect(constructVixen).toHaveBeenCalledTimes(expected ? 0 : 2);
expect(frames).toHaveLength(2);
const cream = theme.style("▀", {
fg: rgbColor(255, 228, 183),
bg: rgbColor(255, 228, 183),
});
for (const frame of frames) {
expect(frame.join("").includes(cream)).toBe(expected);
expect(frame.length).toBeLessThanOrEqual(23);
expect(frame.every((line) => visibleWidth(line) <= 48)).toBe(true);
}
} finally {
widget.dispose();
}
expect(tui.hasOverlay()).toBe(false);
expect(vi.getTimerCount()).toBe(0);
},
);
});
describe("original LOOP kitten motion", () => {
it("keeps runtime relative imports within the owning extension", async () => {
const root = fileURLToPath(new URL("../", import.meta.url));
const files = [
"index.ts",
...(await readdir(join(root, "src")))
.filter((name) => name.endsWith(".ts"))
.map((name) => join("src", name)),
];
for (const name of files) {
const path = join(root, name);
const source = await readFile(path, "utf8");
for (const match of source.matchAll(
/(?:from\s*|import\s*\()\s*["'](\.[^"']+)["']/gu,
)) {
const target = relative(root, resolve(dirname(path), match[1]!));
expect(target.startsWith(".."), `${name}: ${match[1]}`).toBe(false);
}
}
});
it("has distinct silhouettes and independent breathing, blinking, tail and paw motion", () => {
const poses: KittenPose[] = [
"working",
"watching",
"puzzled",
"curled",
"proud",
];
const frames = poses.map((pose) => kittenPixels(pose, 0));
expect(new Set(frames.map((frame) => JSON.stringify(frame))).size).toBe(5);
for (const pose of poses) {
const still = kittenPixels(pose, 0);
expect(still).toHaveLength(30);
expect(still.every((row) => row.length === 32)).toBe(true);
expect(still.flat().filter(Boolean).length).toBeGreaterThan(200);
expect(kittenPixels(pose, 1.4)).not.toEqual(still);
}
// Blink closes eyes while the head remains in place; tail moves separately.
const open = kittenPixels("watching", 5.3);
const blink = kittenPixels("watching", 5.4);
expect(open.slice(10, 14)).not.toEqual(blink.slice(10, 14));
expect(
kittenPixels("watching", 0)
.slice(17, 26)
.map((row) => row.slice(23)),
).not.toEqual(
kittenPixels("watching", 1.4)
.slice(17, 26)
.map((row) => row.slice(23)),
);
});
it.each(["dark", "light"])(
"paints actual state poses without captions in %s theme",
(name) => {
vi.useFakeTimers();
vi.setSystemTime(0);
const tui = new TuiAltScreen(new MemoryTerminal());
const theme: Theme = themes.getThemeByName(name);
const current = {
...run(),
failed: null as vixen.CompanionState["failed"],
};
const widget = createKitten(tui, theme, () => current, Date.now, 1.5);
try {
const watching = widget.render(48);
current.pending = false;
const working = widget.render(48);
current.failed = { gate: "tests", at: 0 };
const puzzled = widget.render(48);
current.status = "paused";
const curled = widget.render(48);
current.status = "succeeded";
const proud = widget.render(48);
expect(
new Set(
[watching, working, puzzled, curled, proud].map((frame) =>
frame.join(""),
),
).size,
).toBe(5);
for (const frame of [watching, working, puzzled, curled, proud]) {
expect(frame).toHaveLength(23);
expect(frame.every((line) => visibleWidth(line) <= 48)).toBe(true);
}
for (const width of [1, 31, 47])
expect(
widget.render(width).every((line) => visibleWidth(line) <= width),
).toBe(true);
vi.advanceTimersByTime(40_001);
expect(widget.render(48)).toEqual([]);
expect(vi.getTimerCount()).toBe(0);
} finally {
widget.dispose();
}
},
);
});