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.

20.7 KB
Raw Blame
import { act } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { type ConversationContext, type ConversationHooks } from '../../../types';
import { createStore } from '../../index';
import type { PendingIntervention } from '../data/pendingInterventions';
import { dataSelectors } from '../data/selectors';

// Mock dependencies
const mockApproveToolCalling = vi.fn();
const mockRejectToolCalling = vi.fn();
const mockRejectAndContinueToolCalling = vi.fn();
const mockSubmitHeteroIntervention = vi.fn();
const mockApproveAllToolCalls = vi.fn();
const mockAddToolToAllowList = vi.fn();

vi.mock('@/store/chat', () => ({
  useChatStore: {
    getState: vi.fn(() => ({
      dbMessagesMap: {},
      messagesMap: {},
      operations: {},
      approveToolCalling: mockApproveToolCalling,
      approveAllToolCalls: mockApproveAllToolCalls,
      rejectToolCalling: mockRejectToolCalling,
      rejectAndContinueToolCalling: mockRejectAndContinueToolCalling,
      submitHeteroIntervention: mockSubmitHeteroIntervention,
      cancelOperations: vi.fn(),
      cancelOperation: vi.fn(),
      deleteMessage: vi.fn(),
      modifyMessageContent: vi.fn(),
      copyMessage: vi.fn(),
      toggleMessageEditing: vi.fn(),
      regenerateUserMessage: vi.fn(),
      regenerateAssistantMessage: vi.fn(),
      continueGenerationMessage: vi.fn(),
      optimisticCreateMessage: vi.fn(),
    })),
    setState: vi.fn(),
  },
}));

vi.mock('@/store/user', () => ({
  useUserStore: { getState: () => ({ addToolToAllowList: mockAddToolToAllowList }) },
}));

vi.mock('@/store/chat/selectors', () => ({
  displayMessageSelectors: {
    lastDisplayMessageId: vi.fn(() => 'last-msg-id'),
    getDisplayMessagesByKey: vi.fn(() => () => []),
    findLastMessageId: vi.fn(() => () => 'parent-id'),
    getDisplayMessageById: vi.fn(() => () => ({ content: 'original content' })),
  },
  dbMessageSelectors: {
    dbUserFiles: vi.fn(() => []),
  },
}));

vi.mock('@/services/message', () => ({
  messageService: {
    createMessage: vi.fn(),
    getMessages: vi.fn().mockResolvedValue([]),
    updateMessage: vi.fn().mockResolvedValue({ success: true, messages: [] }),
    updateMessageMetadata: vi.fn().mockResolvedValue({ success: true, messages: [] }),
    updateMessagePlugin: vi.fn().mockResolvedValue({ success: true, messages: [] }),
    removeMessage: vi.fn().mockResolvedValue({ success: true, messages: [] }),
    removeMessages: vi.fn().mockResolvedValue({ success: true, messages: [] }),
    removeMessagesByAssistant: vi.fn(),
    updateMessagePluginArguments: vi.fn(),
  },
}));

const chatContext = (): ConversationContext => ({
  agentId: 'session-1',
  topicId: null,
  threadId: null,
});

const builderContext = (): ConversationContext => ({
  agentId: 'builder-agent',
  topicId: 'builder-topic',
  threadId: 'builder-thread',
  scope: 'agent_builder',
});

describe('Tool Actions', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

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

  describe('approveToolCall', () => {
    it('should pass entire context object to ChatStore.approveToolCalling', async () => {
      const context: ConversationContext = chatContext();

      const store = createStore({ context });

      await act(async () => {
        await store.getState().approveToolCall('tool-call-1', 'group-1');
      });

      // Verify context is passed as third argument
      expect(mockApproveToolCalling).toHaveBeenCalledWith('tool-call-1', 'group-1', context);
    });

    it('should pass agent_builder scope context correctly', async () => {
      const context: ConversationContext = builderContext();

      const store = createStore({ context });

      await act(async () => {
        await store.getState().approveToolCall('tool-call-1', 'group-1');
      });

      // Verify entire context object is passed (including scope)
      expect(mockApproveToolCalling).toHaveBeenCalledWith('tool-call-1', 'group-1', context);
    });

    it('should call onToolApproved hook before approval', async () => {
      const onToolApproved = vi.fn().mockResolvedValue(true);
      const context: ConversationContext = chatContext();
      const hooks: ConversationHooks = { onToolApproved };

      const store = createStore({ context, hooks });

      await act(async () => {
        await store.getState().approveToolCall('tool-call-1', 'group-1');
      });

      expect(onToolApproved).toHaveBeenCalledWith('tool-call-1');
      expect(mockApproveToolCalling).toHaveBeenCalledWith('tool-call-1', 'group-1', context);
    });

    it('should respect onToolApproved hook returning false', async () => {
      const onToolApproved = vi.fn().mockResolvedValue(false);
      const context: ConversationContext = chatContext();
      const hooks: ConversationHooks = { onToolApproved };

      const store = createStore({ context, hooks });

      await act(async () => {
        await store.getState().approveToolCall('tool-call-1', 'group-1');
      });

      expect(onToolApproved).toHaveBeenCalledWith('tool-call-1');
      expect(mockApproveToolCalling).not.toHaveBeenCalled();
    });

    it('should call onToolCallComplete hook after approval', async () => {
      const onToolCallComplete = vi.fn();
      const context: ConversationContext = chatContext();
      const hooks: ConversationHooks = { onToolCallComplete };

      const store = createStore({ context, hooks });

      await act(async () => {
        await store.getState().approveToolCall('tool-call-1', 'group-1');
      });

      expect(onToolCallComplete).toHaveBeenCalledWith('tool-call-1', undefined);
    });
  });

  it('writes legacy-fallback edits without loading the still-pending server rows', async () => {
    const context: ConversationContext = { agentId: 'session-1', topicId: null, threadId: null };
    const store = createStore({ context });
    const updatePluginArguments = vi.fn().mockResolvedValue(undefined);
    act(() => {
      store.setState({
        dbMessages: [{ id: 'tool-msg-1', role: 'tool', tool_call_id: 'call-1' } as any],
        updatePluginArguments,
      });
    });

    await act(async () => {
      await store
        .getState()
        .approveToolCall('tool-msg-1', 'group-1', { editedArguments: { path: 'edited' } });
    });
    const [, , , options] = mockApproveToolCalling.mock.calls[0];
    await options.onLegacyEditFallback();

    expect(updatePluginArguments).toHaveBeenCalledWith('call-1', { path: 'edited' }, true, {
      refresh: false,
    });
  });

  describe('submitHeteroIntervention', () => {
    it('should pass this conversation context to ChatStore, not fall back to global activeTopicId', async () => {
      // Regression: the hetero path used to call the chat store directly with no
      // context, so optimistic writes / topic-status flip landed on whatever
      // topic the user was viewing (global activeTopicId) instead of the card's.
      const context: ConversationContext = {
        agentId: 'agent-1',
        topicId: 'card-topic',
        threadId: null,
      };

      const store = createStore({ context });

      await act(async () => {
        await store.getState().submitHeteroIntervention('tool-msg-1', 'submit', { answer: 'ok' });
      });

      expect(mockSubmitHeteroIntervention).toHaveBeenCalledWith(
        'tool-msg-1',
        'submit',
        { answer: 'ok' },
        context,
      );
    });

    it('should forward skip / cancel action types with context', async () => {
      const context: ConversationContext = {
        agentId: 'agent-2',
        topicId: 'card-topic-2',
        threadId: null,
      };

      const store = createStore({ context });

      await act(async () => {
        await store.getState().submitHeteroIntervention('tool-msg-2', 'skip');
      });

      expect(mockSubmitHeteroIntervention).toHaveBeenCalledWith(
        'tool-msg-2',
        'skip',
        undefined,
        context,
      );
    });
  });

  describe('rejectToolCall', () => {
    it('should call onToolRejected hook before rejection', async () => {
      const onToolRejected = vi.fn().mockResolvedValue(true);
      const context: ConversationContext = chatContext();
      const hooks: ConversationHooks = { onToolRejected };

      const store = createStore({ context, hooks });

      await act(async () => {
        await store.getState().rejectToolCall('tool-call-1', 'Reason');
      });

      expect(onToolRejected).toHaveBeenCalledWith('tool-call-1', 'Reason');
    });

    it('should respect onToolRejected hook returning false', async () => {
      const onToolRejected = vi.fn().mockResolvedValue(false);
      const context: ConversationContext = chatContext();
      const hooks: ConversationHooks = { onToolRejected };

      const store = createStore({ context, hooks });

      await act(async () => {
        await store.getState().rejectToolCall('tool-call-1', 'Reason');
      });

      expect(onToolRejected).toHaveBeenCalledWith('tool-call-1', 'Reason');
      expect(mockRejectToolCalling).not.toHaveBeenCalled();
    });

    it('should delegate to ChatStore.rejectToolCalling with context', async () => {
      const context: ConversationContext = chatContext();

      const store = createStore({ context });

      await act(async () => {
        await store.getState().rejectToolCall('tool-call-1', 'Reason');
      });

      expect(mockRejectToolCalling).toHaveBeenCalledWith('tool-call-1', 'Reason', context);
    });

    it('should pass agent_builder scope context correctly', async () => {
      const context: ConversationContext = builderContext();

      const store = createStore({ context });

      await act(async () => {
        await store.getState().rejectToolCall('tool-call-1', 'Reason');
      });

      expect(mockRejectToolCalling).toHaveBeenCalledWith('tool-call-1', 'Reason', context);
    });
  });

  describe('rejectAndContinueToolCall', () => {
    it('should pass entire context object to ChatStore.rejectAndContinueToolCalling', async () => {
      const context: ConversationContext = chatContext();

      const store = createStore({ context });

      await act(async () => {
        await store.getState().rejectAndContinueToolCall('tool-call-1', 'Reason');
      });

      // Verify context is passed as third argument
      expect(mockRejectAndContinueToolCalling).toHaveBeenCalledWith(
        'tool-call-1',
        'Reason',
        context,
      );
    });

    it('should pass agent_builder scope context correctly', async () => {
      const context: ConversationContext = builderContext();

      const store = createStore({ context });

      await act(async () => {
        await store.getState().rejectAndContinueToolCall('tool-call-1', 'User rejected');
      });

      // Verify entire context object is passed (including scope)
      expect(mockRejectAndContinueToolCalling).toHaveBeenCalledWith(
        'tool-call-1',
        'User rejected',
        context,
      );
    });

    it('should pass context with undefined reason', async () => {
      const context: ConversationContext = {
        agentId: 'builder-agent',
        topicId: null,
        threadId: null,
      };

      const store = createStore({ context });

      await act(async () => {
        await store.getState().rejectAndContinueToolCall('tool-call-1');
      });

      // Verify context is passed even with undefined reason
      expect(mockRejectAndContinueToolCalling).toHaveBeenCalledWith(
        'tool-call-1',
        undefined,
        context,
      );
    });

    it('should NOT also call ChatStore.rejectToolCalling (avoid double-dispatch with rejected_continue)', async () => {
      const context: ConversationContext = chatContext();

      const store = createStore({ context });

      await act(async () => {
        await store.getState().rejectAndContinueToolCall('tool-call-1', 'Reason');
      });

      // Only the continue variant should fire. If `rejectToolCalling` also
      // fires, Gateway mode would kick off a halting `decision='rejected'`
      // resume op before the `decision='rejected_continue'` one and race
      // two resume ops on the same tool_call_id.
      expect(mockRejectAndContinueToolCalling).toHaveBeenCalledTimes(1);
      expect(mockRejectToolCalling).not.toHaveBeenCalled();
    });

    it('should still fire the onToolRejected hook', async () => {
      const onToolRejected = vi.fn().mockResolvedValue(true);
      const context: ConversationContext = chatContext();
      const hooks: ConversationHooks = { onToolRejected };

      const store = createStore({ context, hooks });

      await act(async () => {
        await store.getState().rejectAndContinueToolCall('tool-call-1', 'Reason');
      });

      expect(onToolRejected).toHaveBeenCalledWith('tool-call-1', 'Reason');
      expect(mockRejectAndContinueToolCalling).toHaveBeenCalledWith(
        'tool-call-1',
        'Reason',
        context,
      );
    });

    it('should respect onToolRejected hook returning false and skip the continue call', async () => {
      const onToolRejected = vi.fn().mockResolvedValue(false);
      const context: ConversationContext = chatContext();
      const hooks: ConversationHooks = { onToolRejected };

      const store = createStore({ context, hooks });

      await act(async () => {
        await store.getState().rejectAndContinueToolCall('tool-call-1', 'Reason');
      });

      expect(onToolRejected).toHaveBeenCalledWith('tool-call-1', 'Reason');
      expect(mockRejectAndContinueToolCalling).not.toHaveBeenCalled();
    });
  });

  describe('waitForPendingArgsUpdate integration', () => {
    it('approveToolCall should wait for pending args update before proceeding', async () => {
      const context: ConversationContext = chatContext();

      const store = createStore({ context });

      // Manually set a pending promise in the store
      let resolvePending: () => void;
      const pendingPromise = new Promise<void>((resolve) => {
        resolvePending = resolve;
      });

      act(() => {
        store.setState({
          pendingArgsUpdates: new Map([['tool-call-1', pendingPromise]]),
        });
      });

      // Start approve (should wait for pending promise)
      let approveFinished = false;
      const approveAction = act(async () => {
        await store.getState().approveToolCall('tool-call-1', 'group-1');
        approveFinished = true;
      });

      // Give time for approve to start waiting
      await new Promise((resolve) => setTimeout(resolve, 10));

      // Approve should not have finished yet (waiting for pending promise)
      expect(approveFinished).toBe(false);
      expect(mockApproveToolCalling).not.toHaveBeenCalled();

      // Resolve the pending promise
      resolvePending!();
      await approveAction;

      // Now approve should have finished
      expect(approveFinished).toBe(true);
      expect(mockApproveToolCalling).toHaveBeenCalledWith('tool-call-1', 'group-1', context);
    });

    it('rejectToolCall should wait for pending args update before proceeding', async () => {
      const onToolRejected = vi.fn().mockResolvedValue(true);
      const context: ConversationContext = chatContext();
      const hooks: ConversationHooks = { onToolRejected };

      const store = createStore({ context, hooks });

      // Manually set a pending promise in the store
      let resolvePending: () => void;
      const pendingPromise = new Promise<void>((resolve) => {
        resolvePending = resolve;
      });

      act(() => {
        store.setState({
          pendingArgsUpdates: new Map([['tool-call-1', pendingPromise]]),
        });
      });

      // Start reject (should wait for pending promise)
      let rejectFinished = false;
      const rejectAction = act(async () => {
        await store.getState().rejectToolCall('tool-call-1', 'Reason');
        rejectFinished = true;
      });

      // Give time for reject to start waiting
      await new Promise((resolve) => setTimeout(resolve, 10));

      // Reject should not have finished yet (waiting for pending promise)
      expect(rejectFinished).toBe(false);
      expect(onToolRejected).not.toHaveBeenCalled();

      // Resolve the pending promise
      resolvePending!();
      await rejectAction;

      // Now reject should have finished
      expect(rejectFinished).toBe(true);
      expect(onToolRejected).toHaveBeenCalledWith('tool-call-1', 'Reason');
    });

    it('rejectAndContinueToolCall should wait for pending args update before proceeding', async () => {
      const context: ConversationContext = chatContext();

      const store = createStore({ context });

      // Manually set a pending promise in the store
      let resolvePending: () => void;
      const pendingPromise = new Promise<void>((resolve) => {
        resolvePending = resolve;
      });

      act(() => {
        store.setState({
          pendingArgsUpdates: new Map([['tool-call-1', pendingPromise]]),
        });
      });

      // Start rejectAndContinue (should wait for pending promise)
      let rejectFinished = false;
      const rejectAction = act(async () => {
        await store.getState().rejectAndContinueToolCall('tool-call-1', 'Reason');
        rejectFinished = true;
      });

      // Give time for reject to start waiting
      await new Promise((resolve) => setTimeout(resolve, 10));

      // RejectAndContinue should not have finished yet (waiting for pending promise)
      expect(rejectFinished).toBe(false);
      expect(mockRejectAndContinueToolCalling).not.toHaveBeenCalled();

      // Resolve the pending promise
      resolvePending!();
      await rejectAction;

      // Now rejectAndContinue should have finished
      expect(rejectFinished).toBe(true);
      expect(mockRejectAndContinueToolCalling).toHaveBeenCalledWith(
        'tool-call-1',
        'Reason',
        context,
      );
    });
  });

  describe('approveToolCallAndCovered', () => {
    const context: ConversationContext = { agentId: 'agent', topicId: 'topic' };
    const pending = (
      toolMessageId: string,
      apiName = 'dryRunWidget',
      batchId = 'batch-1',
    ): PendingIntervention =>
      ({
        apiName,
        batchId,
        identifier: 'builtin-dashboard',
        operationId: 'op-1',
        requestArgs: JSON.stringify({ versionId: toolMessageId }),
        toolCallId: `call-${toolMessageId}`,
        toolMessageId,
      }) as PendingIntervention;

    const withPending = (items: PendingIntervention[]) =>
      vi.spyOn(dataSelectors, 'pendingInterventions').mockReturnValue(items);

    it('approves siblings the remember now covers together with the card, in one batch', async () => {
      withPending([pending('tool-a'), pending('tool-b'), pending('tool-c', 'requestPublish')]);
      const store = createStore({ context });
      const isCovered = vi.fn(async () => true);

      await act(async () => {
        await store.getState().approveToolCallAndCovered('tool-a', 'group-1', { isCovered });
      });

      // Only the same tool's calls are re-checked; another API in the batch still asks.
      expect(isCovered).toHaveBeenCalledTimes(1);
      expect(mockApproveAllToolCalls).toHaveBeenCalledWith(['tool-a', 'tool-b'], context);
      expect(mockApproveToolCalling).not.toHaveBeenCalled();
    });

    it('approves the card alone when no sibling is covered', async () => {
      withPending([pending('tool-a'), pending('tool-b')]);
      const store = createStore({ context });

      await act(async () => {
        await store.getState().approveToolCallAndCovered('tool-a', 'group-1', {
          isCovered: async () => false,
          rememberToolKey: 'builtin-dashboard/dryRunWidget',
        });
      });

      expect(mockApproveAllToolCalls).not.toHaveBeenCalled();
      expect(mockApproveToolCalling).toHaveBeenCalledWith('tool-a', 'group-1', context, {
        editedArguments: undefined,
        rememberToolKey: 'builtin-dashboard/dryRunWidget',
      });
    });

    it('writes the allow-list itself when siblings ride along on the batch approval', async () => {
      withPending([pending('tool-a'), pending('tool-b')]);
      const store = createStore({ context });

      await act(async () => {
        await store.getState().approveToolCallAndCovered('tool-a', 'group-1', {
          isCovered: async () => true,
          rememberToolKey: 'builtin-dashboard/dryRunWidget',
        });
      });

      expect(mockAddToolToAllowList).toHaveBeenCalledWith('builtin-dashboard/dryRunWidget');
      expect(mockApproveAllToolCalls).toHaveBeenCalledWith(['tool-a', 'tool-b'], context);
    });

    it('never reaches into another batch', async () => {
      withPending([pending('tool-a'), pending('tool-b', 'dryRunWidget', 'batch-2')]);
      const store = createStore({ context });
      const isCovered = vi.fn(async () => true);

      await act(async () => {
        await store.getState().approveToolCallAndCovered('tool-a', 'group-1', { isCovered });
      });

      expect(isCovered).not.toHaveBeenCalled();
      expect(mockApproveToolCalling).toHaveBeenCalled();
    });
  });
});