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.

19.0 KB
Raw Blame
/**
 * @vitest-environment happy-dom
 */
import { renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { buildTopicPrompt } from './buildTopicPrompt';
import { useTopicItemDropdownMenu } from './useDropdownMenu';

const favoriteMenuItemMock = vi.hoisted(() =>
  vi.fn((target?: unknown) => (target ? { key: 'toggleFavorite', label: 'favorite.add' } : null)),
);
vi.mock('@/features/Favorites', () => ({ useFavoriteMenuItem: favoriteMenuItemMock }));

const locationFixture = vi.hoisted(() => ({ pathname: '/project/project-1/topic/topic-1' }));
const removeMock = vi.hoisted(() => vi.fn());
const confirmDeleteMock = vi.hoisted(() => vi.fn());
vi.mock('@/features/DeleteTopicConfirm', () => ({ confirmRemoveTopic: confirmDeleteMock }));
vi.mock('@/hooks/useActiveLocation', () => ({ useActiveLocation: () => locationFixture }));

const scopeFixture = vi.hoisted(() => ({
  enabled: false,
  providerType: null as string | null,
}));
const refreshProjectMock = vi.hoisted(() => vi.fn());
const navigateMock = vi.hoisted(() => vi.fn());
const autoRenameMock = vi.hoisted(() => vi.fn());
const favoriteMock = vi.hoisted(() => vi.fn());
const completeMock = vi.hoisted(() => vi.fn());
const cloneMock = vi.hoisted(() => vi.fn());
vi.mock('../../useScopedTopics', () => ({
  useScopedTopic: () =>
    scopeFixture.enabled
      ? {
          agentHeterogeneousProviderType: scopeFixture.providerType,
          agentId: 'agent-other',
          id: 'topic-1',
        }
      : undefined,
  useScopedTopics: () => ({
    scope: scopeFixture.enabled ? { projectId: 'project-1' } : null,
    refresh: refreshProjectMock,
  }),
}));
vi.mock('@/services/topic', () => ({ topicService: { cloneTopic: cloneMock } }));

const permissionMock = vi.hoisted(() => ({
  create_content: true,
  edit_own_content: true,
}));
const versionMock = vi.hoisted(() => ({ isDesktop: false }));
const workspaceMock = vi.hoisted(() => ({
  id: null as string | null,
  slug: null as string | null,
}));

vi.mock('antd', async (importOriginal) => ({
  ...(await importOriginal<object>()),
  App: {
    useApp: () => ({
      message: {
        success: vi.fn(),
      },
      modal: {
        confirm: vi.fn(),
      },
    }),
  },
}));

vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
  useActiveWorkspaceId: () => workspaceMock.id,
}));

vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({
  useActiveWorkspaceSlug: () => workspaceMock.slug,
}));

const labState = vi.hoisted(() => ({ enableTopicBugReport: false }));
const bugReportTargetMock = vi.hoisted(() => vi.fn());
vi.mock('@/business/client/hooks/useTopicBugReportMenuItem', () => ({
  useTopicBugReportMenuItem: (target: unknown) => {
    bugReportTargetMock(target);
    return { key: 'reportProblem', label: 'actions.reportProblem' };
  },
}));
vi.mock('@/store/user', () => ({
  useUserStore: (selector: (state: typeof labState) => unknown) => selector(labState),
}));
vi.mock('@/store/user/selectors', () => ({
  labPreferSelectors: {
    enableTopicBugReport: (state: typeof labState) => state.enableTopicBugReport,
  },
}));

vi.mock('@/components/RenameModal', () => ({
  openRenameModal: vi.fn(),
}));

vi.mock('@/const/version', () => ({
  get isDesktop() {
    return versionMock.isDesktop;
  },
}));

vi.mock('@/features/Electron/titlebar/RecentlyViewed/plugins', () => ({
  pluginRegistry: {
    parseUrl: vi.fn(),
  },
}));

vi.mock('@/features/ShareModal', () => ({
  openShareModal: vi.fn(),
}));

vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
  useWorkspaceAwareNavigate: () => navigateMock,
}));

vi.mock('@/hooks/useAppOrigin', () => ({
  useAppOrigin: () => 'https://example.com',
}));

vi.mock('@/hooks/usePermission', () => ({
  usePermission: (action: 'create_content' | 'edit_own_content') => ({
    allowed: permissionMock[action],
    reason: '',
  }),
}));

const agentMapFixture = vi.hoisted(() => ({ value: {} as Record<string, unknown> }));
vi.mock('@/store/agent', () => ({
  useAgentStore: (selector: (state: Record<string, unknown>) => unknown) =>
    selector({ activeAgentId: 'agent-1', agentMap: agentMapFixture.value }),
}));

vi.mock('@/store/chat', () => ({
  useChatStore: (selector: (state: Record<string, unknown>) => unknown) =>
    selector({
      autoRenameTopicTitle: autoRenameMock,
      duplicateTopic: vi.fn(),
      favoriteTopic: favoriteMock,
      markTopicCompleted: completeMock,
      removeTopic: removeMock,
      unmarkTopicCompleted: completeMock,
      updateTopicTitle: vi.fn(),
    }),
}));

vi.mock('@/store/electron', () => ({
  useElectronStore: (selector: (state: Record<string, unknown>) => unknown) =>
    selector({ addTab: vi.fn() }),
}));

vi.mock('@/store/global', () => ({
  useGlobalStore: (selector: (state: Record<string, unknown>) => unknown) =>
    selector({ openTopicInNewWindow: vi.fn() }),
}));

const getMenuItem = (
  items: NonNullable<ReturnType<ReturnType<typeof useTopicItemDropdownMenu>['dropdownMenu']>>,
  key: string,
) => items.find((item) => item && 'key' in item && item.key === key);

describe('useTopicItemDropdownMenu', () => {
  beforeEach(() => {
    scopeFixture.enabled = false;
    scopeFixture.providerType = null;
    vi.clearAllMocks();
    permissionMock.create_content = true;
    permissionMock.edit_own_content = true;
    versionMock.isDesktop = false;
    workspaceMock.id = null;
    workspaceMock.slug = null;
    labState.enableTopicBugReport = false;
    agentMapFixture.value = {};
  });

  afterEach(() => {
    vi.restoreAllMocks();
    Reflect.deleteProperty(document, 'execCommand');
  });

  it.each([
    ['copySessionId', 'topic-1'],
    ['copyLink', 'https://example.com/agent/agent-1/topic-1'],
    ['copyTopicPrompt', buildTopicPrompt({ id: 'topic-1', title: 'Topic 1' })],
  ])('copies %s when the Clipboard API is unavailable', async (key, expected) => {
    vi.spyOn(navigator, 'clipboard', 'get').mockReturnValue(undefined as never);
    let copiedText: string | undefined;
    const copy = vi.fn(() => {
      copiedText = (document.activeElement as HTMLTextAreaElement).value;
      return true;
    });
    Object.defineProperty(document, 'execCommand', { configurable: true, value: copy });
    const { result } = renderHook(() =>
      useTopicItemDropdownMenu({ id: 'topic-1', title: 'Topic 1' }),
    );
    const item = getMenuItem(result.current.dropdownMenu(), key);
    if (!item || !('onClick' in item)) throw new Error('Expected copy action');

    await item.onClick?.({} as never);

    expect(copy).toHaveBeenCalledWith('copy');
    expect(copiedText).toBe(expected);
    expect(document.querySelector('textarea')).toBeNull();
  });

  it('scopes the copied topic prompt to the active workspace', async () => {
    workspaceMock.id = 'ws_1';
    const writeText = vi.fn().mockResolvedValue(undefined);
    vi.spyOn(navigator, 'clipboard', 'get').mockReturnValue({ writeText } as never);
    const { result } = renderHook(() =>
      useTopicItemDropdownMenu({ id: 'topic-1', title: 'Topic 1' }),
    );
    const item = getMenuItem(result.current.dropdownMenu(), 'copyTopicPrompt');
    if (!item || !('onClick' in item)) throw new Error('Expected copy action');

    await item.onClick?.({} as never);

    expect(writeText).toHaveBeenCalledWith(
      buildTopicPrompt({ id: 'topic-1', title: 'Topic 1', workspaceId: 'ws_1' }),
    );
    expect(writeText.mock.calls[0][0]).toContain('lh topic view topic-1 -L 500 --workspace ws_1');
  });

  it.each([
    ['/team/project/project-1/topic/topic-1', true],
    ['/project/project-1/topic/topic-other', false],
    ['/project/project-1/settings', false],
  ])(
    'after deleting a Project row at %s, navigates home only for the current Topic',
    async (pathname, shouldNavigate) => {
      scopeFixture.enabled = true;
      locationFixture.pathname = pathname;
      const { result } = renderHook(() =>
        useTopicItemDropdownMenu({ id: 'topic-1', title: 'Topic' }),
      );
      const item = getMenuItem(result.current.dropdownMenu(), 'delete');
      if (!item || !('onClick' in item)) throw new Error('Missing delete');
      item.onClick?.({} as never);
      await confirmDeleteMock.mock.calls[0][0].onConfirm(false);
      expect(removeMock).toHaveBeenCalledWith('topic-1', false);
      expect(refreshProjectMock).toHaveBeenCalledOnce();
      if (shouldNavigate) expect(navigateMock).toHaveBeenCalledWith('/project/project-1');
      else expect(navigateMock).not.toHaveBeenCalled();
    },
  );

  it.each([
    ['/project/project-1/topic/topic-1', true],
    ['/project/project-1/topic/topic-other', false],
  ])(
    'after archiving a Project row at %s, navigates home only for the current Topic',
    async (pathname, shouldNavigate) => {
      scopeFixture.enabled = true;
      locationFixture.pathname = pathname;
      const { result } = renderHook(() =>
        useTopicItemDropdownMenu({ id: 'topic-1', title: 'Topic' }),
      );

      await result.current.toggleCompleted();

      expect(completeMock).toHaveBeenCalledWith('topic-1');
      expect(refreshProjectMock).toHaveBeenCalledOnce();
      if (shouldNavigate) expect(navigateMock).toHaveBeenCalledWith('/project/project-1');
      else expect(navigateMock).not.toHaveBeenCalled();
    },
  );

  it('stays on the Topic the user opened while the archive was in flight', async () => {
    scopeFixture.enabled = true;
    locationFixture.pathname = '/project/project-1/topic/topic-1';
    let finishArchive!: () => void;
    completeMock.mockReturnValueOnce(new Promise<void>((resolve) => (finishArchive = resolve)));
    const { rerender, result } = renderHook(() =>
      useTopicItemDropdownMenu({ id: 'topic-1', title: 'Topic' }),
    );

    const archiving = result.current.toggleCompleted();
    locationFixture.pathname = '/project/project-1/topic/topic-other';
    rerender();
    finishArchive();
    await archiving;

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

  it('does not navigate once the user left the Project while the archive was in flight', async () => {
    scopeFixture.enabled = true;
    locationFixture.pathname = '/project/project-1/topic/topic-1';
    let finishArchive!: () => void;
    completeMock.mockReturnValueOnce(new Promise<void>((resolve) => (finishArchive = resolve)));
    const { result, unmount } = renderHook(() =>
      useTopicItemDropdownMenu({ id: 'topic-1', title: 'Topic' }),
    );

    const archiving = result.current.toggleCompleted();
    unmount();
    finishArchive();
    await archiving;

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

  it('copies the row Agent link even when another Agent is active', async () => {
    scopeFixture.enabled = true;
    const writeText = vi.fn();
    vi.spyOn(navigator, 'clipboard', 'get').mockReturnValue({ writeText } as unknown as Clipboard);
    const { result } = renderHook(() =>
      useTopicItemDropdownMenu({ id: 'topic-1', title: 'Other agent topic' }),
    );
    const item = getMenuItem(result.current.dropdownMenu(), 'copyLink');
    if (!item || !('onClick' in item)) throw new Error('Missing copy link');
    await item.onClick?.({} as never);
    expect(writeText).toHaveBeenCalledWith('https://example.com/agent/agent-other/topic-1');
  });

  it('keeps the active workspace prefix in the copied link', async () => {
    workspaceMock.slug = 'lobehub';
    const writeText = vi.fn();
    vi.spyOn(navigator, 'clipboard', 'get').mockReturnValue({ writeText } as unknown as Clipboard);
    const { result } = renderHook(() =>
      useTopicItemDropdownMenu({ id: 'topic-1', title: 'Topic 1' }),
    );
    const item = getMenuItem(result.current.dropdownMenu(), 'copyLink');
    if (!item || !('onClick' in item)) throw new Error('Missing copy link');
    await item.onClick?.({} as never);
    expect(writeText).toHaveBeenCalledWith('https://example.com/lobehub/agent/agent-1/topic-1');
  });

  it.each(['favorite', 'markCompleted'])(
    'refreshes the Project list immediately after %s',
    async (key) => {
      scopeFixture.enabled = true;
      const { result } = renderHook(() =>
        useTopicItemDropdownMenu({ id: 'topic-1', title: 'Topic' }),
      );
      const item = getMenuItem(result.current.dropdownMenu(), key);
      if (!item || !('onClick' in item)) throw new Error('Missing mutation');
      await item.onClick?.({} as never);
      expect(refreshProjectMock).toHaveBeenCalledOnce();
    },
  );

  it('auto-renames using messages from the row Agent', async () => {
    scopeFixture.enabled = true;
    const { result } = renderHook(() =>
      useTopicItemDropdownMenu({ id: 'topic-1', title: 'Topic' }),
    );
    const item = getMenuItem(result.current.dropdownMenu(), 'autoRename');
    if (!item || !('onClick' in item)) throw new Error('Missing auto rename');
    await item.onClick?.({} as never);
    expect(autoRenameMock).toHaveBeenCalledWith('topic-1', 'agent-other');
    expect(refreshProjectMock).toHaveBeenCalledOnce();
  });

  it('duplicates a Project topic without requiring an Agent sidebar cache', async () => {
    scopeFixture.enabled = true;
    cloneMock.mockResolvedValue('topic-copy');
    const { result } = renderHook(() =>
      useTopicItemDropdownMenu({ id: 'topic-1', title: 'Topic' }),
    );
    const item = getMenuItem(result.current.dropdownMenu(), 'duplicate');
    if (!item || !('onClick' in item)) throw new Error('Missing duplicate');
    await item.onClick?.({} as never);
    expect(cloneMock).toHaveBeenCalled();
    expect(refreshProjectMock).toHaveBeenCalledOnce();
    expect(navigateMock).toHaveBeenCalledWith('/project/project-1/topic/topic-copy');
  });

  it('keeps project association out of the individual topic menu', () => {
    const { result } = renderHook(() =>
      useTopicItemDropdownMenu({ id: 'topic-1', title: 'Topic' }),
    );
    expect(getMenuItem(result.current.dropdownMenu(), 'associate-project')).toBeUndefined();
  });

  it('groups desktop topic actions by intent', () => {
    versionMock.isDesktop = true;

    const { result } = renderHook(() =>
      useTopicItemDropdownMenu({ id: 'topic-1', title: 'Topic 1' }),
    );
    const items = result.current.dropdownMenu();

    expect(items.map((item) => (item && 'key' in item ? item.key : 'divider'))).toEqual([
      'markCompleted',
      'favorite',
      'toggleFavorite',
      'divider',
      'autoRename',
      'rename',
      'divider',
      'openInNewTab',
      'openOnRight',
      'openInNewWindow',
      'divider',
      'copySessionId',
      'copyLink',
      'copyTopicPrompt',
      'divider',
      'duplicate',
      'share',
      'forwardToAgent',
      'moveToAgent',
      'divider',
      'diagnose',
      'divider',
      'delete',
    ]);
    expect(getMenuItem(items, 'share')).toMatchObject({ label: 'shareModal.title' });
  });

  it('puts Report Bug next to the message chain check when the lab is on', () => {
    labState.enableTopicBugReport = true;

    const { result } = renderHook(() =>
      useTopicItemDropdownMenu({ id: 'topic-1', title: 'Topic 1' }),
    );
    const keys = result.current
      .dropdownMenu()
      .map((item) => (item && 'key' in item ? item.key : 'divider'));

    expect(keys.slice(-5)).toEqual(['divider', 'diagnose', 'reportProblem', 'divider', 'delete']);
    expect(bugReportTargetMock).toHaveBeenCalledWith({ agentId: 'agent-1', topicId: 'topic-1' });
  });

  it('disables topic management actions for workspace viewers', () => {
    permissionMock.create_content = false;
    permissionMock.edit_own_content = false;

    const { result } = renderHook(() =>
      useTopicItemDropdownMenu({ id: 'topic-1', title: 'Topic 1' }),
    );
    const items = result.current.dropdownMenu();

    for (const key of [
      'markCompleted',
      'favorite',
      'autoRename',
      'rename',
      'duplicate',
      'moveToAgent',
      'share',
      'delete',
    ]) {
      expect(getMenuItem(items, key)).toMatchObject({ disabled: true });
    }

    expect(getMenuItem(items, 'copySessionId')).not.toMatchObject({ disabled: true });
    expect(getMenuItem(items, 'copyLink')).not.toMatchObject({ disabled: true });
    expect(getMenuItem(items, 'copyTopicPrompt')).not.toMatchObject({ disabled: true });
  });

  describe('inline archive', () => {
    const heterogeneousAgent = {
      agencyConfig: { heterogeneousProvider: { type: 'claude-code' } },
    };

    it('is offered for heterogeneous agent topics and archives on toggle', async () => {
      agentMapFixture.value = { 'agent-1': heterogeneousAgent };
      const { result } = renderHook(() =>
        useTopicItemDropdownMenu({ id: 'topic-1', title: 'Topic 1' }),
      );

      expect(result.current.canInlineArchive).toBe(true);
      expect(result.current.isCompleted).toBe(false);
      await result.current.toggleCompleted();

      expect(completeMock).toHaveBeenCalledWith('topic-1');
    });

    it('resolves the row Agent rather than the active one', () => {
      scopeFixture.enabled = true;
      agentMapFixture.value = { 'agent-other': heterogeneousAgent };
      const { result } = renderHook(() =>
        useTopicItemDropdownMenu({ id: 'topic-1', title: 'Topic 1' }),
      );

      expect(result.current.canInlineArchive).toBe(true);
    });

    it('is offered for a project row whose agent config was never loaded', () => {
      scopeFixture.enabled = true;
      scopeFixture.providerType = 'claude-code';
      const { result } = renderHook(() =>
        useTopicItemDropdownMenu({ id: 'topic-1', title: 'Topic 1' }),
      );

      expect(result.current.canInlineArchive).toBe(true);
    });

    it('is not offered for regular agents', () => {
      agentMapFixture.value = { 'agent-1': { agencyConfig: {} } };
      const { result } = renderHook(() =>
        useTopicItemDropdownMenu({ id: 'topic-1', title: 'Topic 1' }),
      );

      expect(result.current.canInlineArchive).toBe(false);
    });

    it('is not offered to viewers without edit permission', () => {
      agentMapFixture.value = { 'agent-1': heterogeneousAgent };
      permissionMock.edit_own_content = false;
      const { result } = renderHook(() =>
        useTopicItemDropdownMenu({ id: 'topic-1', title: 'Topic 1' }),
      );

      expect(result.current.canInlineArchive).toBe(false);
    });
  });

  it('offers Favorites beside Pin, linking the row topic under its agent', () => {
    const { result } = renderHook(() =>
      useTopicItemDropdownMenu({ fav: true, id: 'topic-1', title: 'Topic 1' }),
    );

    const keys = result.current
      .dropdownMenu()
      .map((item) => (item && 'key' in item ? item.key : 'divider'));
    expect(keys.slice(keys.indexOf('favorite'), keys.indexOf('favorite') + 2)).toEqual([
      'favorite',
      'toggleFavorite',
    ]);
    expect(favoriteMenuItemMock).toHaveBeenLastCalledWith(
      {
        path: '/agent/agent-1/topic-1',
        snapshotReady: true,
        targetId: 'topic-1',
        title: 'Topic 1',
        type: 'topic',
      },
      { showHotkey: false },
    );
  });

  it('holds the favorite add until a placeholder topic title is replaced', () => {
    renderHook(() => useTopicItemDropdownMenu({ id: 'topic-1', title: '...' }));

    expect(favoriteMenuItemMock).toHaveBeenLastCalledWith(
      expect.objectContaining({ snapshotReady: false }),
      { showHotkey: false },
    );
  });
});