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.

9.2 KB
Raw Blame
import { AGENT_CHAT_URL } from '@lobechat/const';
import { produce } from 'immer';

import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { INBOX_SESSION_ID } from '@/const/session';
import type { GlobalStore } from '@/store/global';
import type { ModelDetailPanelExpandedKey, WorkingSidebarTab } from '@/store/global/initialState';
import { MODEL_DETAIL_PANEL_EXPANDABLE_KEYS } from '@/store/global/initialState';
import { readOverridableField, systemStatusSelectors } from '@/store/global/selectors/systemStatus';
import type { StoreSetter } from '@/store/types';
import { getStableNavigate } from '@/utils/stableNavigate';
import { setNamespace } from '@/utils/storeDebug';

const n = setNamespace('w');

type Setter = StoreSetter<GlobalStore>;
export const globalWorkspaceSlice = (set: Setter, get: () => GlobalStore, _api?: unknown) =>
  new GlobalWorkspacePaneActionImpl(set, get, _api);

export class GlobalWorkspacePaneActionImpl {
  readonly #get: () => GlobalStore;
  readonly #set: Setter;

  constructor(set: Setter, get: () => GlobalStore, _api?: unknown) {
    void _api;
    this.#get = get;
    this.#set = set;
  }

  switchBackToChat = (sessionId?: string): void => {
    const target = AGENT_CHAT_URL(sessionId || INBOX_SESSION_ID, this.#get().isMobile);
    getStableNavigate()?.(target);
  };

  toggleAgentSystemRoleExpand = (agentId: string, expanded?: boolean): void => {
    const { status } = this.#get();
    const systemRoleExpandedMap = status.systemRoleExpandedMap || {};
    const nextExpanded = typeof expanded === 'boolean' ? expanded : !systemRoleExpandedMap[agentId];

    this.#get().updateSystemStatus(
      {
        systemRoleExpandedMap: {
          ...systemRoleExpandedMap,
          [agentId]: nextExpanded,
        },
      },
      n('toggleAgentSystemRoleExpand', { agentId, expanded: nextExpanded }),
    );
  };

  toggleCommandMenu = (visible?: boolean): void => {
    const currentVisible = this.#get().status.showCommandMenu;
    this.#get().updateSystemStatus({
      showCommandMenu: typeof visible === 'boolean' ? visible : !currentVisible,
    });
  };

  toggleExpandInputActionbar = (newValue?: boolean): void => {
    const expandInputActionbar =
      typeof newValue === 'boolean' ? newValue : !this.#get().status.expandInputActionbar;

    this.#get().updateSystemStatus(
      { expandInputActionbar },
      n('toggleExpandInputActionbar', newValue),
    );
  };

  toggleExpandSessionGroup = (id: string, expand: boolean): void => {
    const { status } = this.#get();
    // Read the effective (overlay-aware) value so workspace-mode toggles compose
    // off the workspace list, not the personal one underneath it.
    const currentKeys =
      readOverridableField(status, 'expandSessionGroupKeys', getActiveWorkspaceId()) ?? [];
    const nextExpandSessionGroup = produce(currentKeys, (draft: string[]) => {
      if (expand) {
        if (draft.includes(id)) return;
        draft.push(id);
      } else {
        const index = draft.indexOf(id);
        if (index !== -1) draft.splice(index, 1);
      }
    });
    this.#get().updateSystemStatus({ expandSessionGroupKeys: nextExpandSessionGroup });
  };

  toggleLeftPanel = (newValue?: boolean): void => {
    const showLeftPanel =
      typeof newValue === 'boolean' ? newValue : !this.#get().status.showLeftPanel;
    this.#get().updateSystemStatus({ showLeftPanel }, n('toggleLeftPanel', newValue));
  };

  toggleAgentBuilderPanel = (newValue?: boolean): void => {
    const showAgentBuilderPanel =
      typeof newValue === 'boolean' ? newValue : !this.#get().status.showAgentBuilderPanel;

    this.#get().updateSystemStatus(
      { showAgentBuilderPanel },
      n('toggleAgentBuilderPanel', newValue),
    );
  };

  toggleHomeRail = (newValue?: boolean): void => {
    const currentValue = this.#get().status.showHomeRail ?? false;
    const showHomeRail = typeof newValue === 'boolean' ? newValue : !currentValue;

    this.#get().updateSystemStatus({ showHomeRail }, n('toggleHomeRail', newValue));
  };

  togglePageAgentPanel = (newValue?: boolean): void => {
    const showPageAgentPanel =
      typeof newValue === 'boolean' ? newValue : !this.#get().status.showPageAgentPanel;

    this.#get().updateSystemStatus({ showPageAgentPanel }, n('togglePageAgentPanel', newValue));
  };

  toggleTaskAgentPanel = (newValue?: boolean): void => {
    const showTaskAgentPanel =
      typeof newValue === 'boolean' ? newValue : !this.#get().status.showTaskAgentPanel;

    this.#get().updateSystemStatus({ showTaskAgentPanel }, n('toggleTaskAgentPanel', newValue));
  };

  toggleMobilePortal = (newValue?: boolean): void => {
    const mobileShowPortal =
      typeof newValue === 'boolean' ? newValue : !this.#get().status.mobileShowPortal;

    this.#get().updateSystemStatus({ mobileShowPortal }, n('toggleMobilePortal', newValue));
  };

  toggleMobileTopic = (newValue?: boolean): void => {
    const mobileShowTopic =
      typeof newValue === 'boolean' ? newValue : !this.#get().status.mobileShowTopic;

    this.#get().updateSystemStatus({ mobileShowTopic }, n('toggleMobileTopic', newValue));
  };

  toggleRightPanel = (newValue?: boolean): void => {
    const showRightPanel =
      typeof newValue === 'boolean' ? newValue : !this.#get().status.showRightPanel;

    this.#get().updateSystemStatus({ showRightPanel }, n('toggleRightPanel', newValue));
  };

  toggleWorkingOverview = (newValue?: boolean): void => {
    const currentValue = systemStatusSelectors.showWorkingOverview(this.#get());
    const showWorkingOverview = typeof newValue === 'boolean' ? newValue : !currentValue;

    this.#get().updateSystemStatus({ showWorkingOverview }, n('toggleWorkingOverview', newValue));
  };

  toggleTerminalPanel = (newValue?: boolean): void => {
    const showTerminalPanel =
      typeof newValue === 'boolean' ? newValue : !this.#get().status.showTerminalPanel;

    this.#get().updateSystemStatus({ showTerminalPanel }, n('toggleTerminalPanel', newValue));
  };

  toggleSystemRole = (newValue?: boolean): void => {
    const showSystemRole =
      typeof newValue === 'boolean' ? newValue : !this.#get().status.mobileShowTopic;

    this.#get().updateSystemStatus({ showSystemRole }, n('toggleMobileTopic', newValue));
  };

  setWorkingSidebarTab = (tab: WorkingSidebarTab): void => {
    const previousNonce = this.#get().status.workingSidebarTabRequest?.nonce ?? 0;
    this.#get().updateSystemStatus(
      {
        workingSidebarTab: tab,
        workingSidebarTabRequest: { nonce: previousNonce + 1, tab },
      },
      n('setWorkingSidebarTab', tab),
    );
  };

  openWorkingSidebar = (tab?: WorkingSidebarTab): void => {
    const previousNonce = this.#get().status.workingSidebarTabRequest?.nonce ?? 0;
    this.#get().updateSystemStatus(
      {
        showRightPanel: true,
        showWorkingOverview: false,
        ...(tab
          ? {
              workingSidebarTab: tab,
              workingSidebarTabRequest: { nonce: previousNonce + 1, tab },
            }
          : {}),
      },
      n('openWorkingSidebar', tab),
    );
  };

  /** Published by the Working Sidebar's PR tab; `undefined` when it shows no PR. */
  setWorkingSidebarPullRequestUrl = (url?: string): void => {
    if (this.#get().workingSidebarPullRequestUrl === url) return;
    this.#set({ workingSidebarPullRequestUrl: url }, false, n('setWorkingSidebarPullRequestUrl'));
  };

  revealInFilesTab = (relativePath: string): void => {
    this.#get().openWorkingSidebar('files');
    this.#get().updateSystemStatus(
      { workingSidebarRevealRequest: { nonce: Date.now(), path: relativePath } },
      n('revealInFilesTab'),
    );
  };

  openInBrowserTab = (url: string): void => {
    this.#get().openWorkingSidebar('browser');
    this.#get().updateSystemStatus(
      { workingSidebarBrowserRequest: { nonce: Date.now(), url } },
      n('openInBrowserTab'),
    );
  };

  /**
   * Retire the request as soon as the browser pane has acted on it. Without
   * this, the request survives in persisted status and every later remount of
   * the pane — which now happens on each topic switch, since the session key is
   * per-topic — would navigate that topic's page to the stale URL.
   */
  clearBrowserTabRequest = (): void => {
    if (!this.#get().status.workingSidebarBrowserRequest) return;
    this.#get().updateSystemStatus(
      { workingSidebarBrowserRequest: null },
      n('clearBrowserTabRequest'),
    );
  };

  toggleWideScreen = (newValue?: boolean): void => {
    const noWideScreen =
      typeof newValue === 'boolean' ? !newValue : !this.#get().status.noWideScreen;

    this.#get().updateSystemStatus({ noWideScreen }, n('toggleWideScreen', newValue));
  };

  updateModelDetailPanelExpandedKeys = (keys: ModelDetailPanelExpandedKey[]): void => {
    // persisted as the complement (collapsed keys) so newly shipped sections
    // default to expanded — see MODEL_DETAIL_PANEL_EXPANDABLE_KEYS
    const collapsedKeys = MODEL_DETAIL_PANEL_EXPANDABLE_KEYS.filter((key) => !keys.includes(key));

    this.#get().updateSystemStatus(
      { modelDetailPanelCollapsedKeys: collapsedKeys },
      n('updateModelDetailPanelExpandedKeys', keys),
    );
  };
}

export type GlobalWorkspacePaneAction = Pick<
  GlobalWorkspacePaneActionImpl,
  keyof GlobalWorkspacePaneActionImpl
>;