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.

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

import { merge } from '@/utils/merge';

import type { GlobalState } from '../initialState';
import {
  DEFAULT_HOME_SIDEBAR_EXPANDED_KEYS,
  INITIAL_STATUS,
  initialState,
  MODEL_DETAIL_PANEL_EXPANDABLE_KEYS,
} from '../initialState';
import {
  DEFAULT_SIDEBAR_ITEMS,
  readOverridableField,
  reorderSidebarItems,
  routeOverlayWrites,
  setSidebarSectionHidden,
  SIDEBAR_ACCORDION_KEYS,
  SIDEBAR_SPACER_ID,
  systemStatusSelectors,
} from './systemStatus';

describe('systemStatusSelectors', () => {
  describe('agent view-all sections', () => {
    it('starts the "In sidebar" section collapsed, even over a persisted earlier default', () => {
      expect(systemStatusSelectors.agentListSidebarSectionCollapsed(initialState)).toBe(true);
      // Earlier builds persisted `agentListSidebarSectionCollapsed: false` for everyone.
      const persisted: GlobalState = merge(initialState, {
        status: { agentListSidebarSectionCollapsed: false },
      });
      expect(systemStatusSelectors.agentListSidebarSectionCollapsed(persisted)).toBe(true);

      const expanded: GlobalState = merge(initialState, {
        status: { agentListSidebarSectionExpanded: true },
      });
      expect(systemStatusSelectors.agentListSidebarSectionCollapsed(expanded)).toBe(false);
    });

    it('starts the "Recommended agents" section expanded and remembers a collapse', () => {
      expect(systemStatusSelectors.agentListRecommendedSectionCollapsed(initialState)).toBe(false);
      const collapsed: GlobalState = merge(initialState, {
        status: { agentListRecommendedSectionCollapsed: true },
      });
      expect(systemStatusSelectors.agentListRecommendedSectionCollapsed(collapsed)).toBe(true);
    });
  });

  describe('sessionGroupKeys', () => {
    it('should return expandSessionGroupKeys from status', () => {
      const s: GlobalState = merge(initialState, {
        status: {
          expandSessionGroupKeys: ['group1', 'group2'],
        },
      });
      expect(systemStatusSelectors.sessionGroupKeys(null)(s)).toEqual(['group1', 'group2']);
    });

    it('should return initial value if not set', () => {
      const s: GlobalState = merge(initialState, {
        status: {
          expandSessionGroupKeys: undefined,
        },
      });
      expect(systemStatusSelectors.sessionGroupKeys(null)(s)).toEqual(
        INITIAL_STATUS.expandSessionGroupKeys,
      );
    });
  });

  describe('basic selectors', () => {
    const s: GlobalState = merge(initialState, {
      status: {
        showSystemRole: true,
        mobileShowTopic: true,
        mobileShowPortal: true,
        showAgentBuilderPanel: true,
        showRightPanel: true,
        showLeftPanel: true,
        showFilePanel: true,
        hidePWAInstaller: true,
        isShowCredit: true,
        leftPanelWidth: 300,
        portalWidth: 500,
        filePanelWidth: 400,
        inputHeight: 150,
        threadInputHeight: 100,
      },
    });

    it('should return correct values for basic selectors', () => {
      expect(systemStatusSelectors.showSystemRole(s)).toBe(true);
      expect(systemStatusSelectors.mobileShowTopic(s)).toBe(true);
      expect(systemStatusSelectors.mobileShowPortal(s)).toBe(true);
      expect(systemStatusSelectors.showAgentBuilderPanel(s)).toBe(true);
      expect(systemStatusSelectors.showRightPanel(s)).toBe(true);
      expect(systemStatusSelectors.showLeftPanel(s)).toBe(true);
      expect(systemStatusSelectors.showFilePanel(s)).toBe(true);
      expect(systemStatusSelectors.hidePWAInstaller(s)).toBe(true);
      expect(systemStatusSelectors.isShowCredit(s)).toBe(true);
      expect(systemStatusSelectors.leftPanelWidth(s)).toBe(300);
      expect(systemStatusSelectors.portalWidth(s)).toBe(500);
      expect(systemStatusSelectors.filePanelWidth(s)).toBe(400);
      expect(systemStatusSelectors.wideScreen(s)).toBe(false);
    });

    it('should return default portal width if not set', () => {
      const noPortalWidth = merge(initialState, {
        status: { portalWidth: undefined },
      });
      expect(systemStatusSelectors.portalWidth(noPortalWidth)).toBe(400);
    });

    it('should show the working overview by default only while the right panel is closed', () => {
      const at = (status: { showRightPanel?: boolean; showWorkingOverview?: boolean }) =>
        systemStatusSelectors.showWorkingOverview(merge(initialState, { status }));

      expect(at({ showRightPanel: false, showWorkingOverview: undefined })).toBe(true);
      expect(at({ showRightPanel: true, showWorkingOverview: undefined })).toBe(false);
      expect(at({ showRightPanel: true, showWorkingOverview: true })).toBe(true);
    });

    it('should return workingSidebarWidth from status, defaulting to 360', () => {
      expect(
        systemStatusSelectors.workingSidebarWidth(
          merge(initialState, {
            status: { workingSidebarWidth: 520 },
          }),
        ),
      ).toBe(520);

      expect(
        systemStatusSelectors.workingSidebarWidth(
          merge(initialState, {
            status: { workingSidebarWidth: undefined },
          }),
        ),
      ).toBe(360);
    });

    it('should clamp persisted left panel width to the draggable panel bounds', () => {
      expect(
        systemStatusSelectors.leftPanelWidth(
          merge(initialState, {
            status: { leftPanelWidth: 120 },
          }),
        ),
      ).toBe(240);

      expect(
        systemStatusSelectors.leftPanelWidth(
          merge(initialState, {
            status: { leftPanelWidth: 720 },
          }),
        ),
      ).toBe(400);

      expect(
        systemStatusSelectors.leftPanelWidth(
          merge(initialState, {
            status: { leftPanelWidth: '360px' as unknown as number },
          }),
        ),
      ).toBe(360);
    });
  });

  describe('topicPageSize', () => {
    it('defaults to 20', () => {
      expect(systemStatusSelectors.topicPageSize(initialState)).toBe(20);
    });

    // A value above the server's `getTopics` cap failed every topic list
    // request; earlier builds could persist one from the project sidebar.
    it('clamps a persisted value above the server cap', () => {
      const s: GlobalState = merge(initialState, { status: { topicPageSize: 140 } });
      expect(systemStatusSelectors.topicPageSize(s)).toBe(100);
    });
  });

  describe('modelDetailPanelExpandedKeys', () => {
    it('should expand every section by default', () => {
      const s: GlobalState = {
        ...initialState,
        status: {
          ...initialState.status,
          modelDetailPanelCollapsedKeys: undefined,
        },
      };

      expect(systemStatusSelectors.modelDetailPanelExpandedKeys(s)).toEqual(
        MODEL_DETAIL_PANEL_EXPANDABLE_KEYS,
      );
    });

    it('should exclude collapsed keys stored by the user', () => {
      const s: GlobalState = merge(initialState, {
        status: {
          modelDetailPanelCollapsedKeys: ['abilities', 'config'],
        },
      });

      expect(systemStatusSelectors.modelDetailPanelExpandedKeys(s)).toEqual(['rating', 'pricing']);
    });

    it('should ignore a legacy persisted expanded-keys array and keep new sections expanded', () => {
      // before the collapsed-keys migration, an expanded-keys array persisted prior to the
      // rating section shipping kept it collapsed forever — the legacy field must be inert
      const s: GlobalState = merge(initialState, {
        status: {
          modelDetailPanelExpandedKeys: ['pricing', 'config'],
        } as never,
      });

      expect(systemStatusSelectors.modelDetailPanelExpandedKeys(s)).toEqual(
        MODEL_DETAIL_PANEL_EXPANDABLE_KEYS,
      );
    });
  });

  describe('modelSwitchPanelGroupMode', () => {
    it('should default to byModel so the everyday list looks unchanged before the user flips the switch', () => {
      const s: GlobalState = {
        ...initialState,
        status: { ...initialState.status, modelSwitchPanelGroupBy: undefined },
      };

      expect(systemStatusSelectors.modelSwitchPanelGroupMode(s)).toBe('byModel');
    });

    it('should not seed the preference into the initial status', () => {
      // `updateSystemStatus` persists the whole merged status, so a seeded
      // value would be written to storage as if the user had chosen it.
      expect(INITIAL_STATUS).not.toHaveProperty('modelSwitchPanelGroupBy');
    });

    it('should return the persisted byProvider preference', () => {
      const s: GlobalState = merge(initialState, {
        status: { modelSwitchPanelGroupBy: 'byProvider' },
      });

      expect(systemStatusSelectors.modelSwitchPanelGroupMode(s)).toBe('byProvider');
    });

    it('should ignore the legacy seeded byProvider value from a pre-upgrade persisted status', () => {
      // Before the key was renamed, the store seeded `byProvider` and persisted
      // it for everyone; the switch itself was hidden behind developer tools,
      // so these users were effectively on `byModel` and must stay there.
      const s: GlobalState = merge(initialState, {
        status: { modelSwitchPanelGroupMode: 'byProvider' } as Record<string, unknown>,
      });

      expect(systemStatusSelectors.modelSwitchPanelGroupMode(s)).toBe('byModel');
    });
  });

  describe('taskListViewMode', () => {
    it('should restore the persisted task board view', () => {
      const s: GlobalState = {
        ...initialState,
        status: {
          ...initialState.status,
          taskListViewMode: 'kanban',
        },
      };

      expect(systemStatusSelectors.taskListViewMode(s)).toBe('kanban');
    });

    it('should default legacy status without a task view mode to list', () => {
      const s: GlobalState = {
        ...initialState,
        status: {
          ...initialState.status,
          taskListViewMode: undefined,
        },
      };

      expect(systemStatusSelectors.taskListViewMode(s)).toBe('list');
    });
  });

  describe('sidebarItems', () => {
    it('should return DEFAULT_SIDEBAR_ITEMS when no data is set', () => {
      expect(systemStatusSelectors.sidebarItems(null)(initialState)).toEqual(DEFAULT_SIDEBAR_ITEMS);
    });

    it('should re-anchor the spacer immediately after the accordion block', () => {
      // Stored order has pages/tasks between the accordion and the first default-bottom item.
      // The invariant moves them into the bottom group (after the spacer).
      const stored = [
        'private',
        'agent',
        'recents',
        'pages',
        'tasks',
        'image',
        'community',
        'resource',
        'memory',
      ];
      const s: GlobalState = merge(initialState, {
        status: { sidebarItems: stored },
      });
      expect(systemStatusSelectors.sidebarItems(null)(s)).toEqual([
        // Defaults missing from a saved layout (here the newer `project`,
        // `goals`, `dashboard` and `favorites`) are backfilled.
        'goals',
        'project',
        'dashboard',
        'favorites',
        'agent',
        'channels',
        'recents',
        SIDEBAR_SPACER_ID,
        'pages',
        'tasks',
        'image',
        'community',
        'resource',
      ]);
    });

    it('should preserve a canonically-positioned spacer', () => {
      const stored = [
        'pages',
        'goals',
        'project',
        'dashboard',
        'favorites',
        'recents',
        'private',
        'agent',
        SIDEBAR_SPACER_ID,
        'image',
        'tasks',
        'community',
        'resource',
        'memory',
      ];
      const s: GlobalState = merge(initialState, {
        status: { sidebarItems: stored },
      });
      // The former Private section is merged into Agents; Channels, saved
      // before they joined the layout, keep their spot right below Agents.
      expect(systemStatusSelectors.sidebarItems(null)(s)).toEqual(
        stored
          .filter((key) => key !== 'private' && key !== 'memory')
          .flatMap((key) => (key === 'agent' ? ['agent', 'channels'] : [key])),
      );
    });

    it('should re-anchor the spacer when stored above the accordion', () => {
      // Simulates the dropdown-menu "move agent down" path that previously left
      // the spacer floating above the accordion block.
      const stored = [
        'tasks',
        'pages',
        SIDEBAR_SPACER_ID,
        'recents',
        'private',
        'agent',
        'image',
        'community',
        'resource',
        'memory',
      ];
      const s: GlobalState = merge(initialState, {
        status: { sidebarItems: stored },
      });
      expect(systemStatusSelectors.sidebarItems(null)(s)).toEqual([
        'tasks',
        'pages',
        'goals',
        'project',
        'dashboard',
        'resource',
        'image',
        'community',
        'favorites',
        'recents',
        'agent',
        'channels',
        SIDEBAR_SPACER_ID,
      ]);
    });

    it('should backfill favorites at the head of a saved accordion block', () => {
      const stored = [
        'tasks',
        'goals',
        'dashboard',
        'resource',
        'recents',
        'project',
        'private',
        'agent',
        SIDEBAR_SPACER_ID,
        'image',
        'community',
        'memory',
      ];
      const s: GlobalState = merge(initialState, {
        status: { sidebarItems: stored },
      });
      expect(systemStatusSelectors.sidebarItems(null)(s)).toEqual([
        'tasks',
        // Projects left the accordion for a link, so a saved layout lifts it below Goals.
        'goals',
        'project',
        'dashboard',
        'resource',
        // Untouched former bottom links move above the accordion.
        'image',
        'community',
        'favorites',
        'recents',
        'agent',
        'channels',
        SIDEBAR_SPACER_ID,
      ]);
    });

    it.each([
      ['April', ['pages', 'recents', 'agent', 'community', 'resource', 'memory']],
      [
        'June',
        [
          'tasks',
          'pages',
          'recents',
          'agent',
          SIDEBAR_SPACER_ID,
          'image',
          'community',
          'resource',
          'memory',
        ],
      ],
      [
        'August',
        [
          'tasks',
          'resource',
          'recents',
          'private',
          'agent',
          SIDEBAR_SPACER_ID,
          'image',
          'community',
          'pages',
          'memory',
        ],
      ],
    ])('should move every link of the former %s default above the sections', (_, stored) => {
      const items = systemStatusSelectors.sidebarItems(null)(
        merge(initialState, { status: { sidebarItems: stored } }),
      );
      const firstSection = items.findIndex((key) => SIDEBAR_ACCORDION_KEYS.has(key));

      expect(items.slice(items.indexOf(SIDEBAR_SPACER_ID) + 1)).toEqual([]);
      // They land in default order, below the links that lead the list.
      expect(items.indexOf('tasks')).toBeLessThan(items.indexOf('resource'));
      expect(items.indexOf('project')).toBeLessThan(items.indexOf('image'));
      expect(items.indexOf('resource')).toBeLessThan(items.indexOf('image'));
      expect(items.indexOf('image')).toBeLessThan(items.indexOf('community'));
      expect(items.indexOf('community')).toBeLessThan(firstSection);
    });

    it('should keep Generation and Plugins pinned at the bottom once saved that way', () => {
      // A layout saved after the move no longer lists `memory`.
      const stored = ['tasks', 'recents', 'agent', SIDEBAR_SPACER_ID, 'image', 'community'];
      const items = systemStatusSelectors.sidebarItems(null)(
        merge(initialState, { status: { sidebarItems: stored } }),
      );
      const spacerIdx = items.indexOf(SIDEBAR_SPACER_ID);
      expect(items.slice(spacerIdx + 1)).toEqual(['image', 'community']);
    });

    it('should leave a hand-arranged bottom group in place and only drop Memory', () => {
      const stored = ['recents', 'agent', SIDEBAR_SPACER_ID, 'tasks', 'image', 'memory'];
      const items = systemStatusSelectors.sidebarItems(null)(
        merge(initialState, { status: { sidebarItems: stored } }),
      );
      const spacerIdx = items.indexOf(SIDEBAR_SPACER_ID);
      expect(items.slice(spacerIdx + 1)).toEqual(['tasks', 'image']);
      expect(items).not.toContain('memory');
    });

    it('should lift projects above the accordion when tasks sit below the spacer', () => {
      const stored = [
        'goals',
        'favorites',
        'project',
        'recents',
        'agent',
        SIDEBAR_SPACER_ID,
        'tasks',
        'image',
      ];
      const s: GlobalState = merge(initialState, {
        status: { sidebarItems: stored },
      });
      const items = systemStatusSelectors.sidebarItems(null)(s);
      expect(items.slice(0, 3)).toEqual(['goals', 'project', 'dashboard']);
      expect(items.indexOf('project')).toBeLessThan(items.indexOf('favorites'));
    });

    it('should keep projects where the user moved them outside the accordion', () => {
      const stored = [
        'tasks',
        'goals',
        'dashboard',
        'resource',
        'favorites',
        'recents',
        'agent',
        SIDEBAR_SPACER_ID,
        'image',
        'project',
        'community',
        'memory',
      ];
      const s: GlobalState = merge(initialState, {
        status: { sidebarItems: stored },
      });
      // The former Private section is merged into Agents; Channels, saved
      // before they joined the layout, keep their spot right below Agents.
      expect(systemStatusSelectors.sidebarItems(null)(s)).toEqual(
        stored
          .filter((key) => key !== 'private' && key !== 'memory')
          .flatMap((key) => (key === 'agent' ? ['agent', 'channels'] : [key])),
      );
    });

    it('should slot missing top-group defaults before the accordion block', () => {
      const s: GlobalState = merge(initialState, {
        status: { sidebarItems: ['agent', 'recents'] },
      });
      const items = systemStatusSelectors.sidebarItems(null)(s);
      const spacerIdx = items.indexOf(SIDEBAR_SPACER_ID);
      // every known key is present
      expect(items).toContain('tasks');
      expect(items).toContain('community');
      expect(items).toContain('resource');
      expect(items).not.toContain('memory');
      // accordion block is flush against the spacer, in stored order, with
      // Channels kept right below Agents
      expect(items.slice(spacerIdx - 3, spacerIdx)).toEqual(['agent', 'channels', 'recents']);
      // missing top-group defaults slot in just before the accordion
      expect(items.indexOf('tasks')).toBeLessThan(spacerIdx - 3);
      expect(items.indexOf('project')).toBe(items.indexOf('goals') + 1);
      expect(items.indexOf('resource')).toBeLessThan(spacerIdx - 3);
      expect(items.indexOf('image')).toBeLessThan(spacerIdx - 3);
      // Pages live in Docs now; the retired entry is not backfilled
      expect(items).not.toContain('pages');
    });

    it('should keep Channels where the user moved them in the accordion block', () => {
      const s: GlobalState = merge(initialState, {
        status: { sidebarItems: ['channels', 'favorites', 'recents', 'agent', SIDEBAR_SPACER_ID] },
      });
      const items = systemStatusSelectors.sidebarItems(null)(s);
      const spacerIdx = items.indexOf(SIDEBAR_SPACER_ID);
      expect(items.slice(spacerIdx - 4, spacerIdx)).toEqual([
        'channels',
        'favorites',
        'recents',
        'agent',
      ]);
      expect(items.filter((key) => key === 'channels')).toHaveLength(1);
    });

    it('should migrate legacy `sidebarSectionOrder` accordion order into the default layout', () => {
      const s: GlobalState = merge(initialState, {
        status: { sidebarSectionOrder: ['agent', 'recents'] },
      });
      const items = systemStatusSelectors.sidebarItems(null)(s);
      // accordion slot uses the user's legacy order; `favorites` (added after
      // the legacy state was saved) is backfilled at the head of the block.
      expect(items).toEqual([
        'tasks',
        'goals',
        'project',
        'dashboard',
        'resource',
        'image',
        'community',
        'favorites',
        'agent',
        'channels',
        'recents',
        SIDEBAR_SPACER_ID,
      ]);
    });

    it('should preserve legacy accordion order when migrating from `sidebarSectionOrder`', () => {
      const s: GlobalState = merge(initialState, {
        status: { sidebarSectionOrder: ['recents', 'agent'] },
      });
      const items = systemStatusSelectors.sidebarItems(null)(s);
      // recents/agent keep their legacy order.
      expect(items).toEqual([
        'tasks',
        'goals',
        'project',
        'dashboard',
        'resource',
        'image',
        'community',
        'favorites',
        'recents',
        'agent',
        'channels',
        SIDEBAR_SPACER_ID,
      ]);
    });

    it('should prefer `sidebarItems` over legacy `sidebarSectionOrder` when both are set', () => {
      const s: GlobalState = merge(initialState, {
        status: {
          sidebarItems: ['pages', 'recents', 'agent', 'community', 'resource', 'memory'],
          sidebarSectionOrder: ['agent', 'recents'],
        },
      });
      const items = systemStatusSelectors.sidebarItems(null)(s);
      expect(items.indexOf('recents')).toBeLessThan(items.indexOf('agent'));
    });
  });

  describe('sidebarExpandedKeys', () => {
    it('should expand sidebar accordion sections by default', () => {
      const s: GlobalState = {
        ...initialState,
        status: {
          ...initialState.status,
          sidebarExpandedKeys: undefined,
        },
      };

      expect(systemStatusSelectors.sidebarExpandedKeys(null)(s)).toEqual(
        DEFAULT_HOME_SIDEBAR_EXPANDED_KEYS,
      );
    });

    it('should preserve an empty stored preference when all sections are collapsed', () => {
      const s: GlobalState = merge(initialState, {
        status: { sidebarExpandedKeys: [] },
      });

      expect(systemStatusSelectors.sidebarExpandedKeys(null)(s)).toEqual([]);
    });
  });

  describe('reorderSidebarItems', () => {
    // Mirrors the shape returned by the sidebarItems selector — spacer is always
    // present, anchored immediately after the accordion block.
    const DEFAULT = [
      'pages',
      'recents',
      'agent',
      SIDEBAR_SPACER_ID,
      'community',
      'resource',
      'memory',
    ];

    it('should move a non-accordion item normally', () => {
      // move `community` (idx 4) up to idx 0
      expect(reorderSidebarItems(DEFAULT, 4, 0)).toEqual([
        'community',
        'pages',
        'recents',
        'agent',
        SIDEBAR_SPACER_ID,
        'resource',
        'memory',
      ]);
    });

    it('should snap a top-group item past the accordion when dragged between accordion items (drag down)', () => {
      // `pages` (idx 0) dragged down to idx 2 (between recents & agent) →
      // pushed past the accordion, lands in the bottom group.
      expect(reorderSidebarItems(DEFAULT, 0, 2)).toEqual([
        'recents',
        'agent',
        SIDEBAR_SPACER_ID,
        'pages',
        'community',
        'resource',
        'memory',
      ]);
    });

    it('should snap a bottom-group item before the accordion when dragged between accordion items (drag up)', () => {
      // `community` (idx 4) dragged up to idx 2 (between recents & agent) →
      // lands ahead of the accordion (top group).
      expect(reorderSidebarItems(DEFAULT, 4, 2)).toEqual([
        'pages',
        'community',
        'recents',
        'agent',
        SIDEBAR_SPACER_ID,
        'resource',
        'memory',
      ]);
    });

    it('should move the whole accordion block when moving `recents` up past the block boundary', () => {
      // `recents` (idx 1) moveUp → idx 0. Block [recents, agent] slides to top,
      // spacer follows it.
      expect(reorderSidebarItems(DEFAULT, 1, 0)).toEqual([
        'recents',
        'agent',
        SIDEBAR_SPACER_ID,
        'pages',
        'community',
        'resource',
        'memory',
      ]);
    });

    it('should snap the accordion back when moving `agent` down past the spacer', () => {
      // `agent` (idx 2) moveDown → idx 3 (past spacer). Normalization re-anchors
      // the spacer behind the accordion, making the move a visible no-op.
      expect(reorderSidebarItems(DEFAULT, 2, 3)).toBe(DEFAULT);
    });

    it('should swap recents and agent within the block', () => {
      // `recents` (idx 1) moveDown → idx 2. Within block, so just swap.
      expect(reorderSidebarItems(DEFAULT, 1, 2)).toEqual([
        'pages',
        'agent',
        'recents',
        SIDEBAR_SPACER_ID,
        'community',
        'resource',
        'memory',
      ]);
    });

    it('should be a no-op when from === to', () => {
      expect(reorderSidebarItems(DEFAULT, 2, 2)).toBe(DEFAULT);
    });

    it('should keep the spacer behind the accordion after moving a non-accordion item', () => {
      const items = [
        'tasks',
        'pages',
        'recents',
        'agent',
        SIDEBAR_SPACER_ID,
        'image',
        'community',
        'resource',
        'memory',
      ];
      // Move `pages` (idx 1) to the very end. Spacer stays right after `agent`.
      const next = reorderSidebarItems(items, 1, items.length - 1);
      const spacerIdx = next.indexOf(SIDEBAR_SPACER_ID);
      expect(next[spacerIdx - 1]).toBe('agent');
      expect(next[spacerIdx - 2]).toBe('recents');
      expect(next.at(-1)).toBe('pages');
    });
  });

  describe('workspace overlay', () => {
    describe('readOverridableField', () => {
      it('returns the top-level value when workspaceId is null', () => {
        const status = {
          ...initialState.status,
          expandSessionGroupKeys: ['personal'],
          workspace: { expandSessionGroupKeys: ['ws'] },
        };
        expect(readOverridableField(status, 'expandSessionGroupKeys', null)).toEqual(['personal']);
      });

      it('returns the overlay value when workspaceId is set and overlay carries the field', () => {
        const status = {
          ...initialState.status,
          expandSessionGroupKeys: ['personal'],
          workspace: { expandSessionGroupKeys: ['ws'] },
        };
        expect(readOverridableField(status, 'expandSessionGroupKeys', 'ws-1')).toEqual(['ws']);
      });

      it('falls back to top-level when overlay is missing the field', () => {
        const status = {
          ...initialState.status,
          hiddenSidebarSections: ['recents'],
          workspace: { expandSessionGroupKeys: ['ws'] },
        };
        expect(readOverridableField(status, 'hiddenSidebarSections', 'ws-1')).toEqual(['recents']);
      });
    });

    describe('selectors honour the overlay', () => {
      const stateWithOverlay: GlobalState = merge(initialState, {
        status: {
          expandSessionGroupKeys: ['personal-group'],
          hiddenSidebarSections: [],
          sidebarItems: undefined,
          sidebarExpandedKeys: ['recents', 'agent', 'private'],
          workspace: {
            expandSessionGroupKeys: ['ws-group'],
            hiddenSidebarSections: ['recents'],
            sidebarExpandedKeys: ['agent'],
          },
        },
      });

      it('sessionGroupKeys prefers overlay in workspace mode', () => {
        expect(systemStatusSelectors.sessionGroupKeys('ws-1')(stateWithOverlay)).toEqual([
          'ws-group',
        ]);
      });

      it('sessionGroupKeys returns personal value in personal mode', () => {
        expect(systemStatusSelectors.sessionGroupKeys(null)(stateWithOverlay)).toEqual([
          'personal-group',
        ]);
      });

      it('keeps the merged entry visible in a workspace if either old entry was visible', () => {
        const workspaceHidden = (keys: string[]) =>
          systemStatusSelectors.hiddenSidebarSections('ws-1')(
            merge(initialState, { status: { workspace: { hiddenSidebarSections: keys } } }),
          );
        expect(workspaceHidden(['tasks'])).not.toContain('tasks');
        expect(workspaceHidden(['tasks', 'goals'])).toContain('tasks');
      });

      it('keeps the merged personal entry visible if either old entry was visible', () => {
        const personalHidden = (keys: string[]) =>
          systemStatusSelectors.hiddenSidebarSections(null)(
            merge(initialState, {
              status: { hiddenSidebarSections: keys },
            }),
          );
        expect(personalHidden(['tasks'])).not.toContain('tasks');
        expect(personalHidden(['goals'])).not.toContain('tasks');
        const hidden = setSidebarSectionHidden(['recents'], 'tasks', true);
        expect(personalHidden(hidden)).toContain('tasks');
        expect(setSidebarSectionHidden(hidden, 'tasks', false)).toEqual(['recents']);
      });

      it('hiddenSidebarSections prefers overlay in workspace mode', () => {
        expect(systemStatusSelectors.hiddenSidebarSections('ws-1')(stateWithOverlay)).toEqual([
          'recents',
        ]);
      });

      it('sidebarExpandedKeys prefers overlay in workspace mode', () => {
        expect(systemStatusSelectors.sidebarExpandedKeys('ws-1')(stateWithOverlay)).toEqual([
          'agent',
        ]);
      });

      it('sidebarItems falls back to default when overlay omits and top-level omits', () => {
        // Both top-level and workspace.sidebarItems are undefined → default
        expect(systemStatusSelectors.sidebarItems('ws-1')(stateWithOverlay)).toEqual(
          DEFAULT_SIDEBAR_ITEMS,
        );
      });

      it('hides `recents` by default in workspace mode when overlay is untouched', () => {
        const s: GlobalState = merge(initialState, {
          status: { hiddenSidebarSections: undefined, workspace: undefined },
        });
        expect(systemStatusSelectors.hiddenSidebarSections('ws-1')(s)).toEqual(['recents']);
      });

      it('keeps `recents` visible in personal mode by default', () => {
        const s: GlobalState = merge(initialState, {
          status: { hiddenSidebarSections: undefined, workspace: undefined },
        });
        expect(systemStatusSelectors.hiddenSidebarSections(null)(s)).toEqual([]);
      });

      it('layers workspace defaults on top of personal-mode hides when overlay is untouched', () => {
        const s: GlobalState = merge(initialState, {
          status: { hiddenSidebarSections: ['pages'], workspace: undefined },
        });
        expect(systemStatusSelectors.hiddenSidebarSections('ws-1')(s)).toEqual([
          'pages',
          'recents',
        ]);
      });

      it('respects an explicit empty overlay as "show everything in this workspace"', () => {
        const s: GlobalState = merge(initialState, {
          status: { hiddenSidebarSections: ['recents'], workspace: { hiddenSidebarSections: [] } },
        });
        expect(systemStatusSelectors.hiddenSidebarSections('ws-1')(s)).toEqual([]);
      });
    });

    describe('routeOverlayWrites', () => {
      it('passes patch through unchanged when workspaceId is null', () => {
        const patch = { hiddenSidebarSections: ['recents'], leftPanelWidth: 300 };
        expect(routeOverlayWrites(patch, null)).toBe(patch);
      });

      it('routes whitelisted fields into the workspace overlay', () => {
        const patch = { hiddenSidebarSections: ['recents'], expandSessionGroupKeys: ['x'] };
        expect(routeOverlayWrites(patch, 'ws-1')).toEqual({
          workspace: {
            hiddenSidebarSections: ['recents'],
            expandSessionGroupKeys: ['x'],
          },
        });
      });

      it('keeps non-whitelisted fields at the top level even in workspace mode', () => {
        const patch = { leftPanelWidth: 300, language: 'zh-CN' as const };
        expect(routeOverlayWrites(patch, 'ws-1')).toEqual({
          leftPanelWidth: 300,
          language: 'zh-CN',
        });
      });

      it('splits a mixed patch into top-level and workspace overlay', () => {
        const patch = {
          leftPanelWidth: 300,
          hiddenSidebarSections: ['recents'],
          sidebarItems: ['agent'],
        };
        expect(routeOverlayWrites(patch, 'ws-1')).toEqual({
          leftPanelWidth: 300,
          workspace: {
            hiddenSidebarSections: ['recents'],
            sidebarItems: ['agent'],
          },
        });
      });

      it('preserves an explicit `workspace` key while routing whitelisted fields', () => {
        const patch = {
          hiddenSidebarSections: ['recents'],
          workspace: { sidebarItems: ['existing'] as string[] },
        };
        expect(routeOverlayWrites(patch, 'ws-1')).toEqual({
          workspace: {
            sidebarItems: ['existing'],
            hiddenSidebarSections: ['recents'],
          },
        });
      });
    });
  });

  describe('teamBoardAttentionCollapsed', () => {
    // Open by default: a first-time viewer must see what needs attention.
    it('reads as open when the viewer has never folded the list', () => {
      const s: GlobalState = merge(initialState, { status: {} });

      expect(systemStatusSelectors.teamBoardAttentionCollapsed(s)).toBe(false);
    });

    it('keeps the list folded once the viewer put it away', () => {
      const s: GlobalState = merge(initialState, {
        status: { teamBoardAttentionCollapsed: true },
      });

      expect(systemStatusSelectors.teamBoardAttentionCollapsed(s)).toBe(true);
    });
  });

  describe('homeGoalsCollapsed', () => {
    // The goals card opens by default: a first-time viewer must see the goals,
    // not an unexplained folded header.
    it('reads as open when the viewer has never folded the card', () => {
      const s: GlobalState = merge(initialState, { status: {} });

      expect(systemStatusSelectors.homeGoalsCollapsed(s)).toBe(false);
    });

    it('keeps the card folded once the viewer put it away', () => {
      const s: GlobalState = merge(initialState, { status: { homeGoalsCollapsed: true } });

      expect(systemStatusSelectors.homeGoalsCollapsed(s)).toBe(true);
    });
  });

  describe('projectOnboardingDismissed', () => {
    it('is false until the card of that project is dismissed', () => {
      const s: GlobalState = merge(initialState, {
        status: { dismissedProjectOnboarding: { 'project-1': true } },
      });
      expect(systemStatusSelectors.projectOnboardingDismissed('project-1')(s)).toBe(true);
      expect(systemStatusSelectors.projectOnboardingDismissed('project-2')(s)).toBe(false);
      expect(systemStatusSelectors.projectOnboardingDismissed('project-2')(initialState)).toBe(
        false,
      );
    });
  });
});