🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
'use client';
import { Block, Button, createStaticStyles, Flexbox, Icon, Select, Text } from '@lobehub/ui';
import { AlertTriangleIcon, CheckCircle2Icon, LinkIcon } from 'lucide-react';
import { memo, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { ProductLogo } from '@/components/Branding';
import InlineErrorText from '@/components/InlineErrorText';
import { marketplaceAppPath } from '@/features/Marketplace/paths';
import { messengerService } from '@/services/messenger';
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, PlatformBrandIcon } from '../../constants';
import { getMessengerErrorMessage } from '../../i18n';
import {
buildMessengerScopeOptions,
messengerScopeSelectClassNames,
PERSONAL_SCOPE,
resolvePersonalScopeLabel,
} from '../../scopeOptions';
import { resolveDefaultAgentId } from './defaultAgent';
export const styles = createStaticStyles(({ css, cssVar }) => ({
bubble: css`
display: flex;
align-items: center;
justify-content: center;
width: 64px;
height: 64px;
border-radius: 14px;
background: ${cssVar.colorBgContainer};
box-shadow: ${cssVar.boxShadowTertiary};
`,
card: css`
width: 100%;
max-width: 440px;
`,
chainBubble: css`
display: flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
border-radius: 999px;
color: ${cssVar.colorBgContainer};
background: ${cssVar.colorTextBase};
`,
iconRow: css`
display: flex;
gap: ${densityVars.contentGap};
align-items: center;
justify-content: center;
margin-block-end: 8px;
`,
infoRow: css`
display: flex;
gap: ${densityVars.sectionGap};
align-items: center;
justify-content: space-between;
padding-block: 10px;
& + & {
border-block-start: 1px solid ${cssVar.colorBorderSecondary};
}
`,
infoValue: css`
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
`,
successBubble: css`
color: ${cssVar.colorTextLightSolid};
background: ${cssVar.colorSuccess};
`,
warningBlock: css`
padding-block: ${densityVars.contentGap};
padding-inline: ${densityVars.cardPadding};
border-color: ${cssVar.colorWarningBorder};
background: ${cssVar.colorWarningBg};
`,
warningIcon: css`
flex-shrink: 0;
color: ${cssVar.colorWarning};
`,
}));
const ChainBubble = () => (
<div className={styles.chainBubble}>
<Icon icon={LinkIcon} size={16} />
</div>
);
const PlatformBubble = ({ platform }: { platform: MessengerPlatform }) => (
<div className={styles.bubble}>
<PlatformBrandIcon platform={platform} size={platform === 'telegram' ? 36 : 32} />
</div>
);
export const IconRow = memo<{ platform: MessengerPlatform }>(({ platform }) => (
<div className={styles.iconRow}>
<div className={styles.bubble}>
<ProductLogo size={36} type="3d" />
</div>
<ChainBubble />
<PlatformBubble platform={platform} />
</div>
));
IconRow.displayName = 'MessengerVerifyIconRow';
export const Heading = memo<{ subtitle?: string; title: string }>(({ subtitle, title }) => (
<Flexbox align="center" gap={12}>
<Text
align="center"
as="h1"
style={{ fontSize: 28, fontWeight: 700, lineHeight: 1.3, margin: 0 }}
>
{title}
</Text>
{subtitle && (
<Text align="center" style={{ fontSize: 16, lineHeight: 1.5 }} type="secondary">
{subtitle}
</Text>
)}
</Flexbox>
));
Heading.displayName = 'MessengerVerifyHeading';
export interface InfoRow {
label: string;
value: string;
}
export interface ConfirmCardProps {
blockingNotice?: {
ctaHref: string;
ctaLabel: string;
description: string;
title: string;
};
infoRows: InfoRow[];
onSuccess: () => void;
platform: MessengerPlatform;
randomId: string;
/** Current user's avatar, used to label the "personal" scope option. */
userAvatar?: string | null;
}
export const ConfirmCard = memo<ConfirmCardProps>(
({ blockingNotice, infoRows, onSuccess, platform, randomId, userAvatar }) => {
const { t } = useTranslation('messenger');
const enableWorkspaceScopes = useServerConfigStore(
serverConfigSelectors.enableBusinessFeatures,
);
// First-level scope selector — personal plus every workspace the user
// belongs to. Picking a scope just filters the agent list below; the
// backend derives the binding's workspace from the chosen agent on confirm.
messengerActions.useFetchBindingScopes(enableWorkspaceScopes);
const bindingScopes = useMessengerStore(messengerSelectors.bindingScopes);
const [scope, setScope] = useState<string>(PERSONAL_SCOPE);
const [selectedAgentId, setSelectedAgentId] = useState<string | undefined>(undefined);
const scopeWorkspaceId = scope === PERSONAL_SCOPE ? null : scope;
const userDisplayName = useUserStore(userProfileSelectors.displayUserName);
const userFullName = useUserStore(userProfileSelectors.fullName);
useEffect(() => {
if (enableWorkspaceScopes || scope === PERSONAL_SCOPE) return;
setScope(PERSONAL_SCOPE);
setSelectedAgentId(undefined);
}, [enableWorkspaceScopes, scope]);
// Scope-aware agent list, the same replica entry AgentSelect reads, so the
// fetch is shared (single request per scope) and follows the scope.
messengerActions.useFetchBindingAgents(scopeWorkspaceId);
const agents = useMessengerStore(messengerSelectors.bindingAgents(scopeWorkspaceId));
// "No agents" only from the server: a restored empty copy may be stale.
const isAgentsConfirmed = useMessengerStore(
messengerSelectors.isBindingAgentsConfirmed(scopeWorkspaceId),
);
const [confirming, setConfirming] = useState(false);
/** Link failure (already mapped to localized copy), shown above the confirm button so the user's agent pick stays in view. */
const [confirmError, setConfirmError] = useState('');
// Default-select the first agent (inbox is pinned to the top) once the
// server confirms a scope's list, and drop a pick that list no longer has.
// Resetting selectedAgentId on scope change re-triggers this so it
// re-defaults to the new scope's inbox.
const resolvedAgentId = resolveDefaultAgentId(agents, isAgentsConfirmed, selectedAgentId);
useEffect(() => {
if (resolvedAgentId !== selectedAgentId) setSelectedAgentId(resolvedAgentId);
}, [resolvedAgentId, selectedAgentId]);
// Mirror the Messenger connection card's scope picker: avatar + name per row.
// Personal uses the user's avatar; workspaces use their own.
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]);
// Personal-only deployments (OSS) return no workspaces — hide the scope
// selector entirely so the experience is unchanged there.
const hasWorkspaces = enableWorkspaceScopes && (bindingScopes?.length ?? 0) > 0;
const isBlocked = !!blockingNotice;
const handleConfirm = async () => {
if (!selectedAgentId || !isAgentsConfirmed) return;
setConfirmError('');
setConfirming(true);
try {
await messengerService.confirmLink({ initialAgentId: selectedAgentId, randomId });
onSuccess();
} catch (error) {
setConfirmError(getMessengerErrorMessage(error, t, 'verify.error.generic'));
} finally {
setConfirming(false);
}
};
return (
<Flexbox align="center" className={styles.card} gap={32}>
<IconRow platform={platform} />
<Heading title={t('verify.confirm.title')} />
<Block padding={4} style={{ width: '100%' }} variant={'outlined'}>
<Flexbox paddingInline={16}>
{infoRows.map((row) => (
<div className={styles.infoRow} key={row.label}>
<Text type="secondary">{row.label}</Text>
<Text strong className={styles.infoValue} title={row.value}>
{row.value}
</Text>
</div>
))}
</Flexbox>
</Block>
{blockingNotice && (
<Block className={styles.warningBlock} style={{ width: '100%' }} variant={'outlined'}>
<Flexbox horizontal gap={12}>
<Icon className={styles.warningIcon} icon={AlertTriangleIcon} size={20} />
<Flexbox gap={8} style={{ flex: 1 }}>
<Text strong>{blockingNotice.title}</Text>
<Text style={{ fontSize: 13 }} type="secondary">
{blockingNotice.description}
</Text>
<Button block href={blockingNotice.ctaHref} type="default">
{blockingNotice.ctaLabel}
</Button>
</Flexbox>
</Flexbox>
</Block>
)}
{!isBlocked && (
<Flexbox gap={16} style={{ width: '100%' }}>
{hasWorkspaces && (
<Flexbox gap={8}>
<Text strong>{t('messenger.scope')}</Text>
<Select
classNames={messengerScopeSelectClassNames}
options={scopeOptions}
value={scope}
onChange={(next) => {
setScope((next as string | null) ?? PERSONAL_SCOPE);
// Re-default to the new scope's inbox agent.
setSelectedAgentId(undefined);
setConfirmError('');
}}
/>
</Flexbox>
)}
<Flexbox gap={8}>
<Text strong>{t('verify.confirm.defaultAgent')}</Text>
{isAgentsConfirmed && agents?.length === 0 ? (
<Text type="warning">{t('verify.confirm.noAgents')}</Text>
) : (
<AgentSelect
placeholder={t('verify.confirm.defaultAgentPlaceholder')}
value={selectedAgentId}
workspaceId={scopeWorkspaceId}
onChange={(id) => {
setSelectedAgentId(id);
setConfirmError('');
}}
/>
)}
<Text style={{ fontSize: 12 }} type="secondary">
{t('verify.confirm.defaultAgentMarketplaceHint')}
</Text>
</Flexbox>
</Flexbox>
)}
{confirmError && (
<InlineErrorText style={{ width: '100%' }}>{confirmError}</InlineErrorText>
)}
<Button
block
disabled={isBlocked || !selectedAgentId || !isAgentsConfirmed}
loading={confirming}
size="large"
type="primary"
onClick={handleConfirm}
>
{t('verify.confirm.cta')}
</Button>
</Flexbox>
);
},
);
ConfirmCard.displayName = 'MessengerVerifyConfirmCard';
export interface SuccessCardProps {
/** Pre-built deep link back to the bot. When omitted, the CTA is hidden. */
openBotUrl?: string | null;
platform: MessengerPlatform;
platformLabel: string;
}
export const SuccessCard = memo<SuccessCardProps>(({ openBotUrl, platform, platformLabel }) => {
const { t } = useTranslation('messenger');
return (
<Flexbox align="center" className={styles.card} gap={24}>
<div className={styles.iconRow}>
<div className={`${styles.bubble} ${styles.successBubble}`}>
<Icon icon={CheckCircle2Icon} size={32} />
</div>
</div>
<Heading
subtitle={t('verify.success.description', { platform: platformLabel })}
title={t('verify.success.title')}
/>
<Flexbox gap={12} style={{ width: '100%' }}>
{openBotUrl && (
<Button block href={openBotUrl} size="large" target="_blank" type="primary">
{t('verify.success.openBot', { platform: platformLabel })}
</Button>
)}
{/* Mirror the Slack/Discord install callback's landing page so every
platform's flow ends back on its Marketplace app. */}
<Button
block
href={marketplaceAppPath(platform)}
size="large"
type={openBotUrl ? 'default' : 'primary'}
>
{t('verify.success.backToLobeHub')}
</Button>
</Flexbox>
</Flexbox>
);
});
SuccessCard.displayName = 'MessengerVerifySuccessCard';
export interface PeekedToken {
linkedToEmail?: string | null;
platform: MessengerPlatform;
platformUserId: string;
platformUsername?: string | null;
tenantId?: string | null;
tenantName?: string | null;
}
export interface ExistingLink {
platform: string;
platformUserId?: string;
platformUsername?: string | null;
tenantId?: string | null;
}
export interface PlatformMeta {
appId?: string;
botUsername?: string;
id: string;
name: string;
}