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.

33.1 KB
Raw Blame
import dayjs from 'dayjs';
import { describe, expect, it } from 'vitest';

import { type ChatStore } from '@/store/chat';
import { initialState } from '@/store/chat/initialState';
import { topicMapKey } from '@/store/chat/utils/topicMapKey';
import { merge } from '@/utils/merge';

import { topicSelectors } from './selectors';

const topicState = <T>(key: string, topics: T[], total: number) => ({
  topicDataMap: {
    [key]: {
      items: topics,
      total,
      currentPage: 0,
      hasMore: false,
      pageSize: 20,
    },
  },
  activeAgentId: 'test',
});

// Mock i18next
vi.mock('i18next', () => ({
  t: vi.fn().mockImplementation((key) => key),
}));

const initialStore = initialState as ChatStore;

const topicItems = [
  { id: 'topic1', name: 'Topic 1', favorite: true },
  { id: 'topic2', name: 'Topic 2' },
];

// Helper to create topicDataMap with correct key format
const createTopicDataMap = (agentId: string, groupId?: string) => ({
  [topicMapKey({ agentId, groupId })]: {
    items: topicItems,
    total: topicItems.length,
    currentPage: 0,
    hasMore: false,
    pageSize: 20,
  },
});

const topicDataMap = createTopicDataMap('test');

describe('topicSelectors', () => {
  describe('currentTopics', () => {
    it('should return undefined if there are no topics with activeAgentId', () => {
      const topics = topicSelectors.currentTopics(initialStore);
      expect(topics).toBeUndefined();
    });

    it('should return all current topics from the store', () => {
      const state = merge(initialStore, { topicDataMap, activeAgentId: 'test' });

      const topics = topicSelectors.currentTopics(state);
      expect(topics).toEqual(topicItems);
    });
  });

  describe('reasoning + hetero pins', () => {
    const pinTopicDataMap = createTopicDataMap('test');
    pinTopicDataMap[topicMapKey({ agentId: 'test' })].items = [
      {
        id: 'pinned',
        metadata: { reasoningConfig: { reasoningEffort: 'high' } },
        model: 'gpt-5',
        name: 'Pinned',
        provider: 'openai',
      },
      { id: 'legacy', model: 'gpt-5', name: 'Legacy', provider: 'openai' },
      { id: 'noModel', metadata: { reasoningConfig: {} }, name: 'No Model' },
      {
        id: 'heteroBoth',
        metadata: { heteroEffort: 'max' },
        model: 'opus',
        name: 'Hetero',
        provider: 'claude-code',
      },
      { id: 'heteroEffortOnly', metadata: { heteroEffort: 'default' }, name: 'Hetero effort' },
      { id: 'heteroNone', name: 'Hetero none' },
    ] as any;
    const state = merge(initialStore, { topicDataMap: pinTopicDataMap, activeAgentId: 'test' });

    it('getTopicReasoningPinById returns the pinned model with its reasoning config', () => {
      expect(topicSelectors.getTopicReasoningPinById('pinned')(state)).toEqual({
        model: 'gpt-5',
        provider: 'openai',
        reasoningConfig: { reasoningEffort: 'high' },
      });
      expect(topicSelectors.getTopicReasoningPinById('legacy')(state)).toEqual({
        model: 'gpt-5',
        provider: 'openai',
        reasoningConfig: undefined,
      });
      expect(topicSelectors.getTopicReasoningPinById('noModel')(state)).toBeUndefined();
    });

    it('getTopicReasoningConfigForModel only honors a pin taken for the same model', () => {
      expect(
        topicSelectors.getTopicReasoningConfigForModel('pinned', 'gpt-5', 'openai')(state),
      ).toEqual({ reasoningEffort: 'high' });
      // a sub-agent modelOverride must not inherit the parent topic's effort
      expect(
        topicSelectors.getTopicReasoningConfigForModel('pinned', 'gpt-4', 'openai')(state),
      ).toBeUndefined();
      expect(
        topicSelectors.getTopicReasoningConfigForModel('pinned', 'gpt-5', 'azure')(state),
      ).toBeUndefined();
      expect(
        topicSelectors.getTopicReasoningConfigForModel('legacy', 'gpt-5', 'openai')(state),
      ).toBeUndefined();
    });

    it('getTopicHeteroPinById combines the model columns with the effort pin', () => {
      expect(topicSelectors.getTopicHeteroPinById('heteroBoth')(state)).toEqual({
        effort: 'max',
        model: 'opus',
        provider: 'claude-code',
      });
      expect(topicSelectors.getTopicHeteroPinById('heteroEffortOnly')(state)).toEqual({
        effort: 'default',
      });
      expect(topicSelectors.getTopicHeteroPinById('heteroNone')(state)).toBeUndefined();
      expect(topicSelectors.getTopicHeteroPinById('missing')(state)).toBeUndefined();
    });

    it('activeTopicHeteroPin follows the active topic', () => {
      expect(topicSelectors.activeTopicHeteroPin(state)).toBeUndefined();
      expect(
        topicSelectors.activeTopicHeteroPin(merge(state, { activeTopicId: 'heteroBoth' })),
      ).toEqual({ effort: 'max', model: 'opus', provider: 'claude-code' });
    });
  });

  describe('getTopicModelById / activeTopicModel', () => {
    const modelTopicDataMap = createTopicDataMap('test');
    modelTopicDataMap[topicMapKey({ agentId: 'test' })].items = [
      // Pinned model lives in the top-level `model`/`provider` columns, not metadata.
      { id: 'withModel', name: 'With Model', model: 'gpt-5', provider: 'openai' },
      { id: 'noModel', name: 'No Model' },
      { id: 'modelOnly', name: 'Model Only', model: 'claude-opus-4-8' },
    ] as any;

    it('returns the model/provider pinned to a topic', () => {
      const state = merge(initialStore, { topicDataMap: modelTopicDataMap, activeAgentId: 'test' });
      expect(topicSelectors.getTopicModelById('withModel')(state)).toEqual({
        model: 'gpt-5',
        provider: 'openai',
      });
    });

    it('defaults provider to empty string when only model is recorded', () => {
      const state = merge(initialStore, { topicDataMap: modelTopicDataMap, activeAgentId: 'test' });
      expect(topicSelectors.getTopicModelById('modelOnly')(state)).toEqual({
        model: 'claude-opus-4-8',
        provider: '',
      });
    });

    it('returns undefined when the topic has no model recorded', () => {
      const state = merge(initialStore, { topicDataMap: modelTopicDataMap, activeAgentId: 'test' });
      expect(topicSelectors.getTopicModelById('noModel')(state)).toBeUndefined();
    });

    it('activeTopicModel reads the active topic model, undefined when no active topic', () => {
      const base = merge(initialStore, { topicDataMap: modelTopicDataMap, activeAgentId: 'test' });
      expect(topicSelectors.activeTopicModel(base)).toBeUndefined();

      const active = merge(base, { activeTopicId: 'withModel' });
      expect(topicSelectors.activeTopicModel(active)).toEqual({
        model: 'gpt-5',
        provider: 'openai',
      });
    });
  });

  describe('currentTopicLength', () => {
    it('should return 0 if there are no topics', () => {
      const length = topicSelectors.currentTopicLength(initialStore);
      expect(length).toBe(0);
    });

    it('should return the number of current topics', () => {
      const state = merge(initialStore, { topicDataMap, activeAgentId: 'test' });
      const length = topicSelectors.currentTopicLength(state);
      expect(length).toBe(topicItems.length);
    });
  });

  describe('hasMoreTopics', () => {
    it('should return true when total exceeds pageSize even if hasMore is temporarily false', () => {
      const state = merge(initialStore, {
        activeAgentId: 'test',
        topicDataMap: {
          [topicMapKey({ agentId: 'test' })]: {
            currentPage: 0,
            hasMore: false,
            items: Array.from({ length: 20 }, (_, index) => ({ id: `topic-${index}` })),
            pageSize: 20,
            total: 21,
          },
        },
      });

      expect(topicSelectors.hasMoreTopics(state)).toBe(false);
      expect(topicSelectors.hasMoreTopicsForSidebar(state)).toBe(true);
    });

    it('should return false when all topics are already loaded', () => {
      const state = merge(initialStore, {
        activeAgentId: 'test',
        topicDataMap: {
          [topicMapKey({ agentId: 'test' })]: {
            currentPage: 1,
            hasMore: false,
            items: Array.from({ length: 21 }, (_, index) => ({ id: `topic-${index}` })),
            pageSize: 20,
            total: 21,
          },
        },
      });

      expect(topicSelectors.hasMoreTopics(state)).toBe(false);
      expect(topicSelectors.hasMoreTopicsForSidebar(state)).toBe(true);
    });

    it('should return false for sidebar when total does not exceed pageSize', () => {
      const state = merge(initialStore, {
        activeAgentId: 'test',
        topicDataMap: {
          [topicMapKey({ agentId: 'test' })]: {
            currentPage: 1,
            hasMore: false,
            items: Array.from({ length: 21 }, (_, index) => ({ id: `topic-${index}` })),
            pageSize: 30,
            total: 21,
          },
        },
      });

      expect(topicSelectors.hasMoreTopics(state)).toBe(false);
      expect(topicSelectors.hasMoreTopicsForSidebar(state)).toBe(false);
    });
  });

  describe('currentTopicDeviceId', () => {
    const stateWithTopicMetadata = (topicMeta: Record<string, unknown> | undefined) =>
      merge(initialStore, {
        ...topicState(
          topicMapKey({ agentId: 'test' }),
          [{ id: 'topic-device', metadata: topicMeta }],
          1,
        ),
        activeTopicId: 'topic-device',
      }) as ChatStore;

    it('prefers the running operation device over the bound device', () => {
      const state = stateWithTopicMetadata({
        boundDeviceId: 'device-bound',
        runningOperation: { deviceId: 'device-running', operationId: 'op-1' },
      });

      expect(topicSelectors.currentTopicDeviceId(state)).toBe('device-running');
    });

    it('falls back to the bound device when no run is in flight', () => {
      const state = stateWithTopicMetadata({
        boundDeviceId: 'device-bound',
        runningOperation: null,
      });

      expect(topicSelectors.currentTopicDeviceId(state)).toBe('device-bound');
    });

    it('returns undefined when the topic has neither', () => {
      expect(topicSelectors.currentTopicDeviceId(stateWithTopicMetadata({}))).toBeUndefined();
      expect(
        topicSelectors.currentTopicDeviceId(stateWithTopicMetadata(undefined)),
      ).toBeUndefined();
      expect(topicSelectors.currentTopicDeviceId(initialStore)).toBeUndefined();
    });
  });

  describe('currentActiveTopic', () => {
    it('should return undefined if there is no active topic', () => {
      const topic = topicSelectors.currentActiveTopic(initialStore);
      expect(topic).toBeUndefined();
    });

    it('should tolerate a partial store state without the detail cache', () => {
      const state = {
        activeAgentId: 'test',
        activeTopicId: 'missing-topic',
        topicDataMap: {},
      } as ChatStore;

      expect(topicSelectors.currentActiveTopic(state)).toBeUndefined();
      expect(topicSelectors.getTopicById('missing-topic')(state)).toBeUndefined();
    });

    it('should return the current active topic', () => {
      const state = merge(initialStore, {
        topicDataMap,
        activeAgentId: 'test',
        activeTopicId: 'topic1',
      });
      const topic = topicSelectors.currentActiveTopic(state);
      expect(topic).toEqual(topicItems[0]);
    });

    it('should fall back to the detail cache when the topic is missing from the list bucket', () => {
      // An archived (completed) topic is excluded from the sidebar list fetch,
      // so it never lands in topicDataMap — only in the by-id detail cache.
      const archived = { id: 'archived1', title: 'Archived topic', status: 'completed' };
      const state = merge(initialStore, {
        topicDataMap,
        topicDetailMap: { archived1: archived },
        activeAgentId: 'test',
        activeTopicId: 'archived1',
      });
      expect(topicSelectors.currentActiveTopic(state)).toEqual(archived);
    });

    it('should prefer the list bucket row over the detail cache', () => {
      const state = merge(initialStore, {
        topicDataMap,
        topicDetailMap: { topic1: { id: 'topic1', title: 'stale detail' } },
        activeAgentId: 'test',
        activeTopicId: 'topic1',
      });
      expect(topicSelectors.currentActiveTopic(state)).toEqual(topicItems[0]);
    });
  });

  describe('getTopicById', () => {
    it('should fall back to the detail cache when the topic is missing from the list bucket', () => {
      const archived = { id: 'archived1', title: 'Archived topic', status: 'completed' };
      const state = merge(initialStore, {
        topicDataMap,
        topicDetailMap: { archived1: archived },
        activeAgentId: 'test',
      });
      expect(topicSelectors.getTopicById('archived1')(state)).toEqual(archived);
      expect(topicSelectors.getTopicById('topic1')(state)).toEqual(topicItems[0]);
    });
  });

  describe('currentUnFavTopics', () => {
    it('should return all unfavorited topics', () => {
      const state = merge(initialStore, { topicDataMap, activeAgentId: 'test' });
      const topics = topicSelectors.currentUnFavTopics(state);
      expect(topics).toEqual([topicItems[1]]);
    });
  });

  describe('displayTopics', () => {
    it('should return current topics if not searching', () => {
      const state = merge(initialStore, { topicDataMap, activeAgentId: 'test' });
      const topics = topicSelectors.displayTopics(state);
      expect(topics).toEqual(topicItems);
    });

    it('should hide every system-owned trigger, not just cron', () => {
      // A panel fetching the same agent with looser filters (goal chat, task
      // manager, page copilot) overwrites this bucket, so the list surfaces
      // must not render whatever lands in it.
      const polluted = [
        ...topicItems,
        { id: 'cron1', name: 'Cron', trigger: 'cron' },
        { id: 'task1', name: 'Task run', trigger: 'task' },
        { id: 'doc1', name: 'Doc chat', trigger: 'document' },
        { id: 'eval1', name: 'Eval', trigger: 'eval' },
        { id: 'channel1', name: 'Channel run', trigger: 'channel' },
      ];
      const state = merge(initialStore, {
        activeAgentId: 'test',
        topicDataMap: {
          [topicMapKey({ agentId: 'test' })]: {
            currentPage: 0,
            hasMore: false,
            items: polluted,
            pageSize: 20,
            total: polluted.length,
          },
        },
      });

      expect(topicSelectors.displayTopics(state)).toEqual(topicItems);
      expect(topicSelectors.currentTopicLength(state)).toBe(topicItems.length);
    });
  });

  describe('searchTopics', () => {
    it('hides cached channel results while keeping their detail accessible', () => {
      const channelTopic = { ...topicItems[0], id: 'channel1', trigger: 'channel' };
      const state = merge(initialStore, {
        activeAgentId: 'test',
        activeTopicId: channelTopic.id,
        searchTopics: [...topicItems, channelTopic],
        topicDetailMap: { [channelTopic.id]: channelTopic },
      });

      expect(topicSelectors.searchTopics(state)).toEqual(topicItems);
      expect(topicSelectors.currentActiveTopic(state)).toEqual(channelTopic);
    });

    it('should return search topics if searching', () => {
      const searchTopics = [{ id: 'search1', name: 'Search 1' }];
      const state = merge(initialStore, { inSearchingMode: true, searchTopics });
      const topics = topicSelectors.searchTopics(state);
      expect(topics).toEqual(searchTopics);
    });
  });

  describe('agentTopicsViewTopics', () => {
    it('hides channel topics in the management list without hiding other trigger types', () => {
      const taskTopic = { ...topicItems[0], id: 'task1', trigger: 'task' };
      const channelTopic = { ...topicItems[0], id: 'channel1', trigger: 'channel' };
      const state = merge(initialStore, {
        activeAgentId: 'test',
        agentTopicsViewMap: {
          [topicMapKey({ agentId: 'test' })]: { items: [...topicItems, taskTopic, channelTopic] },
        },
      });

      expect(topicSelectors.agentTopicsViewTopics(state)).toEqual([...topicItems, taskTopic]);
    });
  });

  describe('getTopicById', () => {
    it('should return undefined if topic is not found', () => {
      const state = merge(initialStore, { topicDataMap, activeAgentId: 'test' });
      const topic = topicSelectors.getTopicById('notfound')(state);
      expect(topic).toBeUndefined();
    });

    it('should return the topic with the given id', () => {
      const state = merge(initialStore, { topicDataMap, activeAgentId: 'test' });
      const topic = topicSelectors.getTopicById('topic1')(state);
      expect(topic).toEqual(topicItems[0]);
    });

    it('should find a topic loaded under another agent for split desktop panes', () => {
      const backgroundTopic = { id: 'background-topic', name: 'Background topic' };
      const state = merge(initialStore, {
        activeAgentId: 'focused-agent',
        topicDataMap: {
          ...createTopicDataMap('focused-agent'),
          [topicMapKey({ agentId: 'background-agent' })]: {
            currentPage: 0,
            hasMore: false,
            items: [backgroundTopic],
            pageSize: 20,
            total: 1,
          },
        },
      });

      expect(topicSelectors.getTopicById('background-topic')(state)).toEqual(backgroundTopic);
    });
  });

  describe('getTopicWorkingDirectory', () => {
    // Two topics with distinct working directories; A is the active topic.
    const wdTopics = [
      { id: 'topicA', metadata: { workingDirectory: '/project-a' }, name: 'A' },
      { id: 'topicB', metadata: { workingDirectory: '/project-b' }, name: 'B' },
    ];
    const wdState = merge(initialStore, {
      activeAgentId: 'test',
      activeTopicId: 'topicA',
      topicDataMap: {
        [topicMapKey({ agentId: 'test' })]: {
          currentPage: 0,
          hasMore: false,
          items: wdTopics,
          pageSize: 20,
          total: wdTopics.length,
        },
      },
    }) as ChatStore;

    // Regression: while topic A is active, a tool call captured for topic B must
    // resolve B's directory — not A's — so a mid-stream topic switch can't make
    // grep search the wrong project.
    it('binds to the requested topic id, not the active topic', () => {
      expect(topicSelectors.getTopicWorkingDirectory('topicB')(wdState)).toBe('/project-b');
      expect(topicSelectors.getTopicWorkingDirectory('topicA')(wdState)).toBe('/project-a');
    });

    it('falls back to the active topic when no id is given', () => {
      expect(topicSelectors.getTopicWorkingDirectory()(wdState)).toBe('/project-a');
    });

    it('treats an explicit null as a new-topic route without a directory', () => {
      expect(topicSelectors.getTopicWorkingDirectory(null)(wdState)).toBeUndefined();
    });

    it('returns undefined for an unknown topic id', () => {
      expect(topicSelectors.getTopicWorkingDirectory('nope')(wdState)).toBeUndefined();
    });
  });

  describe('groupedTopicsSelector', () => {
    it('should return empty array if there are no topics', () => {
      const state = merge(initialStore, { activeAgentId: 'test' });
      const grouped = topicSelectors.groupedTopicsSelector()(state);
      expect(grouped).toEqual([]);
    });

    it('should return grouped topics by time when no favorites exist', () => {
      const topics = [
        { id: 'topic1', name: 'Topic 1', favorite: false, createAt: '2023-01-01' },
        { id: 'topic2', name: 'Topic 2', favorite: false, createAt: '2023-01-01' },
      ];

      const state = merge(
        initialStore,
        topicState(topicMapKey({ agentId: 'test' }), topics, topics.length),
      );

      const grouped = topicSelectors.groupedTopicsSelector()(state);
      expect(grouped).toHaveLength(1); // One time-based group
      expect(grouped[0].children).toEqual(topics);
    });

    it('should separate favorite and unfavorite topics into different groups', () => {
      const topics = [
        { id: 'topic1', name: 'Topic 1', favorite: true, createAt: '2023-01-01' },
        { id: 'topic2', name: 'Topic 2', favorite: false, createAt: '2023-01-01' },
        { id: 'topic3', name: 'Topic 3', favorite: true, createAt: '2023-01-01' },
      ];

      const state = merge(
        initialStore,
        topicState(topicMapKey({ agentId: 'test' }), topics, topics.length),
      );

      const grouped = topicSelectors.groupedTopicsSelector()(state);

      expect(grouped).toHaveLength(2); // Favorite group + one time-based group

      // Check favorite group
      expect(grouped[0]).toEqual({
        id: 'favorite',
        title: 'pinned', // This matches the mocked t function return
        children: topics.filter((t) => t.favorite),
      });

      // Check unfavorite group
      expect(grouped[1].children).toEqual(topics.filter((t) => !t.favorite));
    });

    it('should only create time-based groups when there are no favorites', () => {
      const topics = [
        { id: 'topic1', name: 'Topic 1', favorite: false, createAt: '2023-01-01' },
        { id: 'topic2', name: 'Topic 2', favorite: false, createAt: '2023-02-01' },
      ];

      const state = merge(
        initialStore,
        topicState(topicMapKey({ agentId: 'test' }), topics, topics.length),
      );

      const grouped = topicSelectors.groupedTopicsSelector()(state);

      // Should not have a favorites group
      expect(grouped.find((g) => g.id === 'favorite')).toBeUndefined();
    });
  });

  describe('group session support', () => {
    const timestamp = Date.now();

    it('should return topics for group session when only groupId is set', () => {
      const groupTopics = [
        {
          id: 'group-topic1',
          title: 'Group Topic 1',
          favorite: false,
          createdAt: timestamp,
          updatedAt: timestamp,
        },
        {
          id: 'group-topic2',
          title: 'Group Topic 2',
          favorite: true,
          createdAt: timestamp,
          updatedAt: timestamp,
        },
      ];

      // Note: When in group session, activeAgentId may still have a value (e.g., 'inbox')
      // but we prioritize groupId for topic data lookup
      const state = {
        ...initialStore,
        topicDataMap: {
          [topicMapKey({ groupId: 'group-123' })]: {
            items: groupTopics,
            total: groupTopics.length,
            currentPage: 0,
            hasMore: false,
            pageSize: 20,
          },
        },
        activeAgentId: undefined as any,
        activeGroupId: 'group-123',
      };

      const topics = topicSelectors.currentTopics(state);
      expect(topics).toEqual(groupTopics);
    });

    it('should return topics for group_agent session when both groupId and agentId are set', () => {
      const groupAgentTopics = [
        {
          id: 'ga-topic1',
          title: 'Group Agent Topic 1',
          favorite: false,
          createdAt: timestamp,
          updatedAt: timestamp,
        },
      ];

      const state = merge(initialStore, {
        topicDataMap: {
          [topicMapKey({ agentId: 'agent-456', groupId: 'group-123' })]: {
            items: groupAgentTopics,
            total: groupAgentTopics.length,
            currentPage: 0,
            hasMore: false,
            pageSize: 20,
          },
        },
        activeAgentId: 'agent-456',
        activeGroupId: 'group-123',
      });

      const topics = topicSelectors.currentTopics(state);
      expect(topics).toEqual(groupAgentTopics);
    });

    it('should return correct topic count for group session', () => {
      const groupTopics = [
        { id: 'group-topic1', title: 'Group Topic 1', createdAt: timestamp, updatedAt: timestamp },
        { id: 'group-topic2', title: 'Group Topic 2', createdAt: timestamp, updatedAt: timestamp },
        { id: 'group-topic3', title: 'Group Topic 3', createdAt: timestamp, updatedAt: timestamp },
      ];

      const state = {
        ...initialStore,
        topicDataMap: {
          [topicMapKey({ groupId: 'group-123' })]: {
            items: groupTopics,
            total: 10, // Total could be more than items (pagination)
            currentPage: 0,
            hasMore: true,
            pageSize: 20,
          },
        },
        activeAgentId: undefined as any,
        activeGroupId: 'group-123',
      };

      expect(topicSelectors.currentTopicLength(state)).toBe(3);
      expect(topicSelectors.currentTopicCount(state)).toBe(10);
      expect(topicSelectors.hasMoreTopics(state)).toBe(true);
    });

    it('should return isUndefinedTopics true when group has no topics data', () => {
      const state = {
        ...initialStore,
        topicDataMap: {},
        activeAgentId: undefined as any,
        activeGroupId: 'group-123',
      };

      expect(topicSelectors.isUndefinedTopics(state)).toBe(true);
    });
  });

  describe('displayTopicsForSidebar', () => {
    it('does not pin an open channel topic back into the sidebar', () => {
      const channelTopic = { ...topicItems[0], id: 'channel1', trigger: 'channel' };
      const state = merge(initialStore, {
        activeAgentId: 'test',
        activeTopicId: channelTopic.id,
        topicDataMap,
        topicDetailMap: { [channelTopic.id]: channelTopic },
      });

      expect(topicSelectors.displayTopicsForSidebar(20)(state)).toEqual(topicItems);
      expect(topicSelectors.currentActiveTopic(state)).toEqual(channelTopic);
    });

    it('hides completed topics immediately when completed topics are excluded', () => {
      const now = Date.now();
      const state = merge(initialStore, {
        activeAgentId: 'agent-1',
        topicDataMap: {
          [topicMapKey({ agentId: 'agent-1' })]: {
            currentPage: 0,
            hasMore: false,
            items: [
              { createdAt: now, id: 'active', status: 'active', updatedAt: now },
              { createdAt: now, id: 'completed', status: 'completed', updatedAt: now },
            ],
            pageSize: 20,
            total: 2,
          },
        },
      });

      expect(topicSelectors.displayTopicsForSidebar(20, 'updatedAt', false)(state)).toEqual([
        expect.objectContaining({ id: 'active' }),
      ]);
      expect(topicSelectors.displayTopicsForSidebar(20, 'updatedAt', true)(state)).toHaveLength(2);
    });

    it('keeps the active topic visible when it falls outside the configured page', () => {
      const state = merge(initialStore, {
        activeAgentId: 'agent-1',
        activeTopicId: 'older-active',
        topicDataMap: {
          [topicMapKey({ agentId: 'agent-1' })]: {
            currentPage: 0,
            hasMore: true,
            items: [
              { id: 'newest', updatedAt: 3 },
              { id: 'newer', updatedAt: 2 },
              { id: 'older-active', updatedAt: 1 },
            ],
            pageSize: 2,
            total: 3,
          },
        },
      });

      expect(
        topicSelectors
          .displayTopicsForSidebar(
            2,
            'updatedAt',
            false,
          )(state)
          ?.map(({ id }) => id),
      ).toEqual(['newest', 'newer', 'older-active']);
    });

    it('keeps an active completed topic from the detail cache visible', () => {
      const state = merge(initialStore, {
        activeAgentId: 'agent-1',
        activeTopicId: 'archived-active',
        topicDataMap: {
          [topicMapKey({ agentId: 'agent-1' })]: {
            currentPage: 0,
            hasMore: true,
            items: [{ id: 'visible', status: 'active', updatedAt: 2 }],
            pageSize: 20,
            total: 2,
          },
        },
        topicDetailMap: {
          'archived-active': { id: 'archived-active', status: 'completed', updatedAt: 1 },
        },
      });

      expect(
        topicSelectors
          .displayTopicsForSidebar(
            20,
            'updatedAt',
            false,
          )(state)
          ?.map(({ id }) => id),
      ).toEqual(['visible', 'archived-active']);
    });

    it('keeps an injected active favorite before regular topics', () => {
      const state = merge(initialStore, {
        activeAgentId: 'agent-1',
        activeTopicId: 'archived-favorite',
        topicDataMap: {
          [topicMapKey({ agentId: 'agent-1' })]: {
            currentPage: 0,
            hasMore: true,
            items: [
              { favorite: true, id: 'visible-favorite', updatedAt: 3 },
              { id: 'regular', updatedAt: 2 },
            ],
            pageSize: 20,
            total: 3,
          },
        },
        topicDetailMap: {
          'archived-favorite': {
            favorite: true,
            id: 'archived-favorite',
            status: 'completed',
            updatedAt: 1,
          },
        },
      });

      expect(
        topicSelectors
          .displayTopicsForSidebar(
            20,
            'updatedAt',
            false,
          )(state)
          ?.map(({ id }) => id),
      ).toEqual(['visible-favorite', 'archived-favorite', 'regular']);
    });

    it('does not duplicate an active topic already in the visible page', () => {
      const state = merge(initialStore, {
        activeAgentId: 'agent-1',
        activeTopicId: 'active',
        topicDataMap: {
          [topicMapKey({ agentId: 'agent-1' })]: {
            currentPage: 0,
            hasMore: false,
            items: [{ id: 'active', updatedAt: 1 }],
            pageSize: 20,
            total: 1,
          },
        },
      });

      expect(topicSelectors.displayTopicsForSidebar(20)(state)).toHaveLength(1);
    });
  });

  describe('groupedTopicsForSidebar', () => {
    const now = Date.now();
    const lastYear = dayjs(now).subtract(1, 'year').valueOf();

    const topicsWithDifferentTimes = [
      {
        id: 'old-created-new-updated',
        title: 'Old but active',
        favorite: false,
        createdAt: lastYear,
        updatedAt: now,
      },
      {
        id: 'new-created-new-updated',
        title: 'New and active',
        favorite: false,
        createdAt: now,
        updatedAt: now,
      },
    ];

    const createStateWithTopics = (topics: any[]) =>
      merge(initialStore, topicState(topicMapKey({ agentId: 'test' }), topics, topics.length));

    it('should group by createdAt when sortBy is createdAt', () => {
      const state = createStateWithTopics(topicsWithDifferentTimes);

      const grouped = topicSelectors.groupedTopicsForSidebar(20, 'createdAt')(state);

      // "Old but active" was created last year, so it should be in a separate group from "New and active"
      expect(grouped.length).toBeGreaterThanOrEqual(2);

      const groupIds = grouped.map((g) => g.id);
      // Should have a group for last year
      expect(groupIds).toContain(dayjs(lastYear).year().toString());
    });

    it('should group by updatedAt when sortBy is updatedAt', () => {
      const state = createStateWithTopics(topicsWithDifferentTimes);

      const grouped = topicSelectors.groupedTopicsForSidebar(20, 'updatedAt')(state);

      // Both topics have updatedAt = now, so they should be in the same group
      expect(grouped).toHaveLength(1);
      expect(grouped[0].id).toBe('today');
      expect(grouped[0].children).toHaveLength(2);
    });

    it('should return empty array when no topics exist', () => {
      const state = merge(initialStore, { activeAgentId: 'test' });

      const grouped = topicSelectors.groupedTopicsForSidebar(20, 'updatedAt')(state);

      expect(grouped).toEqual([]);
    });

    it('should respect pageSize limit', () => {
      const manyTopics = Array.from({ length: 10 }, (_, i) => ({
        id: `topic-${i}`,
        title: `Topic ${i}`,
        favorite: false,
        createdAt: now - i * 1000,
        updatedAt: now - i * 1000,
      }));

      const state = createStateWithTopics(manyTopics);

      const grouped = topicSelectors.groupedTopicsForSidebar(3, 'updatedAt')(state);

      const totalChildren = grouped.reduce((sum, g) => sum + g.children.length, 0);
      expect(totalChildren).toBe(3);
    });

    it('should place the pending group right below favorites in byStatus mode', () => {
      const state = createStateWithTopics([
        {
          id: 'fav',
          title: 'Fav',
          favorite: true,
          status: 'active',
          createdAt: now,
          updatedAt: now,
        },
        {
          id: 'failed',
          title: 'Failed',
          favorite: false,
          status: 'failed',
          createdAt: now,
          updatedAt: now,
        },
        {
          id: 'active',
          title: 'Active',
          favorite: false,
          status: 'active',
          createdAt: now,
          updatedAt: now,
        },
      ]);

      const grouped = topicSelectors.groupedTopicsForSidebar(20, 'updatedAt', 'byStatus')(state);

      // favorites stay pinned at the top; pending follows right below, then the rest
      expect(grouped.map((g) => g.id)).toEqual(['favorite', 'pending', 'active']);
      expect(grouped[1].children.map((t) => t.id)).toEqual(['failed']);
    });

    it('should group by boundDeviceId in byDevice mode', () => {
      const state = createStateWithTopics([
        {
          id: 'on-device-x',
          title: 'On device X',
          favorite: false,
          metadata: { boundDeviceId: 'device-x' },
          createdAt: now,
          updatedAt: now,
        },
        {
          id: 'unbound',
          title: 'Unbound',
          favorite: false,
          createdAt: now,
          updatedAt: now,
        },
      ]);

      const grouped = topicSelectors.groupedTopicsForSidebar(20, 'updatedAt', 'byDevice')(state);

      expect(grouped.map((g) => g.id)).toEqual(['device:device-x', 'no-device']);
    });
  });
});