repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/ui/__tests__/rpc.test.ts
RawFile outline
import { once } from "node:events";
import { describe, expect, it } from "vitest";
import { parseJsonLines, rpcSpawnPlan, startRpc } from "../rpc";
const node = process.execPath;
describe("ui rpc bridge", () => {
it("splits only on LF and keeps partial records", () => {
const parsed = parseJsonLines(
'{"type":"event","text":"a
b"}\r\n{"type":"partial"',
);
expect(parsed.messages).toEqual([{ type: "event", text: "a
b" }]);
expect(parsed.rest).toBe('{"type":"partial"');
});
it("wraps win32 cmd shims through cmd.exe", () => {
expect(rpcSpawnPlan("pi.cmd", ["--mode", "rpc"], "win32")).toEqual({
command: "cmd.exe",
args: ["/d", "/s", "/c", "pi.cmd", "--mode", "rpc"],
windowsHide: true,
});
expect(rpcSpawnPlan("pi", ["--mode", "rpc"], "linux")).toEqual({
command: "pi",
args: ["--mode", "rpc"],
windowsHide: false,
});
});
it("matches responses by id and forwards events", async () => {
const events: unknown[] = [];
const rpc = startRpc({
command: node,
args: [
"-e",
`process.stdin.on('data', chunk => {
for (const line of String(chunk).trim().split('\\n')) {
const msg = JSON.parse(line);
console.log(JSON.stringify({ type: 'event', seen: msg.type }));
console.log(JSON.stringify({ id: msg.id, type: 'response', command: msg.type, success: true, data: { ok: true } }));
}
});`,
],
cwd: process.cwd(),
sessionPath: "session.jsonl",
onEvent: (event) => events.push(event),
});
try {
const response = await rpc.send({ type: "get_state" });
expect(response).toMatchObject({
type: "response",
command: "get_state",
success: true,
data: { ok: true },
});
expect(events).toEqual([{ type: "event", seen: "get_state" }]);
} finally {
await rpc.close("test");
}
});
it("captures stderr", async () => {
const rpc = startRpc({
command: node,
args: ["-e", "console.error('rpc stderr'); setTimeout(() => {}, 50);"],
cwd: process.cwd(),
sessionPath: "session.jsonl",
});
try {
await once(rpc.child.stderr, "data");
expect(rpc.stderr()).toContain("rpc stderr");
} finally {
await rpc.close("test");
}
});
it("times out unanswered requests", async () => {
const rpc = startRpc({
command: node,
args: ["-e", "process.stdin.resume()"],
cwd: process.cwd(),
sessionPath: "session.jsonl",
requestTimeoutMs: 10,
});
try {
await expect(rpc.send({ type: "get_state" })).rejects.toThrow(
/timed out/,
);
} finally {
await rpc.close("test");
}
});
it("emits slow-start and exit lifecycle states", async () => {
const states: string[] = [];
const rpc = startRpc({
command: node,
args: ["-e", "setTimeout(() => process.exit(7), 40)"],
cwd: process.cwd(),
sessionPath: "session.jsonl",
slowStartMs: 5,
onState: (state) => states.push(state),
});
await once(rpc.child, "exit");
expect(states).toContain("slow-start");
expect(states).toContain("exit");
});
});