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.

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

import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';
import { type AgentStoreState } from '@/store/agent/initialState';
import { initialAgentSliceState } from '@/store/agent/slices/agent/initialState';
import { initialAgentArtworkSliceState } from '@/store/agent/slices/artwork/initialState';
import { initialBuiltinAgentSliceState } from '@/store/agent/slices/builtin/initialState';

import { agentByIdSelectors } from './agentByIdSelectors';

// getAgentWorkingDirectoryById is desktop-only; force the desktop branch on.
vi.mock('@lobechat/const', async (importOriginal) => ({
  ...(await importOriginal()),
  isDesktop: true,
}));

const createState = (overrides: Partial<AgentStoreState> = {}): AgentStoreState => ({
  ...initialAgentArtworkSliceState,
  ...initialAgentSliceState,
  ...initialBuiltinAgentSliceState,
  ...overrides,
});

describe('agentByIdSelectors', () => {
  describe('getAgentBuilderContextById', () => {
    it('should return builder context from existing agent config', () => {
      const state = createState({
        agentMap: {
          'agent-1': {
            chatConfig: { historyCount: 6 },
            model: 'gpt-4o',
            plugins: ['search'],
            provider: 'openai',
            systemRole: 'You are a helper',
          },
        },
      });

      const context = agentByIdSelectors.getAgentBuilderContextById('agent-1')(state);

      expect(context.config).toMatchObject({
        chatConfig: { historyCount: 6 },
        model: 'gpt-4o',
        plugins: ['search'],
        provider: 'openai',
        systemRole: 'You are a helper',
      });
    });

    it('should not throw when agent config is missing', () => {
      const state = createState({ agentMap: {} });

      expect(() =>
        agentByIdSelectors.getAgentBuilderContextById('missing-agent')(state),
      ).not.toThrow();

      const context = agentByIdSelectors.getAgentBuilderContextById('missing-agent')(state);

      expect(context.config).toMatchObject({
        chatConfig: undefined,
        model: undefined,
        // getActivePluginIds always normalizes to an array, even for a
        // missing/undefined raw plugins field.
        plugins: [],
        provider: undefined,
        systemRole: undefined,
      });
    });

    it('excludes disabled entries from the builder context plugins, in a mixed-shape array', () => {
      const state = createState({
        agentMap: {
          'agent-1': {
            model: 'gpt-4o',
            plugins: ['search', { identifier: 'lobe-web-browsing', mode: 'disabled' }],
            provider: 'openai',
            systemRole: 'You are a helper',
          } as any,
        },
      });

      const context = agentByIdSelectors.getAgentBuilderContextById('agent-1')(state);

      expect(context.config).toMatchObject({ plugins: ['search'] });
    });
  });

  describe('attached knowledge', () => {
    // Regression: the server keeps the mount row but nulls the file / library
    // when the caller can no longer see it; rendering that row crashed the
    // Attachments menu (FileIcon -> `filename.split` on undefined).
    it('drops mounts whose file or library is no longer visible', () => {
      const state = createState({
        agentMap: {
          'agent-1': {
            files: [
              { enabled: true, id: null, name: null } as any,
              { enabled: true, id: 'file-1', name: 'Brief.pdf' } as any,
            ],
            knowledgeBases: [
              { enabled: true, id: null, name: null } as any,
              { enabled: false, id: 'kb-1', name: 'Handbook' } as any,
            ],
          },
        },
      });

      expect(
        agentByIdSelectors
          .getAgentFilesById('agent-1')(state)
          .map((item) => item.id),
      ).toEqual(['file-1']);
      expect(
        agentByIdSelectors
          .getAgentKnowledgeBasesById('agent-1')(state)
          .map((item) => item.id),
      ).toEqual(['kb-1']);
    });
  });

  describe('agent mode', () => {
    it('should default to agent mode when enableAgentMode is not explicitly false', () => {
      const state = createState({
        agentMap: {
          'agent-1': {
            chatConfig: {},
            model: 'gpt-4o',
            provider: 'openai',
          },
        },
      });

      expect(agentByIdSelectors.getAgentModeById('agent-1')(state)).toBe('auto');
      expect(agentByIdSelectors.getAgentEnableModeById('agent-1')(state)).toBe(true);
    });

    it('should keep the agent in agent mode when agent mode is enabled', () => {
      const state = createState({
        agentMap: {
          'agent-1': {
            chatConfig: { enableAgentMode: true },
            model: 'claude-opus-4-8',
            provider: 'lobehub',
          },
        },
      });

      expect(agentByIdSelectors.getAgentModeById('agent-1')(state)).toBe('auto');
      expect(agentByIdSelectors.getAgentEnableModeById('agent-1')(state)).toBe(true);
    });
  });

  describe('getAgentWorkingDirectoryById', () => {
    afterEach(() => {
      vi.restoreAllMocks();
    });

    const stateWith = (config: Record<string, any>, localMap: Record<string, string> = {}) =>
      createState({
        agentMap: { 'agent-1': config },
        localAgentWorkingDirectoryMap: localMap,
      });

    it('reads the per-device choice for the current (local) device', () => {
      vi.spyOn(globalAgentContextManager, 'getContext').mockReturnValue({ homePath: '/home/me' });
      const state = stateWith({
        agencyConfig: { workingDirByDevice: { 'device-A': '/repos/agent-gateway' } },
      });

      expect(agentByIdSelectors.getAgentWorkingDirectoryById('agent-1', 'device-A')(state)).toBe(
        '/repos/agent-gateway',
      );
    });

    it('reads the bound device choice when the agent targets a device', () => {
      vi.spyOn(globalAgentContextManager, 'getContext').mockReturnValue({ homePath: '/home/me' });
      const state = stateWith({
        agencyConfig: {
          boundDeviceId: 'device-B',
          executionTarget: 'device',
          workingDirByDevice: { 'device-A': '/repos/local', 'device-B': '/repos/remote' },
        },
      });

      // currentDeviceId is the local machine, but executionTarget=device → device-B wins
      expect(agentByIdSelectors.getAgentWorkingDirectoryById('agent-1', 'device-A')(state)).toBe(
        '/repos/remote',
      );
    });

    it('falls back to the legacy per-agent value when no device choice exists', () => {
      vi.spyOn(globalAgentContextManager, 'getContext').mockReturnValue({ homePath: '/home/me' });
      const state = stateWith({ agencyConfig: {} }, { 'agent-1': '/repos/legacy' });

      expect(agentByIdSelectors.getAgentWorkingDirectoryById('agent-1', 'device-A')(state)).toBe(
        '/repos/legacy',
      );
    });

    it('falls back to desktop/home path when nothing is set', () => {
      vi.spyOn(globalAgentContextManager, 'getContext').mockReturnValue({
        desktopPath: '/home/me/Desktop',
        homePath: '/home/me',
      });
      const state = stateWith({ agencyConfig: {} });

      expect(agentByIdSelectors.getAgentWorkingDirectoryById('agent-1', 'device-A')(state)).toBe(
        '/home/me/Desktop',
      );
    });
  });

  describe('getAgentConfigErrorById', () => {
    it('returns the recorded error for the agent', () => {
      const state = createState({ agentConfigErrorMap: { 'agent-1': 'boom' } });

      expect(agentByIdSelectors.getAgentConfigErrorById('agent-1')(state)).toBe('boom');
    });

    it('returns undefined for another agent or an empty id', () => {
      const state = createState({ agentConfigErrorMap: { 'agent-1': 'boom' } });

      expect(agentByIdSelectors.getAgentConfigErrorById('agent-2')(state)).toBeUndefined();
      expect(agentByIdSelectors.getAgentConfigErrorById('')(state)).toBeUndefined();
    });
  });

  describe('getAgentTTSVoiceById', () => {
    it('returns the configured openai voice', () => {
      const state = createState({
        agentMap: {
          'agent-1': { tts: { ttsService: 'openai', voice: { openai: 'nova' } } },
        },
      });

      expect(agentByIdSelectors.getAgentTTSVoiceById('agent-1')(state)).toBe('nova');
    });

    it('falls back to a default voice when the agent config is missing', () => {
      const state = createState({ agentMap: {} });

      expect(agentByIdSelectors.getAgentTTSVoiceById('missing')(state)).toBe('alloy');
    });
  });

  describe('hasAgentConfigInScope', () => {
    it('only treats a cached config as renderable in the scope that wrote it', () => {
      const state = createState({
        agentConfigReplica: { entries: {}, scope: 'user-1:workspace-a' },
        agentMap: { 'agent-1': { title: 'From workspace A' } },
      });

      expect(agentByIdSelectors.hasAgentConfigInScope('agent-1', 'user-1:workspace-a')(state)).toBe(
        true,
      );
      // After a workspace switch the entry is still in `agentMap`, but it
      // belongs to the previous scope.
      expect(agentByIdSelectors.hasAgentConfigInScope('agent-1', 'user-1:workspace-b')(state)).toBe(
        false,
      );
      expect(agentByIdSelectors.hasAgentConfigInScope('', 'user-1:workspace-a')(state)).toBe(false);
    });
  });

  describe('isAgentNotFoundById', () => {
    it('returns true only for agents flagged in agentNotFoundMap', () => {
      const state = createState({ agentNotFoundMap: { 'agent-gone': true } });

      expect(agentByIdSelectors.isAgentNotFoundById('agent-gone')(state)).toBe(true);
      expect(agentByIdSelectors.isAgentNotFoundById('agent-1')(state)).toBe(false);
      expect(agentByIdSelectors.isAgentNotFoundById('')(state)).toBe(false);
    });
  });

  describe('isAgentConfigLoadingById', () => {
    it('reports loading while the config is absent from agentMap', () => {
      const state = createState({ agentMap: {} });

      expect(agentByIdSelectors.isAgentConfigLoadingById('agent-1')(state)).toBe(true);
    });

    it('settles once the config lands in agentMap', () => {
      const state = createState({ agentMap: { 'agent-1': { id: 'agent-1' } } });

      expect(agentByIdSelectors.isAgentConfigLoadingById('agent-1')(state)).toBe(false);
    });

    it('settles when the agent is marked not-found (no access / deleted)', () => {
      const state = createState({ agentMap: {}, agentNotFoundMap: { 'agent-gone': true } });

      expect(agentByIdSelectors.isAgentConfigLoadingById('agent-gone')(state)).toBe(false);
    });
  });
});