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.

29.1 KB
Raw Blame
import { type TopicGroupMode } from '@/types/topic';

import type {
  AgentDocumentSort,
  ChannelListSort,
  DocsPageSectionKey,
  DocsPageSectionView,
  GlobalState,
  ModelDetailPanelExpandedKey,
  ProjectListSortBy,
  ProjectListViewMode,
  ProjectTopicSubGroupMode,
  SystemStatus,
  WorkspaceOverridableField,
} from '../initialState';
import {
  DEFAULT_DOCS_PAGE_SECTION_VIEW,
  DEFAULT_HOME_SIDEBAR_EXPANDED_KEYS,
  INITIAL_STATUS,
  MODEL_DETAIL_PANEL_EXPANDABLE_KEYS,
  WORKSPACE_OVERRIDABLE_FIELDS,
} from '../initialState';

/**
 * Read a workspace-overridable field from SystemStatus.
 * When `workspaceId` is non-null and the overlay carries the field, returns the overlay
 * value; otherwise falls back to the top-level (personal mode) value.
 */
export const readOverridableField = <K extends WorkspaceOverridableField>(
  status: SystemStatus,
  field: K,
  workspaceId: string | null,
): SystemStatus[K] => {
  if (workspaceId) {
    const overlay = status.workspace?.[field];
    if (overlay !== undefined) return overlay as SystemStatus[K];
  }
  return status[field];
};

const OVERRIDABLE_SET = new Set<string>(WORKSPACE_OVERRIDABLE_FIELDS);

/**
 * Reshape an `updateSystemStatus` patch when the user is inside a workspace:
 * whitelisted fields land in `workspace.*` so they do not bleed into personal
 * mode. Non-whitelisted fields stay at the top level. An explicit `workspace`
 * key in the patch is preserved and merged with the routed overlay.
 *
 * Pass `workspaceId = null` to bypass routing (init path, personal mode).
 */
export const routeOverlayWrites = (
  patch: Partial<SystemStatus>,
  workspaceId: string | null,
): Partial<SystemStatus> => {
  if (!workspaceId) return patch;

  const { workspace: explicitOverlay, ...rest } = patch;
  const overlayUpdates: Partial<Pick<SystemStatus, WorkspaceOverridableField>> = {};
  const topLevel: Partial<SystemStatus> = {};

  for (const key of Object.keys(rest)) {
    if (OVERRIDABLE_SET.has(key)) {
      (overlayUpdates as any)[key] = (rest as any)[key];
    } else {
      (topLevel as any)[key] = (rest as any)[key];
    }
  }

  const overlay = { ...explicitOverlay, ...overlayUpdates };
  return Object.keys(overlay).length > 0 ? { ...topLevel, workspace: overlay } : topLevel;
};

export const systemStatus = (s: GlobalState) => s.status;

export const NAV_PANEL_MIN_WIDTH = 240;
export const NAV_PANEL_MAX_WIDTH = 400;

const normalizeNavPanelWidth = (width: number | string | undefined): number => {
  const parsed = typeof width === 'string' ? Number.parseInt(width) : width;
  const fallback = INITIAL_STATUS.leftPanelWidth;

  if (!parsed || !Number.isFinite(parsed)) return fallback;

  return Math.min(NAV_PANEL_MAX_WIDTH, Math.max(NAV_PANEL_MIN_WIDTH, parsed));
};

const agentBuilderPanelWidth = (s: GlobalState) => s.status.agentBuilderPanelWidth || 360;

const sessionGroupKeys =
  (workspaceId: string | null) =>
  (s: GlobalState): string[] => {
    const value = readOverridableField(s.status, 'expandSessionGroupKeys', workspaceId);
    return value || INITIAL_STATUS.expandSessionGroupKeys;
  };

const collapsedTopicGroupKeys =
  (mode: TopicGroupMode) =>
  (s: GlobalState): string[] | undefined =>
    s.status.collapsedTopicGroupKeysByMode?.[mode];

const docsPageSectionView =
  (section: DocsPageSectionKey) =>
  (s: GlobalState): DocsPageSectionView => {
    const stored = s.status.docsPageSectionViews?.[section];
    return stored
      ? { ...DEFAULT_DOCS_PAGE_SECTION_VIEW, ...stored }
      : DEFAULT_DOCS_PAGE_SECTION_VIEW;
  };

const projectTopicSubGroupMode =
  (groupId: string) =>
  (s: GlobalState): ProjectTopicSubGroupMode =>
    s.status.projectTopicSubGroupModeByGroup?.[groupId] ?? 'none';

const agentSidebarSections =
  (agentId: string | undefined) =>
  (s: GlobalState): Record<string, boolean> | undefined =>
    agentId ? s.status.expandAgentSidebarSectionsByAgent?.[agentId] : undefined;

const projectSidebarSections =
  (projectId: string | undefined) =>
  (s: GlobalState): Record<string, boolean> | undefined =>
    projectId ? s.status.expandProjectSidebarSectionsByProject?.[projectId] : undefined;

const projectOnboardingDismissed =
  (projectId: string | undefined) =>
  (s: GlobalState): boolean =>
    Boolean(projectId && s.status.dismissedProjectOnboarding?.[projectId]);

/** Whether the topic list owned by `ownerId` (agent / group / project) shows only my topics. */
const topicOnlyMine =
  (ownerId: string | undefined) =>
  (s: GlobalState): boolean =>
    !!ownerId && !!s.status.topicOnlyMineByAgent?.[ownerId];

/** Upper bound of `topic.getTopics`'s `pageSize` input on the server. */
export const MAX_TOPIC_PAGE_SIZE = 100;

/**
 * Clamped to the server's cap: the project sidebar's "load more" used to grow
 * the persisted value past 100, after which every topic list request failed
 * validation. Clamping on read recovers users who already persisted it.
 */
const topicPageSize = (s: GlobalState): number =>
  Math.min(s.status.topicPageSize || 20, MAX_TOPIC_PAGE_SIZE);

const agentPageSize = (s: GlobalState): number => s.status.agentPageSize || 5;

const privateAgentPageSize = (s: GlobalState): number => s.status.privateAgentPageSize || 5;

const recentPageSize = (s: GlobalState): number => s.status.recentPageSize || 5;

const pagePageSize = (s: GlobalState): number => s.status.pagePageSize || 20;
const taskListViewOptions = (s: GlobalState) =>
  s.status.taskListViewOptions || {
    groupBy: 'status',
    nestedSubTasks: true,
    orderBy: 'updatedAt',
    orderCompletedByRecency: true,
    orderDirection: 'asc',
    showSubTasks: false,
    subGroupBy: 'none',
  };

const EMPTY_TASK_LIST_FILTERS: NonNullable<GlobalState['status']['taskListFilters']> = [];

const taskListFilters = (s: GlobalState) => s.status.taskListFilters ?? EMPTY_TASK_LIST_FILTERS;

const taskListFilter = (scope: string) => (s: GlobalState) =>
  taskListFilters(s).find((entry) => entry.scope === scope)?.filter;

const taskListViewMode = (s: GlobalState) => s.status.taskListViewMode ?? 'list';

// Default the inline composer to collapsed so a populated task list keeps the
// records at the top of the fold; the empty-state hero still shows the full
// composer, and the header "+" expands it inline on demand.
const taskCreateInlineCollapsed = (s: GlobalState): boolean =>
  s.status.taskCreateInlineCollapsed ?? true;

export const DEFAULT_KANBAN_HIDDEN_COLUMNS: string[] = ['done', 'canceled'];

const taskKanbanHiddenColumns = (s: GlobalState): string[] =>
  s.status.taskKanbanHiddenColumns ?? DEFAULT_KANBAN_HIDDEN_COLUMNS;

const taskKanbanHiddenPanelCollapsed = (s: GlobalState): boolean =>
  s.status.taskKanbanHiddenPanelCollapsed ?? false;

export const DEFAULT_HIDDEN_SECTIONS: string[] = [];

/** Sections hidden by default in workspace mode until the user customizes
 * sidebar visibility. `recents` lives in personal mode where the catch-all
 * stream is useful, but in a workspace the agent/project lists are the
 * primary entry points — surfacing recents on top adds noise. */
export const WORKSPACE_DEFAULT_HIDDEN_SECTIONS: string[] = ['recents'];

/** Sections hidden by default for the given mode. The customize-sidebar
 * "Reset to default" path uses this so resetting in a workspace restores
 * the workspace defaults, not the empty personal-mode defaults. */
export const getDefaultHiddenSections = (isWorkspaceMode: boolean): string[] =>
  isWorkspaceMode ? [...WORKSPACE_DEFAULT_HIDDEN_SECTIONS] : DEFAULT_HIDDEN_SECTIONS;

/** Tasks and Goals share one sidebar entry, so one control hides both. */
export const setSidebarSectionHidden = (hidden: string[], key: string, hide: boolean): string[] => {
  const keys = key === 'tasks' ? ['tasks', 'goals'] : [key];
  const remaining = hidden.filter((item) => !keys.includes(item));
  return hide ? [...remaining, ...keys] : remaining;
};

// Keep the combined entry reachable if either destination was visible before the merge.
const keepCombinedTasksEntry = (hidden: string[]): string[] =>
  hidden.includes('tasks') && !hidden.includes('goals')
    ? hidden.filter((key) => key !== 'tasks')
    : hidden;

const hiddenSidebarSections =
  (workspaceId: string | null) =>
  (s: GlobalState): string[] => {
    if (workspaceId) {
      const overlay = s.status.workspace?.hiddenSidebarSections;
      // Once the user touches sidebar visibility in this workspace the overlay
      // owns the list — including an explicit empty array meaning "show all".
      if (overlay !== undefined)
        return keepCombinedTasksEntry(normalizeLegacyHiddenSections(overlay));
      // Untouched workspace: inherit any personal-mode hides and layer the
      // workspace defaults on top so `recents` starts collapsed.
      const personal = s.status.hiddenSidebarSections ?? DEFAULT_HIDDEN_SECTIONS;
      const merged = [...normalizeLegacyHiddenSections(personal)];
      for (const k of WORKSPACE_DEFAULT_HIDDEN_SECTIONS) {
        if (!merged.includes(k)) merged.push(k);
      }
      return keepCombinedTasksEntry(merged);
    }
    return keepCombinedTasksEntry(
      normalizeLegacyHiddenSections(s.status.hiddenSidebarSections ?? DEFAULT_HIDDEN_SECTIONS),
    );
  };

const sidebarExpandedKeys =
  (workspaceId: string | null) =>
  (s: GlobalState): string[] =>
    normalizeLegacyExpandedKeys(
      readOverridableField(s.status, 'sidebarExpandedKeys', workspaceId) ??
        DEFAULT_HOME_SIDEBAR_EXPANDED_KEYS,
    );

/** Sentinel id representing the flex spacer slot. Its position in `sidebarItems`
 * determines where the sidebar pushes items to the bottom. */
export const SIDEBAR_SPACER_ID = '__spacer__';

export const DEFAULT_SIDEBAR_ITEMS: string[] = [
  'tasks',
  'goals',
  'project',
  'dashboard',
  'resource',
  'image',
  'community',
  'favorites',
  'recents',
  'agent',
  'channels',
  SIDEBAR_SPACER_ID,
];

/** Items that must stay contiguous in the sidebar list (accordion block). */
export const SIDEBAR_ACCORDION_KEYS = new Set(['favorites', 'recents', 'agent', 'channels']);

/**
 * Section key of the former workspace "Private" accordion. It was merged into
 * the single "Agents" (`agent`) section; saved layouts may still carry it.
 */
export const LEGACY_PRIVATE_SECTION_KEY = 'private';
const AGENT_SECTION_KEY = 'agent';

/**
 * Map a saved section order onto the merged Agents section: `private` is
 * dropped, and when the order has no `agent` yet, `agent` takes the slot
 * `private` held. Returns the input reference when nothing changes.
 */
export const normalizeLegacyAgentItems = (items: string[]): string[] => {
  const privateIndex = items.indexOf(LEGACY_PRIVATE_SECTION_KEY);
  if (privateIndex === -1) return items;

  if (items.includes(AGENT_SECTION_KEY)) {
    return items.filter((key) => key !== LEGACY_PRIVATE_SECTION_KEY);
  }
  const next = [...items];
  next[privateIndex] = AGENT_SECTION_KEY;
  return next.filter((key) => key !== LEGACY_PRIVATE_SECTION_KEY);
};

/**
 * Hidden sections: `private` no longer exists and the Agents section is always
 * shown, so the key is simply dropped.
 */
export const normalizeLegacyHiddenSections = (hidden: string[]): string[] =>
  hidden.includes(LEGACY_PRIVATE_SECTION_KEY)
    ? hidden.filter((key) => key !== LEGACY_PRIVATE_SECTION_KEY)
    : hidden;

/**
 * Expanded sections: the merged Agents section stays expanded when either of
 * the two former sections was.
 */
export const normalizeLegacyExpandedKeys = (keys: string[]): string[] => {
  if (!keys.includes(LEGACY_PRIVATE_SECTION_KEY)) return keys;

  const withoutPrivate = keys.filter((key) => key !== LEGACY_PRIVATE_SECTION_KEY);
  return withoutPrivate.includes(AGENT_SECTION_KEY)
    ? withoutPrivate
    : [...withoutPrivate, AGENT_SECTION_KEY];
};

/** Links that used to sit below the spacer by default. */
const FORMER_BOTTOM_LINKS = new Set(['image', 'community']);
/** Memory left the sidebar for Settings; only layouts saved before that still list it. */
const RETIRED_MEMORY_KEY = 'memory';
/** Everything earlier defaults kept below the spacer, besides Memory. `pages` is retired. */
const FORMER_DEFAULT_BOTTOM_KEYS = new Set(['community', 'image', 'pages', 'resource']);

const arraysEqual = (a: string[], b: string[]): boolean => {
  if (a === b) return true;
  if (a.length !== b.length) return false;
  for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
  return true;
};

// Invariant: spacer always sits immediately after the recents+agent block. Any
// stored position is ignored — the spacer is re-anchored on every read so legacy
// states (e.g. from the move-up/down dropdown that used to leave the spacer
// floating above the accordion) self-heal.
const normalizeSpacerPosition = (order: string[]): string[] => {
  const withoutSpacer = order.filter((k) => k !== SIDEBAR_SPACER_ID);

  let insertAt = -1;
  for (let i = withoutSpacer.length - 1; i >= 0; i--) {
    if (SIDEBAR_ACCORDION_KEYS.has(withoutSpacer[i])) {
      insertAt = i + 1;
      break;
    }
  }
  if (insertAt === -1) {
    const bottomIdx = withoutSpacer.findIndex((k) => FORMER_BOTTOM_LINKS.has(k));
    insertAt = bottomIdx === -1 ? withoutSpacer.length : bottomIdx;
  }

  return [...withoutSpacer.slice(0, insertAt), SIDEBAR_SPACER_ID, ...withoutSpacer.slice(insertAt)];
};

// Generation, Plugins and Docs moved above the accordion. A layout saved before
// that still lists `memory`, which no saved layout contains afterwards, so the
// move runs once per layout and never undoes a later choice to keep them below.
// A bottom group holding anything else was arranged by hand and stays. The links
// are only dropped here: the backfill puts them back in their default order.
const dropFormerDefaultBottom = (order: string[]): string[] => {
  if (!order.includes(RETIRED_MEMORY_KEY)) return order;

  const without = order.filter((k) => k !== RETIRED_MEMORY_KEY);
  const spacerIndex = without.indexOf(SIDEBAR_SPACER_ID);
  const bottom = without.slice(spacerIndex + 1);
  return bottom.length > 0 && bottom.every((k) => FORMER_DEFAULT_BOTTOM_KEYS.has(k))
    ? without.slice(0, spacerIndex + 1)
    : without;
};

// Projects used to be an accordion listing every project; it is now a single
// link to the project list. Saved orders still hold `project` inside the
// accordion block, where a link would split the block in two, so move it up to
// sit after Goals (or Tasks) like the other top links, or just above the block
// when neither is up there. A spot the user picked outside the block is kept.
const liftProjectOutOfAccordion = (order: string[]): string[] => {
  const projectIndex = order.indexOf('project');
  if (projectIndex === -1) return order;

  const firstAccordionIndex = order.findIndex((k) => SIDEBAR_ACCORDION_KEYS.has(k));
  if (firstAccordionIndex === -1 || projectIndex < firstAccordionIndex) return order;
  // The block runs up to the spacer, or to its last section in orders saved
  // without one.
  const spacerIndex = order.indexOf(SIDEBAR_SPACER_ID);
  const blockEnd =
    spacerIndex === -1
      ? order.findLastIndex((k) => SIDEBAR_ACCORDION_KEYS.has(k)) + 1
      : spacerIndex;
  if (projectIndex > blockEnd) return order;

  const without = order.filter((k) => k !== 'project');
  const blockStart = without.findIndex((k) => SIDEBAR_ACCORDION_KEYS.has(k));
  // Goals, else Tasks, may have been dragged below the spacer; then stay above the block.
  const anchor = ['goals', 'tasks']
    .map((k) => without.indexOf(k))
    .find((i) => i !== -1 && i < blockStart);
  const insertAt = anchor === undefined ? blockStart : anchor + 1;
  return [...without.slice(0, insertAt), 'project', ...without.slice(insertAt)];
};

// Backfill missing default keys just before the accordion, keeping the accordion
// flush with the spacer.
// Channels used to render right below Agents outside the saved order; a saved
// order without them keeps them in that spot instead of the top of the block.
const CHANNELS_SECTION_KEY = 'channels';
const withChannelsAfterAgent = (order: string[]): string[] => {
  if (order.includes(CHANNELS_SECTION_KEY)) return order;
  const agentIndex = order.indexOf(AGENT_SECTION_KEY);
  if (agentIndex === -1) return order;
  return [...order.slice(0, agentIndex + 1), CHANNELS_SECTION_KEY, ...order.slice(agentIndex + 1)];
};

const withAllKnownKeys = (order: string[]): string[] => {
  const nextOrder = withChannelsAfterAgent(liftProjectOutOfAccordion(order));
  const withSpacer = dropFormerDefaultBottom(normalizeSpacerPosition(nextOrder));
  const present = new Set(withSpacer);
  const missing = DEFAULT_SIDEBAR_ITEMS.filter((k) => k !== SIDEBAR_SPACER_ID && !present.has(k));

  if (missing.length === 0) return withSpacer;

  const spacerIdx = withSpacer.indexOf(SIDEBAR_SPACER_ID);
  let accordionStartIdx = spacerIdx;
  for (let i = 0; i < spacerIdx; i++) {
    if (SIDEBAR_ACCORDION_KEYS.has(withSpacer[i])) {
      accordionStartIdx = i;
      break;
    }
  }

  return [
    ...withSpacer.slice(0, accordionStartIdx),
    ...missing,
    ...withSpacer.slice(accordionStartIdx),
  ];
};

const accordionIndices = (items: string[]): number[] => {
  const out: number[] = [];
  for (let i = 0; i < items.length; i++) {
    if (SIDEBAR_ACCORDION_KEYS.has(items[i])) out.push(i);
  }
  return out;
};

const reorderInner = (items: string[], from: number, to: number): string[] => {
  const key = items[from];
  const accIdx = accordionIndices(items);

  // Moving an accordion item across the block's outer boundary → move whole block together.
  if (SIDEBAR_ACCORDION_KEYS.has(key) && accIdx.length >= 2) {
    const first = accIdx[0];
    const last = accIdx.at(-1)!;
    const crossesBoundary = (from === first && to < first) || (from === last && to > last);
    if (crossesBoundary) {
      const block = items.slice(first, last + 1);
      const without = [...items.slice(0, first), ...items.slice(last + 1)];
      // After removing the block, adjust target index for upward/downward movement
      const targetIdx = to < first ? to : to - (last - first + 1) + 1;
      const clamped = Math.max(0, Math.min(without.length, targetIdx));
      return [...without.slice(0, clamped), ...block, ...without.slice(clamped)];
    }
  }

  // Standard reorder
  const moved = [...items];
  const [removed] = moved.splice(from, 1);
  moved.splice(to, 0, removed);

  // Non-accordion item that landed between accordion items → snap to the side matching drag direction.
  if (!SIDEBAR_ACCORDION_KEYS.has(key)) {
    const nextAcc = accordionIndices(moved);
    if (nextAcc.length >= 2) {
      const first = nextAcc[0];
      const last = nextAcc.at(-1)!;
      const contiguous = last - first === nextAcc.length - 1;
      if (!contiguous) {
        const pos = moved.indexOf(key);
        if (pos > first && pos < last) {
          const cleaned = [...moved];
          cleaned.splice(pos, 1);
          const cAcc = accordionIndices(cleaned);
          const insertAt = from < to ? cAcc.at(-1)! + 1 : cAcc[0];
          cleaned.splice(insertAt, 0, key);
          return cleaned;
        }
      }
    }
  }

  return moved;
};

/**
 * Reorder sidebar items while keeping the accordion block (recents + agent) contiguous
 * and the spacer immediately after the accordion block. Returns the original `items`
 * reference when the move resolves to a no-op (e.g. dragging the accordion past the
 * spacer, which the invariant snaps right back), so callers can short-circuit on
 * reference equality.
 */
export const reorderSidebarItems = (items: string[], from: number, to: number): string[] => {
  if (from === to || from < 0 || to < 0 || from >= items.length || to >= items.length) {
    return items;
  }
  const normalized = normalizeSpacerPosition(reorderInner(items, from, to));
  return arraysEqual(normalized, items) ? items : normalized;
};

const sidebarItems =
  (workspaceId: string | null) =>
  (s: GlobalState): string[] => {
    const items = readOverridableField(s.status, 'sidebarItems', workspaceId);
    if (items && items.length > 0) return withAllKnownKeys(normalizeLegacyAgentItems(items));

    // Migrate from the legacy `sidebarSectionOrder` (canary) which only stored the
    // accordion order (e.g. ['agent', 'recents']). Apply that order to the accordion
    // slot inside the default list so users keep their custom accordion arrangement.
    const legacy =
      s.status.sidebarSectionOrder && normalizeLegacyAgentItems(s.status.sidebarSectionOrder);
    if (legacy && legacy.length > 0) {
      const legacyAcc = legacy.filter((k) => SIDEBAR_ACCORDION_KEYS.has(k));
      if (legacyAcc.length > 0) {
        const seen = new Set<string>();
        const merged: string[] = [];
        for (const k of DEFAULT_SIDEBAR_ITEMS) {
          if (SIDEBAR_ACCORDION_KEYS.has(k)) {
            for (const lk of legacyAcc) {
              if (!seen.has(lk)) {
                merged.push(lk);
                seen.add(lk);
              }
            }
          } else if (!seen.has(k)) {
            merged.push(k);
            seen.add(k);
          }
        }
        return withAllKnownKeys(merged);
      }
    }

    return DEFAULT_SIDEBAR_ITEMS;
  };
const showSystemRole = (s: GlobalState) => s.status.showSystemRole;
const mobileShowTopic = (s: GlobalState) => s.status.mobileShowTopic;
const mobileShowPortal = (s: GlobalState) => s.status.mobileShowPortal;
const showAgentBuilderPanel = (s: GlobalState) => s.status.showAgentBuilderPanel;
const showHomeRail = (s: GlobalState) => s.status.showHomeRail ?? false;
const showHomePortrait = (s: GlobalState) => s.status.showHomePortrait ?? true;
const hiddenHomeWidgets = (s: GlobalState): string[] => s.status.hiddenHomeWidgets ?? [];
const homeGoalsCollapsed = (s: GlobalState): boolean => s.status.homeGoalsCollapsed ?? false;
const teamBoardAttentionCollapsed = (s: GlobalState): boolean =>
  s.status.teamBoardAttentionCollapsed ?? false;
const homeRecentsCount = (s: GlobalState): number => s.status.homeRecentsCount ?? 8;
const homeTaskCount = (s: GlobalState): number => s.status.homeTaskCount ?? 8;
const showRightPanel = (s: GlobalState) => s.status.showRightPanel;
const showWorkingOverview = (s: GlobalState) =>
  s.status.showWorkingOverview ?? !s.status.showRightPanel;
const showLeftPanel = (s: GlobalState) => s.status.showLeftPanel;
const showPageAgentPanel = (s: GlobalState) => s.status.showPageAgentPanel;
const showTaskAgentPanel = (s: GlobalState) => s.status.showTaskAgentPanel;
const showTerminalPanel = (s: GlobalState) => s.status.showTerminalPanel;
const terminalPanelHeight = (s: GlobalState) => s.status.terminalPanelHeight || 320;
const showFilePanel = (s: GlobalState) => s.status.showFilePanel;
const showVerifyReportPanel = (s: GlobalState) => s.status.showVerifyReportPanel ?? true;
const showImagePanel = (s: GlobalState) => s.status.showImagePanel;
const showImageTopicPanel = (s: GlobalState) => s.status.showImageTopicPanel;
const hidePWAInstaller = (s: GlobalState) => s.status.hidePWAInstaller;
const isShowCredit = (s: GlobalState) => s.status.isShowCredit;
const language = (s: GlobalState) => s.status.language || 'auto';
const modelDetailPanelExpandedKeys = (s: GlobalState): ModelDetailPanelExpandedKey[] => {
  const collapsedKeys = s.status.modelDetailPanelCollapsedKeys ?? [];

  return MODEL_DETAIL_PANEL_EXPANDABLE_KEYS.filter((key) => !collapsedKeys.includes(key));
};
// Reads only the user-written key; the legacy `modelSwitchPanelGroupMode`
// was seeded into persisted status and must not influence the default.
const modelSwitchPanelGroupMode = (s: GlobalState) => s.status.modelSwitchPanelGroupBy || 'byModel';
const modelSwitchPanelWidth = (s: GlobalState) => s.status.modelSwitchPanelWidth || 460;
const pageAgentPanelWidth = (s: GlobalState) => s.status.pageAgentPanelWidth || 360;
const workingSidebarWidth = (s: GlobalState) => s.status.workingSidebarWidth || 360;

const leftPanelWidth = (s: GlobalState): number => {
  return normalizeNavPanelWidth(s.status.leftPanelWidth);
};
const portalWidth = (s: GlobalState) => s.status.portalWidth || 400;
const portalWidths = (s: GlobalState) => s.status.portalWidths;
const filePanelWidth = (s: GlobalState) => s.status.filePanelWidth;
const groupAgentBuilderPanelWidth = (s: GlobalState) => s.status.groupAgentBuilderPanelWidth || 360;
const imagePanelWidth = (s: GlobalState) => s.status.imagePanelWidth;
const agentListViewMode = (s: GlobalState) => s.status.agentListViewMode || 'card';
const DEFAULT_AGENT_DOCUMENT_SORT: AgentDocumentSort = {
  by: 'name',
  foldersFirst: true,
  order: 'asc',
};
// The server lists Channels newest first; keep that as the default view.
const DEFAULT_CHANNEL_LIST_SORT: ChannelListSort = { by: 'createdAt', order: 'desc' };
const channelListSort = (s: GlobalState): ChannelListSort =>
  s.status.channelListSort ?? DEFAULT_CHANNEL_LIST_SORT;
const projectListSortBy = (s: GlobalState): ProjectListSortBy =>
  s.status.projectListSortBy ?? 'manual';
const projectListViewMode = (s: GlobalState): ProjectListViewMode =>
  s.status.projectListViewMode ?? 'folder';
const agentDocumentSort = (s: GlobalState): AgentDocumentSort =>
  s.status.agentDocumentSort ?? DEFAULT_AGENT_DOCUMENT_SORT;
const agentListViewOptions = (s: GlobalState) => s.status.agentListViewOptions;
const agentListExpandedGroupKeys = (s: GlobalState) => s.status.agentListExpandedGroupKeys ?? [];
const agentListRecommendedSectionCollapsed = (s: GlobalState) =>
  s.status.agentListRecommendedSectionCollapsed ?? false;
const agentListSidebarSectionCollapsed = (s: GlobalState) =>
  !s.status.agentListSidebarSectionExpanded;
const imageTopicViewMode = (s: GlobalState) => s.status.imageTopicViewMode || 'grid';
const imageTopicPanelWidth = (s: GlobalState) => s.status.imageTopicPanelWidth;
const musicTopicViewMode = (s: GlobalState) => s.status.musicTopicViewMode || 'list';
const verifyReportPanelWidth = (s: GlobalState) => s.status.verifyReportPanelWidth || 300;
const videoPanelWidth = (s: GlobalState) => s.status.videoPanelWidth;
const videoTopicViewMode = (s: GlobalState) => s.status.videoTopicViewMode || 'grid';
const videoTopicPanelWidth = (s: GlobalState) => s.status.videoTopicPanelWidth;
const showVideoPanel = (s: GlobalState) => s.status.showVideoPanel;
const showVideoTopicPanel = (s: GlobalState) => s.status.showVideoTopicPanel;
const wideScreen = (s: GlobalState) => !s.status.noWideScreen;
const chatInputHeight = (s: GlobalState) => s.status.chatInputHeight || 64;
const expandInputActionbar = (s: GlobalState) => s.status.expandInputActionbar;
const isStatusInit = (s: GlobalState) => !!s.isStatusInit;

const getAgentSystemRoleExpanded =
  (agentId: string) =>
  (s: GlobalState): boolean => {
    const map = s.status.systemRoleExpandedMap || {};
    return map[agentId] === true; // System role is collapsed by default
  };

const disabledModelProvidersSortType = (s: GlobalState) =>
  s.status.disabledModelProvidersSortType || 'default';
const disabledModelsSortType = (s: GlobalState) => s.status.disabledModelsSortType || 'default';

const isNotificationRead =
  (slug: string) =>
  (s: GlobalState): boolean => {
    const slugs = s.status.readNotificationSlugs || [];
    return slugs.includes(slug);
  };

const isBannerDismissed =
  (bannerId: string) =>
  (s: GlobalState): boolean => {
    const ids = s.status.dismissedBannerIds || [];
    return ids.includes(bannerId);
  };
const tokenDisplayFormatShort = (s: GlobalState) =>
  s.status.tokenDisplayFormatShort !== undefined ? s.status.tokenDisplayFormatShort : true;

/** The home AgentSelect choice made in `scope` (a cache scope), if any. */
const homeSelectedAgentId =
  (scope: string) =>
  (s: GlobalState): string | undefined =>
    s.status.homeSelectedAgentIdByScope?.[scope];

export const systemStatusSelectors = {
  agentBuilderPanelWidth,
  agentDocumentSort,
  channelListSort,
  projectListSortBy,
  projectListViewMode,
  agentListExpandedGroupKeys,
  agentListRecommendedSectionCollapsed,
  agentListSidebarSectionCollapsed,
  agentListViewMode,
  agentListViewOptions,
  agentPageSize,
  chatInputHeight,
  disabledModelProvidersSortType,
  disabledModelsSortType,
  expandInputActionbar,
  docsPageSectionView,
  filePanelWidth,
  getAgentSystemRoleExpanded,
  groupAgentBuilderPanelWidth,
  hiddenHomeWidgets,
  hiddenSidebarSections,
  hidePWAInstaller,
  homeGoalsCollapsed,
  homeRecentsCount,
  homeSelectedAgentId,
  homeTaskCount,
  imagePanelWidth,
  imageTopicViewMode,
  imageTopicPanelWidth,
  isBannerDismissed,
  isNotificationRead,
  isShowCredit,
  isStatusInit,
  language,
  leftPanelWidth,
  mobileShowPortal,
  mobileShowTopic,
  modelDetailPanelExpandedKeys,
  modelSwitchPanelGroupMode,
  modelSwitchPanelWidth,
  pageAgentPanelWidth,
  pagePageSize,
  portalWidth,
  portalWidths,
  privateAgentPageSize,
  recentPageSize,
  taskCreateInlineCollapsed,
  taskKanbanHiddenColumns,
  taskKanbanHiddenPanelCollapsed,
  taskListViewMode,
  taskListFilter,
  taskListFilters,
  taskListViewOptions,
  teamBoardAttentionCollapsed,
  sidebarExpandedKeys,
  agentSidebarSections,
  projectOnboardingDismissed,
  projectSidebarSections,
  sidebarItems,
  sessionGroupKeys,
  showAgentBuilderPanel,
  showFilePanel,
  showHomePortrait,
  showHomeRail,
  showImagePanel,
  showImageTopicPanel,
  showLeftPanel,
  showPageAgentPanel,
  showRightPanel,
  showSystemRole,
  showTaskAgentPanel,
  showWorkingOverview,
  showTerminalPanel,
  showVerifyReportPanel,
  showVideoPanel,
  showVideoTopicPanel,
  systemStatus,
  terminalPanelHeight,
  verifyReportPanelWidth,
  tokenDisplayFormatShort,
  collapsedTopicGroupKeys,
  projectTopicSubGroupMode,
  topicOnlyMine,
  topicPageSize,
  videoPanelWidth,
  musicTopicViewMode,
  videoTopicViewMode,
  videoTopicPanelWidth,
  wideScreen,
  workingSidebarWidth,
};