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.

64.7 KB
Raw Blame
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';

import { Command } from 'commander';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { log } from '../utils/logger';
import { registerAgentCommand } from './agent';

const { mockTrpcClient } = vi.hoisted(() => ({
  mockTrpcClient: {
    agent: {
      createAgent: { mutate: vi.fn() },
      createAgentFiles: { mutate: vi.fn() },
      createAgentKnowledgeBase: { mutate: vi.fn() },
      deleteAgentFile: { mutate: vi.fn() },
      deleteAgentKnowledgeBase: { mutate: vi.fn() },
      duplicateAgent: { mutate: vi.fn() },
      getAgentConfigById: { query: vi.fn() },
      getBuiltinAgent: { query: vi.fn() },
      getKnowledgeBasesAndFiles: { query: vi.fn() },
      queryAgents: { query: vi.fn() },
      removeAgent: { mutate: vi.fn() },
      toggleFile: { mutate: vi.fn() },
      toggleKnowledgeBase: { mutate: vi.fn() },
      updateAgentConfig: { mutate: vi.fn() },
      updateAgentPinned: { mutate: vi.fn() },
    },
    agentDocument: {
      copyDocumentByPath: { mutate: vi.fn() },
      deleteDocumentByPath: { mutate: vi.fn() },
      deleteDocumentPermanentlyByPath: { mutate: vi.fn() },
      statDocumentByPath: { query: vi.fn() },
      listDocumentsByPath: { query: vi.fn() },
      listTrashDocumentsByPath: { query: vi.fn() },
      mkdirDocumentByPath: { mutate: vi.fn() },
      readDocumentByPath: { query: vi.fn() },
      renameDocumentByPath: { mutate: vi.fn() },
      restoreDocumentFromTrashByPath: { mutate: vi.fn() },
      writeDocumentByPath: { mutate: vi.fn() },
    },
    agentSkills: {
      createSkill: { mutate: vi.fn() },
      deleteSkill: { mutate: vi.fn() },
      updateSkill: { mutate: vi.fn() },
    },
    aiAgent: {
      execAgent: { mutate: vi.fn() },
      getOperationStatus: { query: vi.fn() },
      interruptTask: { mutate: vi.fn() },
    },
    device: {
      listDevices: { query: vi.fn() },
    },
    user: {
      getUserState: { query: vi.fn() },
    },
  },
}));

const { getTrpcClient: mockGetTrpcClient } = vi.hoisted(() => ({
  getTrpcClient: vi.fn(),
}));

const { mockFollowAgentRun, mockReplayAgentEvents } = vi.hoisted(() => ({
  mockFollowAgentRun: vi.fn(),
  mockReplayAgentEvents: vi.fn(),
}));

const { mockResolveLocalDeviceId } = vi.hoisted(() => ({
  mockResolveLocalDeviceId: vi.fn(),
}));

const { mockReadStdinText } = vi.hoisted(() => ({
  mockReadStdinText: vi.fn(),
}));

vi.mock('node:stream/consumers', () => ({ text: mockReadStdinText }));
vi.mock('../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));
vi.mock('../utils/agentStream', () => ({ replayAgentEvents: mockReplayAgentEvents }));
vi.mock('./agent/followRun', () => ({ followAgentRun: mockFollowAgentRun }));
vi.mock('../utils/device', () => ({ resolveLocalDeviceId: mockResolveLocalDeviceId }));
describe('agent command', () => {
  let exitSpy: ReturnType<typeof vi.spyOn>;
  let consoleSpy: ReturnType<typeof vi.spyOn>;
  let tempDir: string | undefined;

  beforeEach(() => {
    exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);
    consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
    mockGetTrpcClient.mockResolvedValue(mockTrpcClient);
    mockReplayAgentEvents.mockReset();
    mockFollowAgentRun.mockReset();
    mockFollowAgentRun.mockResolvedValue({ kind: 'completed', status: 'done' });
    mockResolveLocalDeviceId.mockReset();
    mockReadStdinText.mockReset();
    for (const method of Object.values(mockTrpcClient.agent)) {
      for (const fn of Object.values(method)) {
        (fn as ReturnType<typeof vi.fn>).mockReset();
      }
    }
    for (const method of Object.values(mockTrpcClient.agentDocument)) {
      for (const fn of Object.values(method)) {
        (fn as ReturnType<typeof vi.fn>).mockReset();
      }
    }
    for (const method of Object.values(mockTrpcClient.agentSkills)) {
      for (const fn of Object.values(method)) {
        (fn as ReturnType<typeof vi.fn>).mockReset();
      }
    }
    for (const method of Object.values(mockTrpcClient.aiAgent)) {
      for (const fn of Object.values(method)) {
        (fn as ReturnType<typeof vi.fn>).mockReset();
      }
    }
    for (const method of Object.values(mockTrpcClient.device)) {
      for (const fn of Object.values(method)) {
        (fn as ReturnType<typeof vi.fn>).mockReset();
      }
    }
    for (const method of Object.values(mockTrpcClient.user)) {
      for (const fn of Object.values(method)) {
        (fn as ReturnType<typeof vi.fn>).mockReset();
      }
    }
    // `lh agent run --no-headless` reads the saved tool approval mode from
    // user.getUserState before deciding what to send. After mockReset a bare
    // vi.fn() returns undefined and `undefined.query(...)` throws before the
    // CLI's own `.catch()` can absorb it, so default to "no saved setting".
    mockTrpcClient.user.getUserState.query.mockResolvedValue(undefined);
  });

  afterEach(async () => {
    exitSpy.mockRestore();
    consoleSpy.mockRestore();
    if (tempDir) {
      await rm(tempDir, { force: true, recursive: true });
      tempDir = undefined;
    }
  });

  function createProgram() {
    const program = new Command();
    program.exitOverride();
    registerAgentCommand(program);
    return program;
  }

  async function writeGraphFixture(graph: unknown) {
    tempDir = await mkdtemp(path.join(tmpdir(), 'lh-agent-graph-'));
    const graphFile = path.join(tempDir, 'graph.json');
    await writeFile(graphFile, JSON.stringify(graph), 'utf8');

    return graphFile;
  }

  describe('list', () => {
    it('should display agents in table format', async () => {
      mockTrpcClient.agent.queryAgents.query.mockResolvedValue([
        { id: 'a1', model: 'gpt-4', title: 'My Agent' },
      ]);

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'list']);

      expect(consoleSpy).toHaveBeenCalledTimes(2); // header + row
    });

    it('should filter by keyword', async () => {
      mockTrpcClient.agent.queryAgents.query.mockResolvedValue([]);

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'list', '-k', 'test']);

      expect(mockTrpcClient.agent.queryAgents.query).toHaveBeenCalledWith(
        expect.objectContaining({ keyword: 'test' }),
      );
    });

    it('opts the inbox into the lookup, unlike callers that leave the default', async () => {
      mockTrpcClient.agent.queryAgents.query.mockResolvedValue([]);

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'list']);

      // `queryAgents` excludes the product-owned inbox unless a caller opts in,
      // so `lh agent list` must ask for it explicitly — this is the surface the
      // inbox is meant to appear on.
      expect(mockTrpcClient.agent.queryAgents.query).toHaveBeenCalledWith(
        expect.objectContaining({ includeInbox: true }),
      );
    });

    it('should output JSON', async () => {
      const agents = [{ id: 'a1', title: 'Test' }];
      mockTrpcClient.agent.queryAgents.query.mockResolvedValue(agents);

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'list', '--json']);

      expect(consoleSpy.mock.calls[0][0]).toContain('"url": "https://app.lobehub.com/agent/a1"');
    });
  });

  describe('view', () => {
    it('should display agent config', async () => {
      mockTrpcClient.agent.getAgentConfigById.query.mockResolvedValue({
        model: 'gpt-4',
        systemRole: 'You are helpful.',
        title: 'Test Agent',
      });

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'view', 'a1']);

      expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Test Agent'));
    });

    it('should show name with the title as the supporting line', async () => {
      mockTrpcClient.agent.getAgentConfigById.query.mockResolvedValue({
        id: 'a1',
        name: 'Sienna',
        title: 'Lobe',
      });

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'view', 'a1']);

      expect(consoleSpy).toHaveBeenNthCalledWith(1, expect.stringContaining('Sienna'));
      expect(consoleSpy).toHaveBeenNthCalledWith(2, expect.stringContaining('Lobe'));
    });

    it('should not append an Untitled placeholder for a named agent without a title', async () => {
      mockTrpcClient.agent.getAgentConfigById.query.mockResolvedValue({
        id: 'a1',
        model: 'gpt-4',
        name: 'Alice',
      });

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'view', 'a1']);

      expect(consoleSpy).toHaveBeenNthCalledWith(1, expect.stringContaining('Alice'));
      expect(consoleSpy).not.toHaveBeenCalledWith(expect.stringContaining('Untitled'));
    });

    it('should exit when not found', async () => {
      mockTrpcClient.agent.getAgentConfigById.query.mockResolvedValue(null);

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'view', 'nonexistent']);

      expect(log.error).toHaveBeenCalledWith(expect.stringContaining('not found'));
      expect(exitSpy).toHaveBeenCalledWith(1);
    });

    it('should support --slug option', async () => {
      mockTrpcClient.agent.getBuiltinAgent.query.mockResolvedValue({
        id: 'resolved-id',
        model: 'gpt-4',
        title: 'Inbox Agent',
      });
      mockTrpcClient.agent.getAgentConfigById.query.mockResolvedValue({
        id: 'resolved-id',
        model: 'gpt-4',
        title: 'Inbox Agent',
      });

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'view', '--slug', 'inbox']);

      expect(mockTrpcClient.agent.getBuiltinAgent.query).toHaveBeenCalledWith({ slug: 'inbox' });
      expect(mockTrpcClient.agent.getAgentConfigById.query).toHaveBeenCalledWith({
        agentId: 'resolved-id',
      });
    });
  });

  describe('edit', () => {
    it('should update agent config', async () => {
      mockTrpcClient.agent.updateAgentConfig.mutate.mockResolvedValue({});

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'edit', 'a1', '--title', 'Updated']);

      expect(mockTrpcClient.agent.updateAgentConfig.mutate).toHaveBeenCalledWith({
        agentId: 'a1',
        value: { title: 'Updated' },
      });
    });

    it('should accept update as an alias of edit', async () => {
      mockTrpcClient.agent.updateAgentConfig.mutate.mockResolvedValue({});

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'update', 'a1', '--title', 'Updated']);

      expect(mockTrpcClient.agent.updateAgentConfig.mutate).toHaveBeenCalledWith({
        agentId: 'a1',
        value: { title: 'Updated' },
      });
    });

    it('should exit when no changes specified', async () => {
      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'edit', 'a1']);

      expect(log.error).toHaveBeenCalledWith(expect.stringContaining('No changes'));
      expect(exitSpy).toHaveBeenCalledWith(1);
    });

    it('should support --slug option', async () => {
      mockTrpcClient.agent.getBuiltinAgent.query.mockResolvedValue({
        id: 'resolved-id',
        title: 'Inbox Agent',
      });
      mockTrpcClient.agent.updateAgentConfig.mutate.mockResolvedValue({});

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'edit',
        '--slug',
        'inbox',
        '--model',
        'gemini-3-pro',
      ]);

      expect(mockTrpcClient.agent.getBuiltinAgent.query).toHaveBeenCalledWith({ slug: 'inbox' });
      expect(mockTrpcClient.agent.updateAgentConfig.mutate).toHaveBeenCalledWith({
        agentId: 'resolved-id',
        value: { model: 'gemini-3-pro' },
      });
    });

    it('should update graph config from a validated graph file', async () => {
      mockTrpcClient.agent.updateAgentConfig.mutate.mockResolvedValue({});
      const graph = {
        edges: [{ from: '__root__', instruction: 'Write the final answer.', to: 'answer' }],
        fields: {},
        name: 'answer-graph',
        nodes: { answer: { type: 'llm' } },
        terminal: 'answer',
      };
      const graphFile = await writeGraphFixture(graph);

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'edit',
        'a1',
        '--enable-graph',
        '--graph-file',
        graphFile,
      ]);

      expect(mockTrpcClient.agent.updateAgentConfig.mutate).toHaveBeenCalledWith({
        agentId: 'a1',
        value: {
          agencyConfig: {
            enableGraphMode: true,
            graph,
          },
        },
      });
    });

    it('should reject conflicting graph enable flags', async () => {
      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'edit',
        'a1',
        '--enable-graph',
        '--disable-graph',
      ]);

      expect(log.error).toHaveBeenCalledWith(
        'Use either --enable-graph or --disable-graph, not both.',
      );
      expect(exitSpy).toHaveBeenCalledWith(1);
      expect(mockTrpcClient.agent.updateAgentConfig.mutate).not.toHaveBeenCalled();
    });

    it('should reject invalid graph files before updating agent config', async () => {
      const graphFile = await writeGraphFixture({
        edges: [],
        fields: {},
        name: 'invalid-graph',
        nodes: { answer: { type: 'llm' } },
        terminal: 'answer',
      });

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'edit', 'a1', '--graph-file', graphFile]);

      expect(log.error).toHaveBeenCalledWith(
        expect.stringContaining('Failed to read graph JSON: Invalid AgentGraph'),
      );
      expect(exitSpy).toHaveBeenCalledWith(1);
      expect(mockTrpcClient.agent.updateAgentConfig.mutate).not.toHaveBeenCalled();
    });

    it('should merge agencyConfig from a JSON file, clearing a nested key with null', async () => {
      mockTrpcClient.agent.updateAgentConfig.mutate.mockResolvedValue({});
      // `null` (not undefined) so the server-side deep-merge drops the nested key.
      const agencyConfigFile = await writeGraphFixture({ heterogeneousProvider: null });

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'edit',
        'a1',
        '--agency-config-file',
        agencyConfigFile,
      ]);

      expect(mockTrpcClient.agent.updateAgentConfig.mutate).toHaveBeenCalledWith({
        agentId: 'a1',
        value: { agencyConfig: { heterogeneousProvider: null } },
      });
    });

    it('should merge a plain-object agencyConfig from a JSON file', async () => {
      mockTrpcClient.agent.updateAgentConfig.mutate.mockResolvedValue({});
      const agencyConfigFile = await writeGraphFixture({ executionTarget: 'none' });

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'edit',
        'a1',
        '--agency-config-file',
        agencyConfigFile,
      ]);

      expect(mockTrpcClient.agent.updateAgentConfig.mutate).toHaveBeenCalledWith({
        agentId: 'a1',
        value: { agencyConfig: { executionTarget: 'none' } },
      });
    });

    it('should reject a non-object agencyConfig file before updating', async () => {
      const agencyConfigFile = await writeGraphFixture(['not', 'an', 'object']);

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'edit',
        'a1',
        '--agency-config-file',
        agencyConfigFile,
      ]);

      expect(log.error).toHaveBeenCalledWith(
        expect.stringContaining('agencyConfig JSON must be a plain object'),
      );
      expect(exitSpy).toHaveBeenCalledWith(1);
      expect(mockTrpcClient.agent.updateAgentConfig.mutate).not.toHaveBeenCalled();
    });

    // The dedicated flags cover six fields; everything else an agent may want
    // to change about itself (opening message, tags, params, …) had no CLI
    // path, even though `agent.updateAgentConfig` is a passthrough server-side.
    it('should send arbitrary config fields from --config-file', async () => {
      mockTrpcClient.agent.updateAgentConfig.mutate.mockResolvedValue({});
      const configFile = await writeGraphFixture({
        openingMessage: 'Hi! Ask me about deploys.',
        tags: ['devops'],
      });

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'edit',
        'a1',
        '--config-file',
        configFile,
      ]);

      expect(mockTrpcClient.agent.updateAgentConfig.mutate).toHaveBeenCalledWith({
        agentId: 'a1',
        value: { openingMessage: 'Hi! Ask me about deploys.', tags: ['devops'] },
      });
    });

    it('should let explicit flags win over --config-file', async () => {
      mockTrpcClient.agent.updateAgentConfig.mutate.mockResolvedValue({});
      const configFile = await writeGraphFixture({
        description: 'from file',
        title: 'from file',
      });

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'edit',
        'a1',
        '--config-file',
        configFile,
        '--title',
        'from flag',
      ]);

      expect(mockTrpcClient.agent.updateAgentConfig.mutate).toHaveBeenCalledWith({
        agentId: 'a1',
        value: { description: 'from file', title: 'from flag' },
      });
    });

    it('should merge graph flags into an agencyConfig supplied by --config-file', async () => {
      mockTrpcClient.agent.updateAgentConfig.mutate.mockResolvedValue({});
      const configFile = await writeGraphFixture({
        agencyConfig: { modelSelectionPolicy: 'member' },
      });

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'edit',
        'a1',
        '--config-file',
        configFile,
        '--enable-graph',
      ]);

      expect(mockTrpcClient.agent.updateAgentConfig.mutate).toHaveBeenCalledWith({
        agentId: 'a1',
        value: { agencyConfig: { enableGraphMode: true, modelSelectionPolicy: 'member' } },
      });
    });

    it('should merge graph flags into an agencyConfig supplied by --agency-config-file', async () => {
      mockTrpcClient.agent.updateAgentConfig.mutate.mockResolvedValue({});
      const agencyConfigFile = await writeGraphFixture({
        executionTarget: 'local',
      });

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'edit',
        'a1',
        '--agency-config-file',
        agencyConfigFile,
        '--graph-file',
        await writeGraphFixture({
          edges: [{ from: '__root__', instruction: 'Write the final answer.', to: 'answer' }],
          fields: {},
          name: 'answer-graph',
          nodes: { answer: { type: 'llm' } },
          terminal: 'answer',
        }),
        '--enable-graph',
      ]);

      expect(mockTrpcClient.agent.updateAgentConfig.mutate).toHaveBeenCalledWith({
        agentId: 'a1',
        value: {
          agencyConfig: {
            executionTarget: 'local',
            enableGraphMode: true,
            graph: expect.any(Object),
          },
        },
      });
    });

    it('should reject a non-object --config-file before updating', async () => {
      const configFile = await writeGraphFixture(['not', 'an', 'object']);

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'edit',
        'a1',
        '--config-file',
        configFile,
      ]);

      expect(log.error).toHaveBeenCalledWith(
        expect.stringContaining('agent config JSON must be a plain object'),
      );
      expect(exitSpy).toHaveBeenCalledWith(1);
      expect(mockTrpcClient.agent.updateAgentConfig.mutate).not.toHaveBeenCalled();
    });

    // Without this the caller can only assume the write landed — which is
    // exactly how a silently mis-scoped edit goes unnoticed.
    it('should print the updated agent with --json', async () => {
      mockTrpcClient.agent.updateAgentConfig.mutate.mockResolvedValue({
        agent: { id: 'a1', title: 'Updated' },
        success: true,
      });

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'edit',
        'a1',
        '--title',
        'Updated',
        '--json',
      ]);

      expect(JSON.parse(consoleSpy.mock.calls[0][0])).toMatchObject({ id: 'a1', title: 'Updated' });
      expect(consoleSpy.mock.calls[0][0]).toContain('"url": "https://app.lobehub.com/agent/a1"');
    });
  });

  describe('delete', () => {
    it('should delete with --yes', async () => {
      mockTrpcClient.agent.removeAgent.mutate.mockResolvedValue({});

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'delete', 'a1', '--yes']);

      expect(mockTrpcClient.agent.removeAgent.mutate).toHaveBeenCalledWith({ agentId: 'a1' });
    });
  });

  describe('duplicate', () => {
    it('should duplicate an agent', async () => {
      mockTrpcClient.agent.duplicateAgent.mutate.mockResolvedValue({ agentId: 'a-dup' });

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'duplicate', 'a1', '--title', 'Copy']);

      expect(mockTrpcClient.agent.duplicateAgent.mutate).toHaveBeenCalledWith(
        expect.objectContaining({ agentId: 'a1', newTitle: 'Copy' }),
      );
    });
  });

  describe('run', () => {
    it('should exec agent and connect to the gateway WebSocket stream by default', async () => {
      mockTrpcClient.aiAgent.execAgent.mutate.mockResolvedValue({
        operationId: 'op-123',
        success: true,
        topicId: 'topic-1',
      });

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'run',
        '--agent-id',
        'a1',
        '--prompt',
        'Hello',
      ]);

      expect(mockTrpcClient.aiAgent.execAgent.mutate).toHaveBeenCalledWith(
        expect.objectContaining({ agentId: 'a1', prompt: 'Hello' }),
      );
      expect(mockFollowAgentRun).toHaveBeenCalledWith('op-123', {
        json: undefined,
        onStall: expect.any(Function),
        verbose: undefined,
      });
    });

    it('should support --slug option', async () => {
      mockTrpcClient.aiAgent.execAgent.mutate.mockResolvedValue({
        operationId: 'op-456',
        success: true,
      });

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'run',
        '--slug',
        'my-agent',
        '--prompt',
        'Do something',
      ]);

      expect(mockTrpcClient.aiAgent.execAgent.mutate).toHaveBeenCalledWith(
        expect.objectContaining({ slug: 'my-agent', prompt: 'Do something' }),
      );
    });

    it('should exit when neither --agent-id nor --slug provided', async () => {
      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'run', '--prompt', 'Hello']);

      expect(log.error).toHaveBeenCalledWith(expect.stringContaining('--agent-id or --slug'));
      expect(exitSpy).toHaveBeenCalledWith(1);
    });

    it('should exit when --prompt not provided', async () => {
      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'run', '--agent-id', 'a1']);

      expect(log.error).toHaveBeenCalledWith(expect.stringContaining('--prompt'));
      expect(exitSpy).toHaveBeenCalledWith(1);
    });

    it('should exit when exec fails', async () => {
      mockTrpcClient.aiAgent.execAgent.mutate.mockResolvedValue({
        error: 'Agent not found',
        success: false,
      });

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'run',
        '--agent-id',
        'bad',
        '--prompt',
        'Hi',
      ]);

      expect(log.error).toHaveBeenCalledWith(expect.stringContaining('Agent not found'));
      expect(exitSpy).toHaveBeenCalledWith(1);
    });

    it('should pass --topic-id as appContext', async () => {
      mockTrpcClient.aiAgent.execAgent.mutate.mockResolvedValue({
        operationId: 'op-789',
        success: true,
      });

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'run',
        '--agent-id',
        'a1',
        '--prompt',
        'Hi',
        '--topic-id',
        't1',
      ]);

      expect(mockTrpcClient.aiAgent.execAgent.mutate).toHaveBeenCalledWith(
        expect.objectContaining({ appContext: { topicId: 't1' } }),
      );
    });

    it('should pass --device local as deviceId', async () => {
      mockResolveLocalDeviceId.mockReturnValue('local-device-1');
      mockTrpcClient.device.listDevices.query.mockResolvedValue([
        { deviceId: 'local-device-1', online: true },
      ]);
      mockTrpcClient.aiAgent.execAgent.mutate.mockResolvedValue({
        operationId: 'op-device',
        success: true,
      });

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'run',
        '--agent-id',
        'a1',
        '--prompt',
        'Hi',
        '--device',
        'local',
      ]);

      expect(mockTrpcClient.aiAgent.execAgent.mutate).toHaveBeenCalledWith(
        expect.objectContaining({ agentId: 'a1', deviceId: 'local-device-1', prompt: 'Hi' }),
      );
    });

    it('should pass --topic-id and --device local together', async () => {
      mockResolveLocalDeviceId.mockReturnValue('local-device-1');
      mockTrpcClient.device.listDevices.query.mockResolvedValue([
        { deviceId: 'local-device-1', online: true },
      ]);
      mockTrpcClient.aiAgent.execAgent.mutate.mockResolvedValue({
        operationId: 'op-topic-device',
        success: true,
      });

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'run',
        '--agent-id',
        'a1',
        '--prompt',
        'Hi',
        '--topic-id',
        't1',
        '--device',
        'local',
      ]);

      expect(mockTrpcClient.aiAgent.execAgent.mutate).toHaveBeenCalledWith(
        expect.objectContaining({ appContext: { topicId: 't1' }, deviceId: 'local-device-1' }),
      );
    });

    it('should pass explicit --device id as deviceId', async () => {
      mockTrpcClient.device.listDevices.query.mockResolvedValue([
        { deviceId: 'device-remote-1', online: true },
      ]);
      mockTrpcClient.aiAgent.execAgent.mutate.mockResolvedValue({
        operationId: 'op-explicit-device',
        success: true,
      });

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'run',
        '--agent-id',
        'a1',
        '--prompt',
        'Hi',
        '--device',
        'device-remote-1',
      ]);

      expect(mockResolveLocalDeviceId).not.toHaveBeenCalled();
      expect(mockTrpcClient.aiAgent.execAgent.mutate).toHaveBeenCalledWith(
        expect.objectContaining({ agentId: 'a1', deviceId: 'device-remote-1', prompt: 'Hi' }),
      );
    });

    it('should exit when explicit device is not found', async () => {
      mockTrpcClient.device.listDevices.query.mockResolvedValue([
        { deviceId: 'other-device', online: true },
      ]);

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'run',
        '--agent-id',
        'a1',
        '--prompt',
        'Hi',
        '--device',
        'device-remote-1',
      ]);

      expect(log.error).toHaveBeenCalledWith(expect.stringContaining('was not found'));
      expect(exitSpy).toHaveBeenCalledWith(1);
    });

    it('should exit when local device cannot be resolved', async () => {
      mockResolveLocalDeviceId.mockReturnValue(undefined);

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'run',
        '--agent-id',
        'a1',
        '--prompt',
        'Hi',
        '--device',
        'local',
      ]);

      expect(log.error).toHaveBeenCalledWith(expect.stringContaining("Run 'lh connect' first"));
      expect(exitSpy).toHaveBeenCalledWith(1);
    });

    it('should exit when local device is offline', async () => {
      mockResolveLocalDeviceId.mockReturnValue('local-device-1');
      mockTrpcClient.device.listDevices.query.mockResolvedValue([
        { deviceId: 'local-device-1', online: false },
      ]);

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'run',
        '--agent-id',
        'a1',
        '--prompt',
        'Hi',
        '--device',
        'local',
      ]);

      expect(log.error).toHaveBeenCalledWith(expect.stringContaining('is not online'));
      expect(exitSpy).toHaveBeenCalledWith(1);
    });

    it('should exit when explicit device is offline', async () => {
      mockTrpcClient.device.listDevices.query.mockResolvedValue([
        { deviceId: 'device-remote-1', online: false },
      ]);

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'run',
        '--agent-id',
        'a1',
        '--prompt',
        'Hi',
        '--device',
        'device-remote-1',
      ]);

      expect(log.error).toHaveBeenCalledWith(expect.stringContaining('Bring it online'));
      expect(exitSpy).toHaveBeenCalledWith(1);
    });

    it('should pass --json to stream options', async () => {
      mockTrpcClient.aiAgent.execAgent.mutate.mockResolvedValue({
        operationId: 'op-j',
        success: true,
      });

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'run',
        '--agent-id',
        'a1',
        '--prompt',
        'Hi',
        '--json',
      ]);

      expect(mockFollowAgentRun).toHaveBeenCalledWith(
        'op-j',
        expect.objectContaining({ json: true }),
      );
    });
  });

  describe('pin/unpin', () => {
    it('should pin an agent', async () => {
      mockTrpcClient.agent.updateAgentPinned.mutate.mockResolvedValue({});

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'pin', 'a1']);

      expect(mockTrpcClient.agent.updateAgentPinned.mutate).toHaveBeenCalledWith({
        id: 'a1',
        pinned: true,
      });
    });

    it('should unpin an agent', async () => {
      mockTrpcClient.agent.updateAgentPinned.mutate.mockResolvedValue({});

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'unpin', 'a1']);

      expect(mockTrpcClient.agent.updateAgentPinned.mutate).toHaveBeenCalledWith({
        id: 'a1',
        pinned: false,
      });
    });
  });

  describe('kb-files', () => {
    it('should list kb and files', async () => {
      mockTrpcClient.agent.getKnowledgeBasesAndFiles.query.mockResolvedValue([
        { enabled: true, id: 'f1', name: 'file.txt', type: 'file' },
      ]);

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'kb-files', 'a1']);

      expect(mockTrpcClient.agent.getKnowledgeBasesAndFiles.query).toHaveBeenCalledWith({
        agentId: 'a1',
      });
    });

    it('should show empty message', async () => {
      mockTrpcClient.agent.getKnowledgeBasesAndFiles.query.mockResolvedValue([]);

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'kb-files', 'a1']);

      expect(consoleSpy).toHaveBeenCalledWith('No knowledge bases or files found.');
    });
  });

  describe('add-file', () => {
    it('should add files to agent', async () => {
      mockTrpcClient.agent.createAgentFiles.mutate.mockResolvedValue({});

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'add-file', 'a1', '--file-ids', 'f1,f2']);

      expect(mockTrpcClient.agent.createAgentFiles.mutate).toHaveBeenCalledWith(
        expect.objectContaining({ agentId: 'a1', fileIds: ['f1', 'f2'] }),
      );
    });
  });

  describe('remove-file', () => {
    it('should remove a file from agent', async () => {
      mockTrpcClient.agent.deleteAgentFile.mutate.mockResolvedValue({});

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'remove-file', 'a1', '--file-id', 'f1']);

      expect(mockTrpcClient.agent.deleteAgentFile.mutate).toHaveBeenCalledWith({
        agentId: 'a1',
        fileId: 'f1',
      });
    });
  });

  describe('toggle-file', () => {
    it('should toggle file with enable', async () => {
      mockTrpcClient.agent.toggleFile.mutate.mockResolvedValue({});

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'toggle-file',
        'a1',
        '--file-id',
        'f1',
        '--enable',
      ]);

      expect(mockTrpcClient.agent.toggleFile.mutate).toHaveBeenCalledWith({
        agentId: 'a1',
        enabled: true,
        fileId: 'f1',
      });
    });
  });

  describe('add-kb', () => {
    it('should add kb to agent', async () => {
      mockTrpcClient.agent.createAgentKnowledgeBase.mutate.mockResolvedValue({});

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'add-kb', 'a1', '--kb-id', 'kb1']);

      expect(mockTrpcClient.agent.createAgentKnowledgeBase.mutate).toHaveBeenCalledWith(
        expect.objectContaining({ agentId: 'a1', knowledgeBaseId: 'kb1' }),
      );
    });
  });

  describe('remove-kb', () => {
    it('should remove kb from agent', async () => {
      mockTrpcClient.agent.deleteAgentKnowledgeBase.mutate.mockResolvedValue({});

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'remove-kb', 'a1', '--kb-id', 'kb1']);

      expect(mockTrpcClient.agent.deleteAgentKnowledgeBase.mutate).toHaveBeenCalledWith({
        agentId: 'a1',
        knowledgeBaseId: 'kb1',
      });
    });
  });

  describe('toggle-kb', () => {
    it('should toggle kb with disable', async () => {
      mockTrpcClient.agent.toggleKnowledgeBase.mutate.mockResolvedValue({});

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'toggle-kb',
        'a1',
        '--kb-id',
        'kb1',
        '--disable',
      ]);

      expect(mockTrpcClient.agent.toggleKnowledgeBase.mutate).toHaveBeenCalledWith({
        agentId: 'a1',
        enabled: false,
        knowledgeBaseId: 'kb1',
      });
    });
  });

  describe('run outcome and exit status (#19543 #19613 #19614 #19615)', () => {
    let errorSpy: ReturnType<typeof vi.spyOn>;
    let warnSpy: ReturnType<typeof vi.spyOn>;
    let infoSpy: ReturnType<typeof vi.spyOn>;
    let stderrSpy: ReturnType<typeof vi.spyOn>;

    const envelope = (status: string, extra: Record<string, unknown> = {}) => ({
      currentState: { status, stepCount: 3, ...extra },
      hasError: status === 'error',
      isActive: !['done', 'error', 'interrupted'].includes(status),
      isCompleted: ['done', 'error', 'interrupted'].includes(status),
      metadata: {},
      needsHumanInput: status === 'waiting_for_human',
      operationId: 'op-run',
      stats: { totalSteps: 3 },
    });

    const run = async (...extra: string[]) => {
      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'run',
        '--agent-id',
        'a1',
        '--prompt',
        'Hello',
        ...extra,
      ]);
    };

    /** Let the poll loop advance through its sleeps under fake timers. */
    const runWithTimers = async (ms: number, ...extra: string[]) => {
      const done = run(...extra);
      await vi.advanceTimersByTimeAsync(ms);
      await done;
    };

    const allOutput = () =>
      [
        ...consoleSpy.mock.calls,
        ...errorSpy.mock.calls,
        ...warnSpy.mock.calls,
        ...infoSpy.mock.calls,
      ]
        .map((c) => String(c[0]))
        .join('\n');

    beforeEach(() => {
      process.exitCode = undefined;
      errorSpy = vi.spyOn(log, 'error').mockImplementation(() => {});
      warnSpy = vi.spyOn(log, 'warn').mockImplementation(() => {});
      infoSpy = vi.spyOn(log, 'info').mockImplementation(() => {});
      stderrSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
      mockTrpcClient.aiAgent.execAgent.mutate.mockResolvedValue({
        operationId: 'op-run',
        success: true,
        topicId: 'topic-1',
      });
    });

    afterEach(() => {
      vi.useRealTimers();
      process.exitCode = undefined;
      errorSpy.mockRestore();
      warnSpy.mockRestore();
      infoSpy.mockRestore();
      stderrSpy.mockRestore();
    });

    // ── #19613: live-stream completion ────────────────────────────

    it('exits 0 when the stream reports the run done', async () => {
      mockFollowAgentRun.mockResolvedValue({ kind: 'completed', status: 'done' });
      await run();
      expect(process.exitCode).toBeUndefined();
      expect(exitSpy).not.toHaveBeenCalled();
    });

    it.each([
      ['waiting_for_human', 2],
      ['failed', 1],
      ['interrupted', 1],
    ] as const)('exits %s → %i from the WebSocket stream', async (kind, code) => {
      mockFollowAgentRun.mockResolvedValue({ kind, status: kind });
      await run();
      expect(process.exitCode).toBe(code);
    });

    it('exits 2 for a run parked on human approval over WebSocket, in --json mode too', async () => {
      mockFollowAgentRun.mockResolvedValue({
        kind: 'waiting_for_human',
        status: 'waiting_for_human',
      });
      await run('--json', '--no-headless');
      expect(process.exitCode).toBe(2);
    });

    it('a WebSocket stream that cannot be opened falls back to polling the run outcome', async () => {
      mockFollowAgentRun.mockRejectedValue(new Error('Agent stream failed: 502 Bad Gateway'));
      mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValue(envelope('done'));

      await run();

      expect(mockTrpcClient.aiAgent.getOperationStatus.query).toHaveBeenCalled();
      expect(exitSpy).not.toHaveBeenCalled();
      expect(process.exitCode).toBeUndefined();
    });

    it.each([
      [{ kind: 'completed', status: 'done' }, undefined],
      [{ kind: 'failed', status: 'error' }, 1],
      [{ kind: 'interrupted', status: 'interrupted' }, 1],
      [{ kind: 'waiting_for_human', status: 'waiting_for_human' }, 2],
      [undefined, 3],
    ] as const)('--replay of a recording ending in %o exits %s', async (outcome, code) => {
      const dir = await mkdtemp(path.join(tmpdir(), 'lh-agent-replay-'));
      const file = path.join(dir, 'events.json');
      await writeFile(file, '[]');
      mockReplayAgentEvents.mockReturnValue(outcome);

      try {
        const program = createProgram();
        await program.parseAsync(['node', 'test', 'agent', 'run', '--replay', file, '--json']);
      } finally {
        await rm(dir, { force: true, recursive: true });
      }

      expect(process.exitCode).toBe(code);
    });

    it('documents the exit status contract and the parked-run behaviour in --help', () => {
      const program = createProgram();
      const runCmd = program.commands
        .find((c) => c.name() === 'agent')!
        .commands.find((c) => c.name() === 'run')!;
      let help = '';
      runCmd.configureOutput({ writeOut: (s) => (help += s) });
      runCmd.outputHelp();
      expect(help).toContain('2  the run is paused waiting for human approval');
      // commander wraps option descriptions; compare with whitespace collapsed
      expect(help.replaceAll(/\s+/g, ' ')).toContain('does not wait for that approval');
    });

    // ── #19543: polling fallback reads the real envelope ──────────

    it('polls the envelope the server returns and stops on currentState.status=done', async () => {
      vi.useFakeTimers();
      mockFollowAgentRun.mockRejectedValue(
        new Error('Agent gateway WebSocket failed: [object ErrorEvent]'),
      );
      mockTrpcClient.aiAgent.getOperationStatus.query
        .mockResolvedValueOnce(envelope('idle'))
        .mockResolvedValueOnce(envelope('done'));

      await runWithTimers(20_000);

      expect(mockTrpcClient.aiAgent.getOperationStatus.query).toHaveBeenCalledTimes(2);
      expect(process.exitCode).toBeUndefined();
      expect(allOutput()).toContain('Agent finished');
    });

    it('falls back to the envelope summary flags when there is no status string', async () => {
      mockFollowAgentRun.mockRejectedValue(new Error('ws down'));
      mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValue({
        hasError: false,
        isCompleted: true,
      });
      await run();
      expect(process.exitCode).toBeUndefined();
    });

    it('gives up loudly with exit 3 on an answer whose status it cannot read', async () => {
      vi.useFakeTimers();
      mockFollowAgentRun.mockRejectedValue(new Error('ws down'));
      mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValue({ foo: 1 });

      await runWithTimers(60_000);

      expect(mockTrpcClient.aiAgent.getOperationStatus.query).toHaveBeenCalledTimes(3);
      expect(process.exitCode).toBe(3);
      expect(allOutput()).toContain('Could not read a run status');
    });

    // ── #19614: failure statuses and missing results are not success ──

    it.each([
      ['error', 1],
      ['interrupted', 1],
      ['waiting_for_human', 2],
    ] as const)('poll ending in %s exits %i', async (status, code) => {
      mockFollowAgentRun.mockRejectedValue(new Error('ws down'));
      mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValue(
        envelope(status, status === 'error' ? { error: 'model quota exceeded' } : {}),
      );
      await run();
      expect(process.exitCode).toBe(code);
      expect(allOutput()).not.toContain('Agent finished');
      if (status === 'error') expect(allOutput()).toContain('model quota exceeded');
    });

    it.each(['failed', 'cancelled', 'aborted'])(
      'legacy flat status %s is not reported as success',
      async (status) => {
        mockFollowAgentRun.mockRejectedValue(new Error('ws down'));
        mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValue({ status });
        await run();
        expect(process.exitCode).toBe(1);
      },
    );

    it('a missing status result exits 3 without claiming the run finished or expired', async () => {
      mockFollowAgentRun.mockRejectedValue(new Error('ws down'));
      mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValue(null);
      await run();
      expect(process.exitCode).toBe(3);
      const out = allOutput();
      expect(out).not.toContain('finished (or expired)');
      expect(out).not.toContain('Agent finished');
      expect(out).toContain('outcome cannot be confirmed');
    });

    // ── #19615: timeouts must not cut off an active run ───────────

    it('--json no longer throws on a dropped stream; it polls the run to its end', async () => {
      vi.useFakeTimers();
      mockFollowAgentRun.mockRejectedValue(
        new Error('Agent gateway WebSocket sent no progress for 60s; status check failed: x'),
      );
      mockTrpcClient.aiAgent.getOperationStatus.query
        .mockResolvedValueOnce(envelope('running'))
        .mockResolvedValueOnce(envelope('running'))
        .mockResolvedValueOnce(envelope('done'));

      await runWithTimers(30_000, '--json');

      expect(mockTrpcClient.aiAgent.getOperationStatus.query).toHaveBeenCalledTimes(3);
      expect(process.exitCode).toBeUndefined();
      // progress lines stay off stdout so the --json array is not corrupted
      expect(consoleSpy.mock.calls.flat().join('\n')).not.toContain('Run status');
    });

    it('the WebSocket quiet-window probe keeps waiting on an active run instead of failing it', async () => {
      mockFollowAgentRun.mockImplementation(async (_operationId: string, opts: any) => {
        mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValueOnce(envelope('running'));
        expect(await opts.onStall()).toBeUndefined(); // active → keep streaming
        mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValueOnce(
          envelope('waiting_for_human'),
        );
        return opts.onStall();
      });

      await run('--json');

      expect(process.exitCode).toBe(2);
    });

    it('bounds an in-flight status request that never answers', async () => {
      vi.useFakeTimers();
      mockFollowAgentRun.mockRejectedValue(new Error('ws down'));
      mockTrpcClient.aiAgent.getOperationStatus.query
        .mockImplementationOnce(() => new Promise(() => {})) // hangs
        .mockResolvedValueOnce(envelope('done'));

      await runWithTimers(45_000);

      const [, opts] = mockTrpcClient.aiAgent.getOperationStatus.query.mock.calls[0];
      expect(opts.signal.aborted).toBe(true);
      expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('no answer within 30s'));
      expect(process.exitCode).toBeUndefined();
    });

    it('stops after repeated failed status requests with exit 3, not success', async () => {
      vi.useFakeTimers();
      mockFollowAgentRun.mockRejectedValue(new Error('ws down'));
      mockTrpcClient.aiAgent.getOperationStatus.query.mockRejectedValue(new Error('ECONNRESET'));

      await runWithTimers(60_000);

      expect(mockTrpcClient.aiAgent.getOperationStatus.query).toHaveBeenCalledTimes(3);
      expect(process.exitCode).toBe(3);
    });

    it('--timeout stops waiting with exit 3 and points at lh agent status', async () => {
      vi.useFakeTimers();
      mockFollowAgentRun.mockImplementation(() => new Promise(() => {}));

      await runWithTimers(5_000, '--timeout', '5');

      expect(exitSpy).toHaveBeenCalledWith(3);
      expect(allOutput()).toContain('lh agent status op-run');
    });

    it('waits on an active run indefinitely by default (no built-in deadline)', async () => {
      vi.useFakeTimers();
      mockFollowAgentRun.mockRejectedValue(new Error('ws down'));
      mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValue(envelope('running'));

      const done = vi.fn();
      void run().then(done);
      await vi.advanceTimersByTimeAsync(3 * 60 * 60_000); // 3h of a busy run

      expect(done).not.toHaveBeenCalled();
      expect(exitSpy).not.toHaveBeenCalled();
      expect(process.exitCode).toBeUndefined();
    });
  });

  describe('status', () => {
    it('should display operation status', async () => {
      mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValue({
        cost: { total: 0.0042 },
        status: 'completed',
        stepCount: 3,
        usage: { total_tokens: 1500 },
      });

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'status', 'op-123']);

      expect(mockTrpcClient.aiAgent.getOperationStatus.query).toHaveBeenCalledWith(
        expect.objectContaining({ operationId: 'op-123' }),
      );
      expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Operation Status'));
    });

    it('reads the envelope getOperationStatus actually returns (#19543)', async () => {
      mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValue({
        currentState: {
          cost: { total: 0.0042 },
          error: 'boom',
          status: 'error',
          stepCount: 3,
          usage: { total_tokens: 1500 },
        },
        hasError: true,
        isCompleted: true,
      });

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'status', 'op-123']);

      const out = consoleSpy.mock.calls.map((c: unknown[]) => String(c[0])).join('\n');
      expect(out).toContain('error');
      expect(out).not.toContain('unknown');
      expect(out).toContain('Steps:  3');
      expect(out).toContain('Tokens: 1500');
      expect(out).toContain('Cost:   $0.0042');
      expect(out).toContain('boom');
    });

    it('should output JSON', async () => {
      const data = { status: 'completed', stepCount: 2 };
      mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValue(data);

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'status', 'op-123', '--json']);

      expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify(data, null, 2));
    });

    it('should pass --history flag', async () => {
      mockTrpcClient.aiAgent.getOperationStatus.query.mockResolvedValue({ status: 'running' });

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'status', 'op-123', '--history']);

      expect(mockTrpcClient.aiAgent.getOperationStatus.query).toHaveBeenCalledWith(
        expect.objectContaining({ includeHistory: true, operationId: 'op-123' }),
      );
    });
  });

  describe('interrupt', () => {
    it('should interrupt an operation by id', async () => {
      mockTrpcClient.aiAgent.interruptTask.mutate.mockResolvedValue({
        operationId: 'op-123',
        success: true,
      });

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'interrupt', '--operation-id', 'op-123']);

      expect(mockTrpcClient.aiAgent.interruptTask.mutate).toHaveBeenCalledWith({
        operationId: 'op-123',
      });
      expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Interrupted'));
    });

    it('should interrupt by thread id alone (server resolves the operation)', async () => {
      mockTrpcClient.aiAgent.interruptTask.mutate.mockResolvedValue({
        operationId: 'op-123',
        success: true,
        threadId: 'thd-1',
      });

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'interrupt', '--thread-id', 'thd-1']);

      expect(mockTrpcClient.aiAgent.interruptTask.mutate).toHaveBeenCalledWith({
        threadId: 'thd-1',
      });
      expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Interrupted'));
    });

    it('should require at least one of --operation-id or --thread-id', async () => {
      const program = createProgram();

      await expect(program.parseAsync(['node', 'test', 'agent', 'interrupt'])).rejects.toThrow(
        'Either --thread-id or --operation-id must be provided',
      );
      expect(mockTrpcClient.aiAgent.interruptTask.mutate).not.toHaveBeenCalled();
    });

    it('should pass optional topic and thread ids through', async () => {
      mockTrpcClient.aiAgent.interruptTask.mutate.mockResolvedValue({ success: true });

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'interrupt',
        '--operation-id',
        'op-123',
        '--topic-id',
        'tpc-1',
        '--thread-id',
        'thd-1',
      ]);

      expect(mockTrpcClient.aiAgent.interruptTask.mutate).toHaveBeenCalledWith({
        operationId: 'op-123',
        threadId: 'thd-1',
        topicId: 'tpc-1',
      });
    });

    it('should warn when the interrupt is not acknowledged', async () => {
      mockTrpcClient.aiAgent.interruptTask.mutate.mockResolvedValue({
        operationId: 'op-123',
        success: false,
      });

      const program = createProgram();
      await program.parseAsync(['node', 'test', 'agent', 'interrupt', '--operation-id', 'op-123']);

      expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('not acknowledged'));
    });
  });

  describe('fs', () => {
    it('should list VFS entries from the unified agent root alias', async () => {
      mockTrpcClient.agentDocument.listDocumentsByPath.query.mockResolvedValue([
        {
          mode: 8,
          mount: { driver: 'synthetic', source: 'virtual' },
          name: 'writer',
          path: './lobe',
          type: 'directory',
        },
      ]);

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'space',
        'fs',
        'ls',
        '--agent-id',
        'a1',
        'agent:/',
        '--json',
      ]);

      expect(mockTrpcClient.agentDocument.listDocumentsByPath.query).toHaveBeenCalledWith({
        agentId: 'a1',
        cursor: undefined,
        limit: undefined,
        path: './',
        topicId: undefined,
      });
      expect(consoleSpy).toHaveBeenCalledWith(
        JSON.stringify(
          [
            {
              mode: 8,
              mount: { driver: 'synthetic', source: 'virtual' },
              name: 'writer',
              path: './lobe',
              type: 'directory',
            },
          ],
          null,
          2,
        ),
      );
    });

    it('should pass pagination options to VFS ls', async () => {
      mockTrpcClient.agentDocument.listDocumentsByPath.query.mockResolvedValue([]);

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'space',
        'fs',
        'ls',
        '--agent-id',
        'a1',
        '--cursor',
        '100',
        '--limit',
        '25',
        'agent:/notes',
      ]);

      expect(mockTrpcClient.agentDocument.listDocumentsByPath.query).toHaveBeenCalledWith({
        agentId: 'a1',
        cursor: '100',
        limit: 25,
        path: './notes',
        topicId: undefined,
      });
    });

    it('should print unix-like long listings with ls -la', async () => {
      mockTrpcClient.agentDocument.listDocumentsByPath.query.mockResolvedValue([
        {
          mode: 14,
          name: '.config',
          path: './notes/.config',
          size: 0,
          type: 'directory',
          updatedAt: '2026-04-27T07:18:00',
        },
        {
          mode: 6,
          name: 'SOUL.md',
          path: './notes/SOUL.md',
          size: 399,
          type: 'file',
          updatedAt: '2026-04-27T07:19:00',
        },
      ]);

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'space',
        'fs',
        'ls',
        '-la',
        '--agent-id',
        'a1',
        'agent:/notes',
      ]);

      expect(consoleSpy).toHaveBeenNthCalledWith(1, 'total 1');
      expect(consoleSpy).toHaveBeenNthCalledWith(
        2,
        expect.stringMatching(/^dr-x------ {2}1 agent {2}agent {4}0 --- -- --:-- \.$/),
      );
      expect(consoleSpy).toHaveBeenNthCalledWith(
        3,
        expect.stringMatching(/^dr-x------ {2}1 agent {2}agent {4}0 --- -- --:-- \.\.$/),
      );
      expect(consoleSpy).toHaveBeenNthCalledWith(
        4,
        expect.stringMatching(/^drwx------ {2}1 agent {2}agent {4}0 Apr 27 07:18 \.config\/$/),
      );
      expect(consoleSpy).toHaveBeenNthCalledWith(
        5,
        expect.stringMatching(/^-rw------- {2}1 agent {2}agent {2}399 Apr 27 07:19 SOUL\.md$/),
      );
    });

    it('should expose VFS commands through agent space fs', async () => {
      mockTrpcClient.agentDocument.listDocumentsByPath.query.mockResolvedValue([]);

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'space',
        'fs',
        'ls',
        '--agent-id',
        'a1',
        'agent:/notes',
      ]);

      expect(mockTrpcClient.agentDocument.listDocumentsByPath.query).toHaveBeenCalledWith({
        agentId: 'a1',
        cursor: undefined,
        limit: undefined,
        path: './notes',
        topicId: undefined,
      });
    });

    it('should collect tree traversal warnings instead of failing the whole tree', async () => {
      mockTrpcClient.agentDocument.listDocumentsByPath.query
        .mockResolvedValueOnce([
          {
            mode: 8,
            name: 'builtin',
            path: './lobe/skills/builtin',
            type: 'directory',
          },
        ])
        .mockRejectedValueOnce(new Error('Failed to list builtin skills'));

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'space',
        'fs',
        'tree',
        '--agent-id',
        'a1',
        'agent:/lobe/skills',
      ]);

      expect(mockTrpcClient.agentDocument.listDocumentsByPath.query).toHaveBeenNthCalledWith(1, {
        agentId: 'a1',
        path: './lobe/skills',
        topicId: undefined,
      });
      expect(mockTrpcClient.agentDocument.listDocumentsByPath.query).toHaveBeenNthCalledWith(2, {
        agentId: 'a1',
        path: './lobe/skills/builtin',
        topicId: undefined,
      });
      expect(log.warn).toHaveBeenCalledWith('./lobe/skills/builtin: Failed to list builtin skills');
    });

    it('should read SKILL.md when cat targets a skill directory alias', async () => {
      const stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true);
      mockTrpcClient.agentDocument.statDocumentByPath.query.mockResolvedValue({
        content: '# Writer',
        mode: 2,
        mount: { driver: 'skills', namespace: 'builtin', source: 'builtin' },
        name: 'SKILL.md',
        path: './lobe/skills/builtin/skills/writer/SKILL.md',
        type: 'file',
      });
      mockTrpcClient.agentDocument.readDocumentByPath.query.mockResolvedValue({
        content: '# Writer',
        contentType: 'text/markdown',
        path: './lobe/skills/builtin/skills/writer/SKILL.md',
      });

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'space',
        'fs',
        'cat',
        '--agent-id',
        'a1',
        'builtin:/writer',
      ]);

      expect(mockTrpcClient.agentDocument.statDocumentByPath.query).toHaveBeenCalledWith({
        agentId: 'a1',
        path: './lobe/skills/builtin/skills/writer/SKILL.md',
        topicId: undefined,
      });
      expect(mockTrpcClient.agentDocument.readDocumentByPath.query).toHaveBeenCalledWith({
        agentId: 'a1',
        path: './lobe/skills/builtin/skills/writer/SKILL.md',
        topicId: undefined,
      });
      expect(stdoutSpy).toHaveBeenCalledWith('# Writer');
      stdoutSpy.mockRestore();
    });

    it('should create a writable skill through touch when the path does not exist', async () => {
      mockTrpcClient.agentDocument.statDocumentByPath.query.mockRejectedValue({
        data: { code: 'NOT_FOUND' },
      });
      mockTrpcClient.agentDocument.writeDocumentByPath.mutate.mockResolvedValue({
        path: './lobe/skills/agent/skills/writer/SKILL.md',
      });

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'space',
        'fs',
        'touch',
        '--agent-id',
        'a1',
        'skills:/writer',
        '--content',
        '# Writer',
      ]);

      expect(mockTrpcClient.agentDocument.writeDocumentByPath.mutate).toHaveBeenCalledWith({
        agentId: 'a1',
        content: '# Writer',
        createMode: 'if-missing',
        path: './lobe/skills/agent/skills/writer',
        topicId: undefined,
      });
    });

    it('should create directories through the generic mkdir path API', async () => {
      mockTrpcClient.agentDocument.mkdirDocumentByPath.mutate.mockResolvedValue({
        path: './notes/archive',
      });

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'space',
        'fs',
        'mkdir',
        '--agent-id',
        'a1',
        '--parents',
        'agent:/notes/archive',
      ]);

      expect(mockTrpcClient.agentDocument.mkdirDocumentByPath.mutate).toHaveBeenCalledWith({
        agentId: 'a1',
        path: './notes/archive',
        recursive: true,
        topicId: undefined,
      });
    });

    it('should stat unified root paths', async () => {
      mockTrpcClient.agentDocument.statDocumentByPath.query.mockResolvedValue({
        mode: 8,
        name: 'lobe',
        path: './lobe',
        type: 'directory',
      });

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'space',
        'fs',
        'stat',
        '--agent-id',
        'a1',
        'agent:/lobe',
        '--json',
      ]);

      expect(mockTrpcClient.agentDocument.statDocumentByPath.query).toHaveBeenCalledWith({
        agentId: 'a1',
        path: './lobe',
        topicId: undefined,
      });
    });

    it('should copy paths through the generic copyDocumentByPath API', async () => {
      mockTrpcClient.agentDocument.copyDocumentByPath.mutate.mockResolvedValue({
        path: './notes/published.md',
      });

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'space',
        'fs',
        'cp',
        '--agent-id',
        'a1',
        '--force',
        'agent:/notes/draft.md',
        'agent:/notes/published.md',
      ]);

      expect(mockTrpcClient.agentDocument.copyDocumentByPath.mutate).toHaveBeenCalledWith({
        agentId: 'a1',
        force: true,
        fromPath: './notes/draft.md',
        toPath: './notes/published.md',
        topicId: undefined,
      });
    });

    it('should rename paths through the generic renameDocumentByPath API', async () => {
      mockTrpcClient.agentDocument.renameDocumentByPath.mutate.mockResolvedValue({
        path: './notes/final.md',
      });

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'space',
        'fs',
        'mv',
        '--agent-id',
        'a1',
        'agent:/notes/draft.md',
        'agent:/notes/final.md',
      ]);

      expect(mockTrpcClient.agentDocument.renameDocumentByPath.mutate).toHaveBeenCalledWith({
        agentId: 'a1',
        force: undefined,
        fromPath: './notes/draft.md',
        toPath: './notes/final.md',
        topicId: undefined,
      });
    });

    it('should soft-delete paths through the generic deleteDocumentByPath API', async () => {
      mockTrpcClient.agentDocument.deleteDocumentByPath.mutate.mockResolvedValue({});

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'space',
        'fs',
        'rm',
        '--agent-id',
        'a1',
        '--yes',
        '--recursive',
        'agent:/notes',
      ]);

      expect(mockTrpcClient.agentDocument.deleteDocumentByPath.mutate).toHaveBeenCalledWith({
        agentId: 'a1',
        force: undefined,
        path: './notes',
        recursive: true,
        topicId: undefined,
      });
    });

    it('should list trash through the generic trash path API', async () => {
      mockTrpcClient.agentDocument.listTrashDocumentsByPath.query.mockResolvedValue([
        { path: './notes/deleted.md' },
      ]);

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'space',
        'fs',
        'trash',
        'ls',
        '--agent-id',
        'a1',
        'agent:/notes',
      ]);

      expect(mockTrpcClient.agentDocument.listTrashDocumentsByPath.query).toHaveBeenCalledWith({
        agentId: 'a1',
        path: './notes',
        topicId: undefined,
      });
      expect(consoleSpy).toHaveBeenCalledWith('agent:/notes/deleted.md');
    });

    it('should restore trash entries through the generic trash restore API', async () => {
      mockTrpcClient.agentDocument.restoreDocumentFromTrashByPath.mutate.mockResolvedValue({
        path: './notes/deleted.md',
      });

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'space',
        'fs',
        'trash',
        'restore',
        '--agent-id',
        'a1',
        'agent:/notes/deleted.md',
      ]);

      expect(
        mockTrpcClient.agentDocument.restoreDocumentFromTrashByPath.mutate,
      ).toHaveBeenCalledWith({
        agentId: 'a1',
        path: './notes/deleted.md',
        topicId: undefined,
      });
    });

    it('should permanently delete trash entries through the generic trash rm API', async () => {
      mockTrpcClient.agentDocument.deleteDocumentPermanentlyByPath.mutate.mockResolvedValue({});

      const program = createProgram();
      await program.parseAsync([
        'node',
        'test',
        'agent',
        'space',
        'fs',
        'trash',
        'rm',
        '--agent-id',
        'a1',
        '--yes',
        '--force',
        'agent:/notes/deleted.md',
      ]);

      expect(
        mockTrpcClient.agentDocument.deleteDocumentPermanentlyByPath.mutate,
      ).toHaveBeenCalledWith({
        agentId: 'a1',
        force: true,
        path: './notes/deleted.md',
        recursive: undefined,
        topicId: undefined,
      });
    });
  });
});