Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

7.6 KB
Raw Blame
import { afterEach, describe, expect, it, vi } from 'vitest';

import { createPiRpcAgentHandle, toPiRpcPrompt } from './piRpcAgentHandle';
import type { PiRpcEvent } from './piRpcProtocol';

const mocks = vi.hoisted(() => ({
  clientInstances: [] as any[],
  command: vi.fn(),
  start: vi.fn(),
  close: vi.fn(),
  abort: vi.fn(),
}));

vi.mock('./piRpcClient', async (importOriginal) => {
  const actual = await importOriginal<Record<string, unknown>>();
  return {
    ...actual,
    PiRpcClient: class MockPiRpcClient {
      static instances = mocks.clientInstances;
      onEvent?: (event: PiRpcEvent) => void | Promise<void>;
      constructor(readonly options: any) {
        this.onEvent = options.onEvent;
        mocks.clientInstances.push(this);
      }
      get pid() {
        return 123_456;
      }
      get isReady() {
        return true;
      }
      get sessionId() {
        return undefined;
      }
      start = mocks.start;
      command = mocks.command;
      close = mocks.close;
      abort = mocks.abort;
      setOperationContext = async () => {};
      clearOperationContext = async () => {};
    },
  };
});

const emit = (event: PiRpcEvent) => {
  const client = mocks.clientInstances.at(-1)!;
  return client.onEvent!(event);
};

afterEach(() => {
  vi.restoreAllMocks();
  mocks.clientInstances.length = 0;
  mocks.start.mockReset();
  mocks.command.mockReset();
  mocks.close.mockReset();
  mocks.abort.mockReset();
});

describe('toPiRpcPrompt', () => {
  it('rejects unreadable attachments instead of silently sending an incomplete prompt', async () => {
    await expect(
      toPiRpcPrompt([
        { type: 'text', text: 'describe this' },
        { type: 'image', source: { type: 'path', path: '/nonexistent-pi-test-image.png' } },
      ]),
    ).rejects.toThrow();
  });

  it('joins text blocks and leaves image-less prompts image-free', async () => {
    await expect(toPiRpcPrompt('hello')).resolves.toEqual({ text: 'hello' });
    await expect(
      toPiRpcPrompt([
        { text: 'one', type: 'text' },
        { text: 'two', type: 'text' },
      ]),
    ).resolves.toEqual({ text: 'one\n\ntwo' });
  });
});

describe('createPiRpcAgentHandle', () => {
  it('preserves prompt failure diagnostics in stderr and exits nonzero', async () => {
    mocks.start.mockResolvedValue(undefined);
    mocks.close.mockResolvedValue(undefined);
    mocks.command.mockRejectedValue(new Error('prompt rejected: invalid model'));
    const handle = await createPiRpcAgentHandle({
      args: [],
      commandPath: 'pi',
      cwd: '/workspace',
      env: { ...process.env },
      operationId: 'op-error',
      prompt: { text: 'x' },
    });
    let stderr = '';
    handle.stderr.on('data', (data) => {
      stderr += data;
    });
    await expect(handle.exit).resolves.toEqual({ code: 1, signal: null });
    expect(stderr).toContain('prompt rejected: invalid model');
    expect(mocks.close).toHaveBeenCalled();
  });

  it('streams adapted events, resolves exit on settle, and reports the native session id', async () => {
    mocks.start.mockResolvedValue(undefined);
    mocks.command.mockImplementation((command: { type: string }) => {
      if (command.type === 'get_state') {
        return Promise.resolve({ success: true, type: 'response', command: 'get_state' });
      }
      return Promise.resolve({ success: true, type: 'response', command: command.type });
    });
    mocks.close.mockResolvedValue(undefined);

    const handle = await createPiRpcAgentHandle({
      args: [],
      commandPath: 'pi',
      cwd: '/workspace',
      env: { ...process.env },
      operationId: 'op-cli',
      prompt: { text: 'inspect the repo' },
    });

    const collected: string[] = [];
    const consume = (async () => {
      for await (const event of handle.events) {
        if (event.type === 'stream_chunk' && event.data.chunkType === 'text') {
          collected.push(event.data.content);
        }
      }
    })();

    await emit({ type: 'session', id: 'native-1' });
    await emit({
      assistantMessageEvent: { contentIndex: 0, delta: 'Hi', type: 'text_delta' },
      type: 'message_update',
    });
    await emit({ type: 'agent_settled' });

    await consume;
    await expect(handle.exit).resolves.toEqual({ code: 0, signal: null });
    expect(collected.join('')).toBe('Hi');
    expect(handle.sessionId).toBe('native-1');
  });

  it('rejects on spawn/handshake failure so the CLI can classify it', async () => {
    mocks.start.mockRejectedValue(new Error('pi did not answer the RPC handshake'));
    await expect(
      createPiRpcAgentHandle({
        args: [],
        commandPath: 'pi',
        cwd: '/workspace',
        env: { ...process.env },
        operationId: 'op-cli',
        prompt: { text: 'x' },
      }),
    ).rejects.toThrow(/handshake/);
  });

  it('exposes startup cancellation before awaiting the handshake and closes instead of aborting', async () => {
    let rejectStart: ((error: Error) => void) | undefined;
    mocks.start.mockReturnValue(
      new Promise<void>((_resolve, reject) => {
        rejectStart = reject;
      }),
    );
    mocks.close.mockResolvedValue(undefined);
    let control: { cancel: (signal: NodeJS.Signals) => Promise<void> } | undefined;

    const creating = createPiRpcAgentHandle({
      args: [],
      commandPath: 'pi',
      cwd: '/workspace',
      env: { ...process.env },
      onStartupControl: (value) => {
        control = value;
      },
      operationId: 'op-startup-cancel',
      prompt: { text: 'x' },
    });

    expect(control).toBeDefined();
    await control!.cancel('SIGINT');
    expect(mocks.close).toHaveBeenCalledOnce();
    expect(mocks.abort).not.toHaveBeenCalled();
    rejectStart!(new Error('Pi RPC session is closed'));
    await expect(creating).rejects.toThrow('closed');
  });

  it('forces startup shutdown on SIGKILL and installs raw stdout before start', async () => {
    mocks.start.mockResolvedValue(undefined);
    mocks.close.mockResolvedValue(undefined);
    mocks.command.mockResolvedValue({ success: true, type: 'response' });
    const onRawStdout = vi.fn();
    let control: { cancel: (signal: NodeJS.Signals) => Promise<void> } | undefined;

    const creating = createPiRpcAgentHandle({
      args: [],
      commandPath: 'pi',
      cwd: '/workspace',
      env: { ...process.env },
      onRawStdout,
      onStartupControl: (value) => {
        control = value;
      },
      operationId: 'op-force',
      prompt: { text: 'x' },
    });
    // Session construction (and therefore raw tee installation) happened
    // before startup control became observable and before the eager await.
    expect(mocks.clientInstances).toHaveLength(1);
    await control!.cancel('SIGKILL');
    // PiRpcSession owns propagation of `{ force: true }` to the transport.
    expect(mocks.close).toHaveBeenCalledOnce();
    await expect(creating).rejects.toThrow('closed');
  });

  it('maps kill(SIGINT) to a graceful abort', async () => {
    mocks.start.mockResolvedValue(undefined);
    mocks.command.mockImplementation((command: { type: string }) => {
      if (command.type === 'get_state') {
        return Promise.resolve({ success: true, type: 'response', command: 'get_state' });
      }
      return Promise.resolve({ success: true, type: 'response', command: command.type });
    });
    mocks.close.mockResolvedValue(undefined);

    const handle = await createPiRpcAgentHandle({
      args: [],
      commandPath: 'pi',
      cwd: '/workspace',
      env: { ...process.env },
      operationId: 'op-cli',
      prompt: { text: 'x' },
    });

    handle.kill('SIGINT');
    expect(mocks.abort).toHaveBeenCalled();
    await emit({ type: 'agent_settled' });
    await handle.exit;
  });
});