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.

17.0 KB
Raw Blame
'use client';

import {
  Block,
  Button,
  confirmModal,
  createStaticStyles,
  Flexbox,
  Icon,
  Select,
  Tag,
  Text,
  toast,
} from '@lobehub/ui';
import { ArrowLeftIcon, CheckCircle2Icon, Trash2Icon, UserIcon } from 'lucide-react';
import type { ReactNode } from 'react';
import { memo, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';

import { usePermission } from '@/hooks/usePermission';
import { messengerActions, messengerSelectors, useMessengerStore } from '@/store/messenger';
import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
import { densityVars } from '@/styles/densityVars';

import AgentSelect from '../AgentSelect';
import { type MessengerPlatform, PlatformAvatar } from '../constants';
import { getMessengerErrorMessage, type MessengerTranslationKey } from '../i18n';
import {
  buildMessengerScopeOptions,
  messengerScopeSelectClassNames,
  PERSONAL_SCOPE,
  resolvePersonalScopeLabel,
} from '../scopeOptions';
import CommandsSection from './CommandsSection';

export const styles = createStaticStyles(({ css, cssVar }) => ({
  backButton: css`
    cursor: pointer;

    display: inline-flex;
    gap: 6px;
    align-items: center;

    color: ${cssVar.colorTextSecondary};

    &:hover {
      color: ${cssVar.colorText};
    }
  `,
  card: css`
    padding: ${densityVars.cardPadding};
    border: 1px solid ${cssVar.colorBorder};
    border-radius: ${cssVar.borderRadius};
  `,
  emptyRow: css`
    padding-block: 32px;
    padding-inline: ${densityVars.cardPadding};
    border: 1px dashed ${cssVar.colorBorder};
    border-radius: ${cssVar.borderRadius};

    color: ${cssVar.colorTextSecondary};
    text-align: center;
  `,
  rowIcon: css`
    display: flex;
    align-items: center;
    justify-content: center;

    width: 36px;
    height: 36px;
    border-radius: 8px;

    color: ${cssVar.colorTextSecondary};

    background: ${cssVar.colorFillTertiary};
  `,
  rowIdentity: css`
    min-width: 0;
  `,
}));

export interface ConnectionRowProps {
  action?: ReactNode;
  children?: ReactNode;
  icon: ReactNode;
  label: string;
  name: string;
  nameTooltip?: string;
  status: 'connected' | 'pending';
}

export const ConnectionRow = memo<ConnectionRowProps>(
  ({ action, children, icon, label, name, nameTooltip, status }) => {
    const { t } = useTranslation('messenger');

    return (
      <Block className={styles.card}>
        <Flexbox gap={12}>
          <Flexbox horizontal align="center" gap={12}>
            <div className={styles.rowIcon}>{icon}</div>
            <Flexbox className={styles.rowIdentity} flex={1} gap={2}>
              <Text style={{ fontSize: 12 }} type="secondary">
                {label}
              </Text>
              <Text strong ellipsis={{ tooltip: nameTooltip ?? true }}>
                {name}
              </Text>
            </Flexbox>
            {status === 'connected' ? (
              <Tag color="success" icon={<Icon icon={CheckCircle2Icon} size="small" />}>
                {t('messenger.detail.connections.connected')}
              </Tag>
            ) : (
              <Tag color="warning">{t('messenger.detail.connections.pending')}</Tag>
            )}
            {action}
          </Flexbox>
          {children && <Flexbox style={{ paddingInlineStart: 48 }}>{children}</Flexbox>}
        </Flexbox>
      </Block>
    );
  },
);
ConnectionRow.displayName = 'MessengerConnectionRow';

export { IntegrationDetailSkeleton } from '@/components/Skeleton/Settings/MessengerDetail';

interface DetailLayoutProps {
  children?: ReactNode;
  /** Standalone sections (own title + card) rendered between the connections
   *  section and the commands section. */
  extraSections?: ReactNode;
  hasConnections: boolean;
  headerAction: ReactNode;
  name: string;
  onBack?: () => void;
  platform: MessengerPlatform;
  sectionTitle?: ReactNode;
}

export const DetailLayout = memo<DetailLayoutProps>(
  ({
    children,
    extraSections,
    headerAction,
    hasConnections,
    name,
    onBack,
    platform,
    sectionTitle,
  }) => {
    const { t } = useTranslation('messenger');

    return (
      <Flexbox gap={20}>
        {onBack && (
          <Flexbox horizontal align="center" gap={8}>
            <span className={styles.backButton} onClick={onBack}>
              <Icon icon={ArrowLeftIcon} size="small" />
            </span>
            <Text strong style={{ fontSize: 20 }}>
              {name}
            </Text>
          </Flexbox>
        )}

        <Block className={styles.card}>
          <Flexbox horizontal align="center" gap={16}>
            <PlatformAvatar platform={platform} size={48} />
            <Flexbox flex={1} gap={2}>
              <Text strong style={{ fontSize: 15 }}>
                {name}
              </Text>
              <Text style={{ fontSize: 13 }} type="secondary">
                {t(`messenger.list.${platform}.description` as any)}
              </Text>
            </Flexbox>
            {headerAction}
          </Flexbox>
        </Block>

        {hasConnections && (
          <Flexbox gap={8}>
            <Text strong style={{ fontSize: 15 }}>
              {sectionTitle ?? t('messenger.detail.connections.title')}
            </Text>
            <Flexbox gap={12}>{children}</Flexbox>
          </Flexbox>
        )}

        {extraSections}

        <CommandsSection platform={platform} />
      </Flexbox>
    );
  },
);
DetailLayout.displayName = 'MessengerDetailLayout';

interface UserLinkLike {
  activeAgentId: string | null;
  platformUserId: string;
  platformUsername: string | null;
  /** Active scope of this link: a workspace id, or null for personal. */
  workspaceId: string | null;
}

export const formatUserHandle = (link: UserLinkLike): string =>
  link.platformUsername ? `@${link.platformUsername}` : `ID ${link.platformUserId}`;

interface UserAgentConnectionProps {
  extraLabel?: string;
  link: UserLinkLike;
  onSetActive: (agentId: string | null) => Promise<boolean>;
  onUnlink: () => void;
}

export const UserAgentConnection = memo<UserAgentConnectionProps>(
  ({ extraLabel, link, onSetActive, onUnlink }) => {
    const { t } = useTranslation('messenger');
    const { allowed: canEdit } = usePermission('edit_own_content');
    const enableWorkspaceScopes = useServerConfigStore(
      serverConfigSelectors.enableBusinessFeatures,
    );
    const handle = formatUserHandle(link);
    const hasReadableHandle = Boolean(link.platformUsername);
    const name = extraLabel
      ? hasReadableHandle
        ? `${handle} · ${extraLabel}`
        : extraLabel
      : handle;
    const nameTooltip = extraLabel && !hasReadableHandle ? handle : undefined;

    // First-level "scope" selector — personal plus every workspace the user
    // belongs to. The bot is a single shared bot; which LobeHub context a
    // conversation runs in is the active agent's scope, so picking a scope just
    // filters the agent list below. The active scope is persisted server-side
    // only when an agent is chosen (it derives the workspace from the agent).
    // `PERSONAL_SCOPE` is the sentinel for personal (null).
    messengerActions.useFetchBindingScopes(enableWorkspaceScopes);
    const bindingScopes = useMessengerStore(messengerSelectors.bindingScopes);
    const linkScope = enableWorkspaceScopes ? (link.workspaceId ?? PERSONAL_SCOPE) : PERSONAL_SCOPE;
    const [scope, setScope] = useState<string>(linkScope);
    // A link painted from the local copy may name an older binding scope. When
    // the server's link moves to another scope, the picker follows it, so the
    // agent below is read (and defaulted) in the scope the link is bound to.
    const [syncedLinkScope, setSyncedLinkScope] = useState(linkScope);
    if (syncedLinkScope !== linkScope) {
      setSyncedLinkScope(linkScope);
      setScope(linkScope);
    }
    // Defaulting to the inbox writes the binding: never from a restored link.
    const isLinksConfirmed = useMessengerStore(messengerSelectors.isLinksConfirmed);
    const userAvatar = useUserStore(userProfileSelectors.userAvatar);
    const userDisplayName = useUserStore(userProfileSelectors.displayUserName);
    const userFullName = useUserStore(userProfileSelectors.fullName);

    // Mirror the Agent Transfer scope picker: each row is an avatar + name.
    // Personal uses the user's avatar; workspaces use their own avatar.
    const scopeOptions = useMemo(() => {
      const personalLabel = resolvePersonalScopeLabel({
        fallbackLabel: userDisplayName || t('messenger.scopePersonal'),
        fullName: userFullName,
      });

      return buildMessengerScopeOptions({
        personalAvatar: userAvatar,
        personalLabel,
        personalTagLabel: t('messenger.scopePersonalTag', { defaultValue: 'personal' }),
        workspaces: enableWorkspaceScopes ? bindingScopes : undefined,
      });
    }, [bindingScopes, enableWorkspaceScopes, t, userAvatar, userDisplayName, userFullName]);

    const scopeWorkspaceId = scope === PERSONAL_SCOPE ? null : scope;
    const linkIsActiveScope = scopeWorkspaceId === (link.workspaceId ?? null);

    useEffect(() => {
      if (enableWorkspaceScopes || scope === PERSONAL_SCOPE) return;
      setScope(PERSONAL_SCOPE);
    }, [enableWorkspaceScopes, scope]);

    // Optimistic selection for the currently-selected scope. Persisting the
    // active agent waits for the server to adopt the pick into the link, so
    // without this the dropdown only reflects the new pick once both finish.
    // `pending` mirrors the user's choice immediately and is cleared once the
    // link data catches up. Scoped by workspace so it only applies while the
    // scope it was made in is selected.
    const [pending, setPending] = useState<{
      agentId: string | null;
      workspaceId: string | null;
    } | null>(null);
    const pendingForScope = pending && pending.workspaceId === scopeWorkspaceId ? pending : null;

    useEffect(() => {
      if (!pending) return;
      if (
        (link.workspaceId ?? null) === pending.workspaceId &&
        (link.activeAgentId ?? null) === pending.agentId
      ) {
        setPending(null);
      }
    }, [link.workspaceId, link.activeAgentId, pending]);

    const activeAgentId = pendingForScope
      ? pendingForScope.agentId
      : linkIsActiveScope
        ? (link.activeAgentId ?? null)
        : null;

    return (
      <ConnectionRow
        icon={<Icon icon={UserIcon} size="small" />}
        label={t('messenger.detail.connections.userLabel')}
        name={name}
        nameTooltip={nameTooltip}
        status="connected"
        action={
          <Button
            danger
            disabled={!canEdit}
            icon={<Icon icon={Trash2Icon} />}
            size="small"
            onClick={() => {
              if (!canEdit) return;
              onUnlink();
            }}
          >
            {t('messenger.detail.disconnect')}
          </Button>
        }
      >
        <Flexbox horizontal align="flex-end" gap={12}>
          <Flexbox flex={1} gap={6}>
            <Text style={{ fontSize: 12 }} type="secondary">
              {t('messenger.scope')}
            </Text>
            <Select
              classNames={messengerScopeSelectClassNames}
              disabled={!canEdit}
              options={scopeOptions}
              value={scope}
              onChange={(next) => setScope((next as string | null) ?? PERSONAL_SCOPE)}
            />
          </Flexbox>
          <Flexbox flex={1} gap={6}>
            <Text style={{ fontSize: 12 }} type="secondary">
              {t('messenger.activeAgent')}
            </Text>
            <AgentSelect
              // Default to the scope's inbox agent whenever the selected scope has
              // no active Agent. This also repairs historical agent-less links.
              defaultToInbox={canEdit && isLinksConfirmed && !pendingForScope && !activeAgentId}
              disabled={!canEdit}
              placeholder={t('messenger.activeAgentPlaceholder')}
              value={activeAgentId ?? undefined}
              workspaceId={scopeWorkspaceId}
              onChange={async (agentId) => {
                if (!canEdit) return;
                const next = (agentId ?? null) as string | null;
                // Reflect the pick immediately, then persist in the background.
                setPending({ agentId: next, workspaceId: scopeWorkspaceId });
                const ok = await onSetActive(next);
                // Roll back to the persisted value if the update failed.
                if (!ok) setPending(null);
              }}
            />
          </Flexbox>
        </Flexbox>
      </ConnectionRow>
    );
  },
);
UserAgentConnection.displayName = 'MessengerUserAgentConnection';

export const useMessengerData = (platform: MessengerPlatform) => {
  // A reload paints the last local copy of both lists, then revalidates.
  const linksSync = messengerActions.useFetchLinks();
  const installationsSync = messengerActions.useFetchInstallations();
  const links = useMessengerStore(messengerSelectors.linksByPlatform(platform)) ?? EMPTY;
  const installations =
    useMessengerStore(messengerSelectors.installationsByPlatform(platform)) ?? EMPTY;
  const isSettled = useMessengerStore(messengerSelectors.isPlatformDataSettled(platform));
  const tenantNameByTenantId = new Map(installations.map((i) => [i.tenantId, i.tenantName]));
  // A failed links / installations fetch with nothing to paint would otherwise
  // read as a permanent skeleton — surface the error so the detail renders a
  // failure + Retry instead (ux Read §1.1). A retry in flight is loading again.
  const error =
    linksSync.isValidating || installationsSync.isValidating
      ? undefined
      : (linksSync.error ?? installationsSync.error);

  return {
    error,
    installations,
    isInitialLoading: !isSettled,
    links,
    mutate: () => {
      void messengerActions.refreshConnections();
    },
    tenantNameByTenantId,
  };
};

const EMPTY: never[] = [];

interface UseLinkActionsArgs {
  name: string;
  platform: MessengerPlatform;
}

export const useLinkActions = ({ name, platform }: UseLinkActionsArgs) => {
  const { t } = useTranslation('messenger');

  const { allowed: canEdit } = usePermission('edit_own_content');

  // Returns whether the update succeeded so the caller can roll back its
  // optimistic selection on failure.
  const handleSetActive = async (tenantId: string, agentId: string | null): Promise<boolean> => {
    if (!canEdit) return false;

    try {
      await messengerActions.setActiveAgent({
        agentId,
        platform,
        tenantId: tenantId || undefined,
      });
      toast.success(t('messenger.setActiveSuccess'));
      return true;
    } catch (error) {
      toast.error(getMessengerErrorMessage(error, t, 'messenger.setActiveFailed'));
      return false;
    }
  };

  const handleUnlink = (tenantId: string) => {
    if (!canEdit) return;

    confirmModal({
      // WeChat links by scanning a QR code — it has no /start command, so the
      // generic "/start again" copy would point users at a dead end.
      content:
        platform === 'wechat'
          ? t('messenger.unlinkConfirmWechat')
          : platform === 'linq'
            ? t('messenger.unlinkConfirmLinq')
            : t('messenger.unlinkConfirm', { platform: name }),
      okButtonProps: { danger: true },
      onOk: async () => {
        try {
          await messengerActions.unlink({ platform, tenantId: tenantId || undefined });
          toast.success(t('messenger.unlinkSuccess'));
        } catch (error) {
          toast.error(getMessengerErrorMessage(error, t, 'messenger.unlinkFailed'));
        }
      },
      title: t('messenger.unlinkTitle'),
    });
  };

  return { handleSetActive, handleUnlink };
};

export interface DisconnectInstallationCopy {
  /** Confirm modal body. */
  confirm: string;
  /** i18n key used for the toast fallback when the server doesn't return a known messenger error. */
  failedKey: MessengerTranslationKey;
  /** Toast text on success. */
  success: string;
  /** Confirm modal title. */
  title: string;
}

/**
 * Disconnect-installation handler shared by Slack and Discord. The copy
 * diverges sharply between platforms — for Slack the operation freezes the
 * workspace's bot (token-gated dispatch); for Discord it only removes the
 * audit entry, since the bot stays in the guild until a server admin kicks
 * it. The platform passes already-localized strings + the `failedKey` so the
 * shared hook avoids embedding any platform-specific copy.
 */
export const useDisconnectInstallation = () => {
  const { t } = useTranslation('messenger');

  const { allowed: canEdit } = usePermission('edit_own_content');

  return (id: string, copy: DisconnectInstallationCopy) => {
    if (!canEdit) return;

    confirmModal({
      content: copy.confirm,
      okButtonProps: { danger: true },
      onOk: async () => {
        try {
          await messengerActions.uninstallInstallation(id);
          toast.success(copy.success);
        } catch (error) {
          toast.error(getMessengerErrorMessage(error, t, copy.failedKey));
        }
      },
      title: copy.title,
    });
  };
};