repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/extensions/llmiterate/__tests__/rpc.test.ts

Raw
File outline
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, test } from "bun:test";
import { PiRpcWorker } from "../rpc";
import type { RpcEvent } from "../types";

const tempDirs: string[] = [];
const workers: PiRpcWorker[] = [];

afterEach(() => {
  while (workers.length) workers.pop()!.dispose();
  while (tempDirs.length) rmSync(tempDirs.pop()!, { recursive: true, force: true });
});

function tempDir(): string {
  const dir = mkdtempSync(join(tmpdir(), "llmiterate-rpc-"));
  tempDirs.push(dir);
  return dir;
}

describe("PiRpcWorker integration", () => {
  test("runs prompt through JSON-RPC worker and forwards events", async () => {
    const root = tempDir();
    const fake = writeFakeRpc(root, "ok");
    const events: RpcEvent[] = [];
    const worker = new PiRpcWorker({
      cwd: root,
      sessionDir: join(root, "sessions"),
      invocation: { command: process.execPath, args: [fake] },
      onEvent: (event) => events.push(event),
    });
    workers.push(worker);

    await worker.runPrompt("do thing", "job name");

    expect(events.map((e) => e.type)).toEqual(["message_update", "tool_execution_start", "tool_execution_end", "agent_end"]);
    const first = events[0];
    expect(first.type).toBe("message_update");
    if (first.type === "message_update") {
      const content = first.message?.content;
      expect(Array.isArray(content) ? content[0]?.text : undefined).toBe("streaming");
    }
  });

  test("rejects concurrent prompts instead of corrupting current prompt", async () => {
    const root = tempDir();
    const fake = writeFakeRpc(root, "ok");
    const worker = new PiRpcWorker({
      cwd: root,
      sessionDir: join(root, "sessions"),
      invocation: { command: process.execPath, args: [fake] },
      onEvent: () => {},
    });
    workers.push(worker);

    const first = worker.runPrompt("first", "first job");
    await expect(worker.runPrompt("second", "second job")).rejects.toThrow("already has an active prompt");
    await first;
  });

  test("rejects failed RPC command", async () => {
    const root = tempDir();
    const fake = writeFakeRpc(root, "fail-new-session");
    const worker = new PiRpcWorker({
      cwd: root,
      sessionDir: join(root, "sessions"),
      invocation: { command: process.execPath, args: [fake] },
      onEvent: () => {},
    });
    workers.push(worker);

    await expect(worker.runPrompt("do thing", "job name")).rejects.toThrow("new_session denied");
  });

  test("rejects malformed RPC stdout", async () => {
    const root = tempDir();
    const fake = writeFakeRpc(root, "malformed");
    const worker = new PiRpcWorker({
      cwd: root,
      sessionDir: join(root, "sessions"),
      invocation: { command: process.execPath, args: [fake] },
      onEvent: () => {},
    });
    workers.push(worker);

    await expect(worker.runPrompt("do thing", "job name")).rejects.toThrow();
  });
});

function writeFakeRpc(root: string, mode: "ok" | "fail-new-session" | "malformed"): string {
  const file = join(root, "fake-rpc.js");
  writeFileSync(file, `
process.stdin.setEncoding('utf8');
let buffer = '';
process.stdin.on('data', chunk => {
  buffer += chunk;
  const lines = buffer.split('\\n');
  buffer = lines.pop() || '';
  for (const line of lines) handle(line);
});
function send(value) { process.stdout.write(JSON.stringify(value) + '\\n'); }
function handle(line) {
  if (!line.trim()) return;
  const msg = JSON.parse(line);
  if (${JSON.stringify(mode)} === 'fail-new-session' && msg.type === 'new_session') {
    send({ id: msg.id, type: 'response', command: msg.type, success: false, error: 'new_session denied' });
    return;
  }
  send({ id: msg.id, type: 'response', command: msg.type, success: true });
  if (${JSON.stringify(mode)} === 'malformed' && msg.type === 'prompt') {
    process.stdout.write('not json\\n');
    return;
  }
  if (msg.type === 'prompt') {
    send({ type: 'message_update', message: { role: 'assistant', content: [{ type: 'text', text: 'streaming' }] } });
    send({ type: 'tool_execution_start', toolName: 'edit' });
    send({ type: 'tool_execution_end', toolName: 'edit', isError: false, result: { content: [{ type: 'text', text: 'ok' }] } });
    send({ type: 'agent_end' });
  }
}
`, "utf-8");
  return file;
}