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.

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

import { getTrpcClient } from '../../api/client';
import { removeTask, saveTask } from '../../daemon/taskRegistry';
import { cancelHeteroTask, runHeteroTask } from '../heteroTask';

// ─── Mocks ───

const spawnMock = vi.hoisted(() => vi.fn());
const execFileSyncMock = vi.hoisted(() => vi.fn());
const fsState = vi.hoisted(() => ({ content: undefined as string | undefined }));
const notifyMutateMock = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
const prepareSpawnMock = vi.hoisted(() => vi.fn());
const resolveRemotePlatformRuntimeMock = vi.hoisted(() => vi.fn());

vi.mock('node:child_process', () => ({
  execFileSync: execFileSyncMock,
  spawn: spawnMock,
}));

vi.mock('@lobechat/heterogeneous-agents/scanHost', () => ({
  resolveRemotePlatformRuntime: resolveRemotePlatformRuntimeMock,
}));

vi.mock('node:fs', () => ({
  default: {
    mkdirSync: vi.fn(),
    readFileSync: vi.fn(() => {
      if (fsState.content === undefined) throw new Error('File not found');
      return fsState.content;
    }),
    writeFileSync: vi.fn((_path: string, content: string) => {
      fsState.content = content;
    }),
  },
}));

// task registry β€” use real implementation backed by a temporary in-memory map
const taskStore: Record<string, any> = {};
vi.mock('../../daemon/taskRegistry', () => ({
  getTask: vi.fn((id: string) => taskStore[id]),
  listTasks: vi.fn(() => Object.values(taskStore)),
  removeTask: vi.fn((id: string) => {
    delete taskStore[id];
  }),
  saveTask: vi.fn((entry: any) => {
    taskStore[entry.taskId] = entry;
  }),
}));

vi.mock('../../api/client', () => ({
  getTrpcClient: vi.fn().mockResolvedValue({
    agentNotify: {
      notify: { mutate: notifyMutateMock },
    },
  }),
}));

const getTrpcClientMock = vi.mocked(getTrpcClient);

vi.mock('../../utils/logger', () => ({
  log: { error: vi.fn(), info: vi.fn(), warn: vi.fn() },
}));

beforeEach(() => {
  resolveRemotePlatformRuntimeMock.mockImplementation(
    async (type: 'hermes' | 'openclaw', baseEnv: NodeJS.ProcessEnv) => ({
      available: true,
      execute: vi.fn(),
      prepareSpawn: (args: string[]) => prepareSpawnMock(type, args, baseEnv),
    }),
  );
  prepareSpawnMock.mockImplementation(
    async (type: 'hermes' | 'openclaw', args: string[], baseEnv: NodeJS.ProcessEnv) => ({
      args,
      command: `/resolved/bin/${type}`,
      env: {
        ...baseEnv,
        PATH: '/resolved/bin:/runtime/bin:/usr/bin',
      },
    }),
  );
});

// ─── Helpers ───

function resetTrpcClientMock() {
  notifyMutateMock.mockResolvedValue(undefined);
  getTrpcClientMock.mockImplementation(
    () =>
      Promise.resolve({
        agentNotify: { notify: { mutate: notifyMutateMock } },
      }) as ReturnType<typeof getTrpcClient>,
  );
}

function makeMockStream() {
  const listeners: Array<(chunk: Buffer) => void> = [];

  return {
    on: vi.fn((_event: string, cb: (chunk: Buffer) => void) => listeners.push(cb)),
    _emit: (content: string) => listeners.forEach((cb) => cb(Buffer.from(content))),
  };
}

function makeMockChild(pid = 9999) {
  const listeners: Record<string, Array<(...a: any[]) => void>> = {};
  return {
    on: vi.fn((event: string, cb: (...a: any[]) => void) => {
      (listeners[event] ??= []).push(cb);
    }),
    pid,
    stderr: makeMockStream(),
    stdout: makeMockStream(),
    unref: vi.fn(),
    _emit: (event: string, ...args: any[]) => listeners[event]?.forEach((cb) => cb(...args)),
  };
}

// ─── Tests ───

describe.each(['openclaw', 'hermes'] as const)('runHeteroTask (%s) identity', (agentType) => {
  beforeEach(() => {
    vi.clearAllMocks();
    for (const key of Object.keys(taskStore)) delete taskStore[key];
    execFileSyncMock.mockReturnValue('/usr/local/bin/lh\n');
    spawnMock.mockReturnValue(makeMockChild());
    resetTrpcClientMock();
  });

  afterEach(() => {
    vi.unstubAllEnvs();
    vi.restoreAllMocks();
  });

  it.each([
    { agentId: 'agent-current', inherited: false, workspaceId: 'workspace-current' },
    { agentId: 'agent-current', inherited: true, workspaceId: 'workspace-current' },
    { agentId: undefined, inherited: true, workspaceId: undefined },
  ])('isolates dispatched identity ($agentId, inherited=$inherited)', async (params) => {
    for (const key of [
      'AGENT_ID',
      'TOPIC_ID',
      'OPERATION_ID',
      'ASSISTANT_MESSAGE_ID',
      'TASK_ID',
      'WORKSPACE_ID',
    ]) {
      vi.stubEnv(`LOBEHUB_${key}`, params.inherited ? `ancestor-${key}` : undefined);
    }

    await runHeteroTask({
      agentId: params.agentId,
      agentType,
      operationId: 'operation-current',
      prompt: 'hello',
      taskId: 'device-task-current',
      topicId: 'topic-current',
      workspaceId: params.workspaceId,
    });

    expect(spawnMock).toHaveBeenCalledTimes(1);
    const env = spawnMock.mock.calls[0][2].env;
    expect(env.LOBEHUB_AGENT_ID).toBe(params.agentId);
    expect(env.LOBEHUB_TOPIC_ID).toBe('topic-current');
    expect(env.LOBEHUB_OPERATION_ID).toBe('operation-current');
    expect(env.LOBEHUB_WORKSPACE_ID).toBe(params.workspaceId);
    expect(env.LOBEHUB_ASSISTANT_MESSAGE_ID).toBeUndefined();
    expect(env.LOBEHUB_TASK_ID).toBeUndefined();
  });
});

describe('runHeteroTask (openclaw)', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    // Clear task store
    for (const key of Object.keys(taskStore)) delete taskStore[key];
    execFileSyncMock.mockReturnValue('/usr/local/bin/lh\n');
    resetTrpcClientMock();
  });

  afterEach(() => {
    vi.unstubAllEnvs();
    vi.restoreAllMocks();
  });

  it('always injects buildNotifyProtocol into the prompt regardless of session history', async () => {
    const child = makeMockChild();
    spawnMock.mockReturnValue(child);

    await runHeteroTask({
      agentType: 'openclaw',
      operationId: 'op-1',
      prompt: 'what time is it',
      taskId: 'task-1',
      topicId: 'topic-1',
    });

    expect(spawnMock).toHaveBeenCalledTimes(1);
    const [, spawnArgs] = spawnMock.mock.calls[0] as [string, string[]];
    const msgIdx = spawnArgs.indexOf('--message');
    const messageArg = spawnArgs[msgIdx + 1];

    expect(messageArg).toContain('what time is it');
    expect(messageArg).toContain('lh notify');
    expect(messageArg).toContain('MSG_ID');
  });

  it.each([
    {
      environmentAgentId: 'ops-default',
      expectedAgentId: 'researcher',
      platformAgentId: ' researcher ',
    },
    {
      environmentAgentId: 'ops-default',
      expectedAgentId: 'ops-default',
      platformAgentId: undefined,
    },
    {
      environmentAgentId: 'ops-default',
      expectedAgentId: 'ops-default',
      platformAgentId: '   ',
    },
    { environmentAgentId: '', expectedAgentId: 'main', platformAgentId: undefined },
  ])(
    'selects OpenClaw agent $expectedAgentId from platform config before environment fallback',
    async ({ environmentAgentId, expectedAgentId, platformAgentId }) => {
      vi.stubEnv('OPENCLAW_AGENT_ID', environmentAgentId);
      spawnMock.mockReturnValue(makeMockChild());

      await runHeteroTask({
        agentType: 'openclaw',
        operationId: 'op-agent-selection',
        platformAgentId,
        prompt: 'hello',
        taskId: 'task-agent-selection',
        topicId: 'topic-agent-selection',
      });

      const [, spawnArgs] = spawnMock.mock.calls[0] as [string, string[]];
      expect(spawnArgs[spawnArgs.indexOf('--agent') + 1]).toBe(expectedAgentId);
    },
  );

  it('always injects protocol even on the second turn of the same session', async () => {
    const child1 = makeMockChild(1111);
    const child2 = makeMockChild(2222);
    spawnMock.mockReturnValueOnce(child1).mockReturnValueOnce(child2);

    // First turn
    await runHeteroTask({
      agentType: 'openclaw',
      operationId: 'op-1',
      prompt: 'hello',
      taskId: 'task-1',
      topicId: 'topic-1',
    });
    // Simulate process exit so task is removed
    child1._emit('close', 0, null);

    // Second turn (same topicId)
    await runHeteroTask({
      agentType: 'openclaw',
      operationId: 'op-2',
      prompt: 'follow up',
      taskId: 'task-2',
      topicId: 'topic-1',
    });

    expect(spawnMock).toHaveBeenCalledTimes(2);
    for (const call of spawnMock.mock.calls) {
      const args = call[1] as string[];
      const msg = args[args.indexOf('--message') + 1];
      expect(msg).toContain('lh notify');
    }
  });

  it('kills an existing concurrent process for the same topicId before spawning', async () => {
    const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);

    const child1 = makeMockChild(1111);
    spawnMock.mockReturnValueOnce(child1);
    await runHeteroTask({
      agentType: 'openclaw',
      operationId: 'op-1',
      prompt: 'msg1',
      taskId: 'task-1',
      topicId: 'topic-same',
    });
    // task-1 is still "running" (close not fired)

    const child2 = makeMockChild(2222);
    spawnMock.mockReturnValueOnce(child2);
    await runHeteroTask({
      agentType: 'openclaw',
      operationId: 'op-2',
      prompt: 'msg2',
      taskId: 'task-2',
      topicId: 'topic-same',
    });

    expect(killSpy).toHaveBeenCalledWith(1111, 'SIGTERM');
    expect(spawnMock).toHaveBeenCalledTimes(2);
  });

  it('isolates concurrent group members that share a topic', async () => {
    const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
    spawnMock.mockReturnValueOnce(makeMockChild(1111)).mockReturnValueOnce(makeMockChild(2222));

    await runHeteroTask({
      agentType: 'openclaw',
      operationId: 'op-child-1',
      parentOperationId: 'op-parent',
      prompt: 'member one',
      taskId: 'task-child-1',
      topicId: 'topic-shared',
    });
    await runHeteroTask({
      agentType: 'openclaw',
      operationId: 'op-child-2',
      parentOperationId: 'op-parent',
      prompt: 'member two',
      taskId: 'task-child-2',
      topicId: 'topic-shared',
    });

    expect(killSpy).not.toHaveBeenCalled();
    const firstArgs = spawnMock.mock.calls[0][1] as string[];
    const secondArgs = spawnMock.mock.calls[1][1] as string[];
    expect(firstArgs[firstArgs.indexOf('--session-id') + 1]).toBe('op-child-1');
    expect(secondArgs[secondArgs.indexOf('--session-id') + 1]).toBe('op-child-2');
    expect(saveTask).toHaveBeenLastCalledWith(
      expect.objectContaining({ parentOperationId: 'op-parent', taskId: 'task-child-2' }),
    );
  });

  it('does not kill processes for a different topicId', async () => {
    const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);

    const child1 = makeMockChild(3333);
    spawnMock.mockReturnValueOnce(child1);
    await runHeteroTask({
      agentType: 'openclaw',
      operationId: 'op-1',
      prompt: 'a',
      taskId: 'task-a',
      topicId: 'topic-A',
    });

    const child2 = makeMockChild(4444);
    spawnMock.mockReturnValueOnce(child2);
    await runHeteroTask({
      agentType: 'openclaw',
      operationId: 'op-2',
      prompt: 'b',
      taskId: 'task-b',
      topicId: 'topic-B',
    });

    expect(killSpy).not.toHaveBeenCalled();
  });

  it('saves task entry with correct fields after spawn', async () => {
    const child = makeMockChild(5555);
    spawnMock.mockReturnValue(child);

    await runHeteroTask({
      agentId: 'agent-1',
      agentType: 'openclaw',
      operationId: 'op-x',
      prompt: 'test',
      taskId: 'task-x',
      topicId: 'topic-x',
    });

    expect(saveTask).toHaveBeenCalledWith(
      expect.objectContaining({
        agentType: 'openclaw',
        pid: 5555,
        taskId: 'task-x',
        topicId: 'topic-x',
      }),
    );
  });

  it('passes --session-id and --agent args to openclaw', async () => {
    const child = makeMockChild();
    spawnMock.mockReturnValue(child);

    await runHeteroTask({
      agentType: 'openclaw',
      operationId: 'op-1',
      prompt: 'hello',
      taskId: 'task-1',
      topicId: 'my-topic-id',
    });

    const [, spawnArgs] = spawnMock.mock.calls[0] as [string, string[]];
    expect(spawnArgs).toContain('--session-id');
    expect(spawnArgs[spawnArgs.indexOf('--session-id') + 1]).toBe('my-topic-id');
    expect(spawnArgs).toContain('--agent');
    expect(spawnArgs).toContain('--local');
  });

  it('spawns the resolved OpenClaw executable with its recovered PATH', async () => {
    const child = makeMockChild();
    spawnMock.mockReturnValue(child);

    await runHeteroTask({
      agentType: 'openclaw',
      operationId: 'op-resolved',
      prompt: 'hello',
      taskId: 'task-resolved',
      topicId: 'topic-resolved',
    });

    expect(resolveRemotePlatformRuntimeMock).toHaveBeenCalledWith(
      'openclaw',
      expect.objectContaining({ LOBEHUB_OPERATION_ID: 'op-resolved' }),
    );
    expect(prepareSpawnMock).toHaveBeenCalledWith(
      'openclaw',
      expect.any(Array),
      expect.objectContaining({ LOBEHUB_OPERATION_ID: 'op-resolved' }),
    );
    expect(spawnMock).toHaveBeenCalledWith(
      '/resolved/bin/openclaw',
      expect.any(Array),
      expect.objectContaining({
        env: expect.objectContaining({ PATH: '/resolved/bin:/runtime/bin:/usr/bin' }),
      }),
    );
  });

  it('removes task and ignores already-exited process when killing concurrent task', async () => {
    const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => {
      throw new Error('No such process');
    });

    const child1 = makeMockChild(7777);
    spawnMock.mockReturnValueOnce(child1);
    await runHeteroTask({
      agentType: 'openclaw',
      operationId: 'op-1',
      prompt: 'msg1',
      taskId: 'task-1',
      topicId: 'topic-gone',
    });

    const child2 = makeMockChild(8888);
    spawnMock.mockReturnValueOnce(child2);
    // Should not throw even though kill fails
    await expect(
      runHeteroTask({
        agentType: 'openclaw',
        operationId: 'op-2',
        prompt: 'msg2',
        taskId: 'task-2',
        topicId: 'topic-gone',
      }),
    ).resolves.not.toThrow();

    expect(removeTask).toHaveBeenCalledWith('task-1');
    killSpy.mockRestore();
  });

  it('threads workspaceId into the saved task entry and the spawned child env', async () => {
    const child = makeMockChild(6666);
    spawnMock.mockReturnValue(child);

    await runHeteroTask({
      agentId: 'agent-ws',
      agentType: 'openclaw',
      operationId: 'op-ws',
      prompt: 'workspace dispatch',
      taskId: 'task-ws',
      topicId: 'topic-ws',
      workspaceId: 'ws-42',
    });

    expect(saveTask).toHaveBeenCalledWith(expect.objectContaining({ workspaceId: 'ws-42' }));

    const [, , spawnOpts] = spawnMock.mock.calls[0] as [
      string,
      string[],
      { env: NodeJS.ProcessEnv },
    ];
    expect(spawnOpts.env.LOBEHUB_OPERATION_ID).toBe('op-ws');
    expect(spawnOpts.env.LOBEHUB_WORKSPACE_ID).toBe('ws-42');
  });

  it('passes workspaceId to getTrpcClient when the close handler auto-notifies', async () => {
    const child = makeMockChild(7777);
    spawnMock.mockReturnValue(child);

    await runHeteroTask({
      agentId: 'agent-ws',
      agentType: 'openclaw',
      operationId: 'op-ws-2',
      prompt: 'ws prompt',
      taskId: 'task-ws-2',
      topicId: 'topic-ws-2',
      workspaceId: 'ws-99',
    });

    getTrpcClientMock.mockClear();
    // Abnormal exit triggers sendAutoNotify + sendDoneSignal β€” both must scope
    // to the dispatching workspace or agentNotify resolves the topic in
    // personal mode and 404s.
    child._emit('close', 1, null);
    // Await microtask drain so the close-handler promise chain settles.
    await new Promise((r) => setImmediate(r));

    expect(getTrpcClientMock.mock.calls.length).toBeGreaterThan(0);
    for (const call of getTrpcClientMock.mock.calls) {
      expect(call[0]).toBe('ws-99');
    }
  });

  it('reports a signal exit as a cancelled terminal signal', async () => {
    const child = makeMockChild(7788);
    spawnMock.mockReturnValue(child);

    await runHeteroTask({
      agentType: 'openclaw',
      operationId: 'op-cancelled',
      prompt: 'cancel me',
      taskId: 'task-cancelled',
      topicId: 'topic-cancelled',
    });

    child._emit('close', null, 'SIGINT');
    await new Promise((resolve) => setImmediate(resolve));

    expect(notifyMutateMock).toHaveBeenCalledWith(
      expect.objectContaining({
        cancelled: true,
        done: true,
        operationId: 'op-cancelled',
        role: 'assistant',
        topicId: 'topic-cancelled',
      }),
    );
  });
});

describe('runHeteroTask retry ownership', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    fsState.content = undefined;
    for (const key of Object.keys(taskStore)) delete taskStore[key];
    execFileSyncMock.mockReturnValue('/usr/local/bin/lh\n');
    resetTrpcClientMock();
  });

  afterEach(() => {
    vi.restoreAllMocks();
  });

  it.each(['openclaw', 'hermes'] as const)(
    'ignores the stale %s close callback after an exact task retry',
    async (agentType) => {
      const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
      const oldChild = makeMockChild(1111);
      const replacementChild = makeMockChild(2222);
      spawnMock.mockReturnValueOnce(oldChild).mockReturnValueOnce(replacementChild);

      await runHeteroTask({
        agentType,
        operationId: 'op-old',
        prompt: 'first attempt',
        taskId: 'task-retry',
        topicId: 'topic-retry',
      });
      await runHeteroTask({
        agentType,
        operationId: 'op-replacement',
        prompt: 'retry',
        taskId: 'task-retry',
        topicId: 'topic-retry',
      });

      expect(killSpy).toHaveBeenCalledWith(1111, 'SIGTERM');
      expect(taskStore['task-retry']).toEqual(expect.objectContaining({ pid: 2222 }));

      oldChild._emit('close', null, 'SIGTERM');
      await new Promise((resolve) => setImmediate(resolve));

      expect(taskStore['task-retry']).toEqual(expect.objectContaining({ pid: 2222 }));
      expect(getTrpcClientMock).not.toHaveBeenCalled();
      expect(notifyMutateMock).not.toHaveBeenCalled();
    },
  );
});

describe('runHeteroTask (hermes)', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    fsState.content = undefined;
    for (const key of Object.keys(taskStore)) delete taskStore[key];
    execFileSyncMock.mockReturnValue('/usr/local/bin/lh\n');
    resetTrpcClientMock();
  });

  afterEach(() => {
    vi.restoreAllMocks();
  });

  it('relays stdout intact and saves the final session id from stderr', async () => {
    const child = makeMockChild();
    spawnMock.mockReturnValue(child);

    await runHeteroTask({
      agentType: 'hermes',
      operationId: 'op-hermes-1',
      prompt: 'hello',
      taskId: 'task-hermes-1',
      topicId: 'topic-hermes',
    });

    const [, , spawnOptions] = spawnMock.mock.calls[0] as [string, string[], { stdio: string[] }];
    expect(spawnOptions.stdio).toEqual(['ignore', 'pipe', 'pipe']);

    child.stdout._emit('session_id: part of the final answer\nHello from Hermes\n');
    child.stderr._emit(
      'Resuming session metadata...\r\nsession_id: session-before-compaction\r\n' +
        'Context compacted\r\nsession_id: session-continuation\r\n',
    );
    child._emit('close', 0, null);
    await new Promise((resolve) => setImmediate(resolve));

    expect(notifyMutateMock).toHaveBeenCalledWith(
      expect.objectContaining({
        content: 'session_id: part of the final answer\nHello from Hermes',
        topicId: 'topic-hermes',
      }),
    );
    expect(JSON.parse(fsState.content!)).toEqual({
      'topic-hermes': 'session-continuation',
    });
  });

  it('spawns the resolved Hermes executable with its recovered PATH', async () => {
    const child = makeMockChild();
    spawnMock.mockReturnValue(child);

    await runHeteroTask({
      agentType: 'hermes',
      operationId: 'op-resolved',
      prompt: 'hello',
      taskId: 'task-resolved',
      topicId: 'topic-resolved',
    });

    expect(resolveRemotePlatformRuntimeMock).toHaveBeenCalledWith(
      'hermes',
      expect.objectContaining({ LOBEHUB_OPERATION_ID: 'op-resolved' }),
    );
    expect(prepareSpawnMock).toHaveBeenCalledWith(
      'hermes',
      ['chat', '--query', 'hello', '--quiet', '--accept-hooks'],
      expect.objectContaining({ LOBEHUB_OPERATION_ID: 'op-resolved' }),
    );
    expect(spawnMock).toHaveBeenCalledWith(
      '/resolved/bin/hermes',
      expect.any(Array),
      expect.objectContaining({
        env: expect.objectContaining({ PATH: '/resolved/bin:/runtime/bin:/usr/bin' }),
      }),
    );
  });

  it('resumes the saved session and replaces it with a continuation id', async () => {
    const firstChild = makeMockChild(1001);
    const secondChild = makeMockChild(1002);
    const thirdChild = makeMockChild(1003);
    spawnMock
      .mockReturnValueOnce(firstChild)
      .mockReturnValueOnce(secondChild)
      .mockReturnValueOnce(thirdChild);

    await runHeteroTask({
      agentType: 'hermes',
      operationId: 'op-1',
      prompt: 'remember this',
      taskId: 'task-1',
      topicId: 'topic-multi-turn',
    });
    firstChild.stderr._emit('session_id: session-a\n');
    firstChild._emit('close', 0, null);

    await runHeteroTask({
      agentType: 'hermes',
      operationId: 'op-2',
      prompt: 'what did I say?',
      taskId: 'task-2',
      topicId: 'topic-multi-turn',
    });
    expect(spawnMock.mock.calls[1][1]).toEqual([
      'chat',
      '--query',
      'what did I say?',
      '--quiet',
      '--accept-hooks',
      '--resume',
      'session-a',
    ]);

    secondChild.stderr._emit('session_id: session-continuation\n');
    secondChild._emit('close', 0, null);

    await runHeteroTask({
      agentType: 'hermes',
      operationId: 'op-3',
      prompt: 'continue',
      taskId: 'task-3',
      topicId: 'topic-multi-turn',
    });
    expect(spawnMock.mock.calls[2][1]).toContain('session-continuation');
  });

  it('still relays a successful response when stderr has no session id', async () => {
    const child = makeMockChild();
    spawnMock.mockReturnValue(child);

    await runHeteroTask({
      agentType: 'hermes',
      operationId: 'op-no-session',
      prompt: 'hello',
      taskId: 'task-no-session',
      topicId: 'topic-no-session',
    });
    child.stdout._emit('Successful response\n');
    child.stderr._emit('Provider diagnostic only\n');
    child._emit('close', 0, null);
    await new Promise((resolve) => setImmediate(resolve));

    expect(notifyMutateMock).toHaveBeenCalledWith(
      expect.objectContaining({ content: 'Successful response' }),
    );
    expect(fsState.content).toBeUndefined();
  });
});

// ─── cancelHeteroTask: process-group kill regression ───
// When a local CLI agent (devin/claude-code/codex/…) is dispatched through
// `lh connect`, the spawned child runs in its own process group. The cancel
// handler must signal the whole group (negative PID) so the CLI wrapper, the
// ACP client, and any agent subprocesses all receive the signal β€” not just
// the top-level node wrapper.

describe('cancelHeteroTask (process-group kill)', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    for (const key of Object.keys(taskStore)) delete taskStore[key];
    resetTrpcClientMock();
  });

  afterEach(() => {
    vi.restoreAllMocks();
  });

  it('signals the whole process group via negative PID on Unix', async () => {
    let groupAlive = true;
    const killSpy = vi.spyOn(process, 'kill').mockImplementation((_pid, signal) => {
      if (signal === 'SIGINT') groupAlive = false;
      if (signal === 0 && !groupAlive) {
        throw Object.assign(new Error('No such process'), { code: 'ESRCH' });
      }
      return true;
    });
    // Simulate a registered local CLI agent task.
    taskStore['op-cli-cancel'] = {
      agentType: 'devin',
      operationId: 'op-cli-cancel',
      pid: 4242,
      startedAt: new Date().toISOString(),
      taskId: 'op-cli-cancel',
      topicId: 'tpc-cli',
    };

    const result = await cancelHeteroTask({ signal: 'SIGINT', taskId: 'op-cli-cancel' });

    expect(killSpy).toHaveBeenCalledWith(-4242, 'SIGINT');
    expect(result).toEqual({
      exited: true,
      pid: 4242,
      signal: 'SIGINT',
      taskId: 'op-cli-cancel',
    });
    killSpy.mockRestore();
  });

  it('kills the persisted process tree with taskkill on Windows', async () => {
    vi.spyOn(process, 'platform', 'get').mockReturnValue('win32');
    let exitHandler: ((code: number) => void) | undefined;
    spawnMock.mockReturnValue({
      once: vi.fn((event: string, handler: (code: number) => void) => {
        if (event === 'exit') exitHandler = handler;
      }),
    });
    taskStore['op-windows-cancel'] = {
      agentType: 'codex',
      operationId: 'op-windows-cancel',
      pid: 4242,
      startedAt: new Date().toISOString(),
      taskId: 'op-windows-cancel',
      topicId: 'tpc-cli',
    };

    const cancellation = cancelHeteroTask({ signal: 'SIGINT', taskId: 'op-windows-cancel' });
    await vi.waitFor(() => expect(exitHandler).toBeDefined());
    exitHandler?.(0);

    await expect(cancellation).resolves.toEqual({
      exited: true,
      pid: 4242,
      signal: 'SIGINT',
      taskId: 'op-windows-cancel',
    });
    expect(spawnMock).toHaveBeenCalledWith('taskkill', ['/pid', '4242', '/T', '/F'], {
      stdio: 'ignore',
      windowsHide: true,
    });
  });

  it('still escalates after the wrapper exits and removes its registry entry', async () => {
    vi.useFakeTimers();
    let groupAlive = true;
    const killSpy = vi.spyOn(process, 'kill').mockImplementation((_pid, signal) => {
      if (signal === 'SIGKILL') groupAlive = false;
      if (signal === 0 && !groupAlive) {
        throw Object.assign(new Error('No such process'), { code: 'ESRCH' });
      }
      return true;
    });
    taskStore['op-cli-orphan'] = {
      agentType: 'devin',
      operationId: 'op-cli-orphan',
      pid: 4343,
      startedAt: new Date().toISOString(),
      taskId: 'op-cli-orphan',
      topicId: 'tpc-cli',
    };

    try {
      const cancellation = cancelHeteroTask({ signal: 'SIGINT', taskId: 'op-cli-orphan' });
      await Promise.resolve();
      removeTask('op-cli-orphan');
      await vi.advanceTimersByTimeAsync(2_000);
      const result = await cancellation;

      expect(killSpy).toHaveBeenCalledWith(-4343, 'SIGINT');
      expect(killSpy).toHaveBeenCalledWith(-4343, 'SIGKILL');
      expect(result).toEqual({
        exited: true,
        pid: 4343,
        signal: 'SIGINT',
        taskId: 'op-cli-orphan',
      });
    } finally {
      vi.useRealTimers();
    }
  });

  it('reports an unconfirmed cancellation when the group survives SIGKILL', async () => {
    vi.useFakeTimers();
    const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
    taskStore['op-cli-stuck'] = {
      agentType: 'codex',
      operationId: 'op-cli-stuck',
      pid: 4444,
      startedAt: new Date().toISOString(),
      taskId: 'op-cli-stuck',
      topicId: 'tpc-cli',
    };

    try {
      const cancellation = cancelHeteroTask({ signal: 'SIGINT', taskId: 'op-cli-stuck' });
      await vi.advanceTimersByTimeAsync(5_100);

      await expect(cancellation).resolves.toEqual({
        exited: false,
        pid: 4444,
        signal: 'SIGINT',
        taskId: 'op-cli-stuck',
      });
      expect(killSpy).toHaveBeenCalledWith(-4444, 'SIGKILL');
    } finally {
      vi.useRealTimers();
    }
  });

  it('returns No task found when the task is not registered', async () => {
    const result = await cancelHeteroTask({ signal: 'SIGINT', taskId: 'op-missing' });

    expect(result).toEqual({
      message: 'No task found with taskId: op-missing',
      success: false,
    });
  });

  it('cleans up the registry and notifies when the process already exited', async () => {
    const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => {
      throw Object.assign(new Error('No such process'), { code: 'ESRCH' });
    });
    taskStore['op-gone'] = {
      agentType: 'claude-code',
      operationId: 'op-gone',
      pid: 5555,
      startedAt: new Date().toISOString(),
      taskId: 'op-gone',
      topicId: 'tpc-gone',
    };

    const result = await cancelHeteroTask({ signal: 'SIGINT', taskId: 'op-gone' });

    expect(removeTask).toHaveBeenCalledWith('op-gone');
    expect(notifyMutateMock).toHaveBeenCalledWith(expect.objectContaining({ topicId: 'tpc-gone' }));
    expect(result).toEqual({
      exited: true,
      pid: 5555,
      signal: 'SIGINT',
      taskId: 'op-gone',
    });
    killSpy.mockRestore();
  });
});