🤯 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
🐛 fix: add the user github oauth in community home page profiles (#13222)
LiJian6b4046eb17e9
diff --git a/locales/en-US/discover.json b/locales/en-US/discover.jsonindex fe244ef83cc..dc2193c463c 100644--- a/locales/en-US/discover.json+++ b/locales/en-US/discover.json@@ -607,6 +607,7 @@"time.today": "Today","time.yesterday": "Yesterday","user.agents": "Agents",+ "user.cancel": "Cancel","user.downloads": "Downloads","user.editProfile": "Edit Profile","user.favoriteAgents": "Saved Agents",@@ -616,6 +617,9 @@"user.following": "Following","user.forkedAgentGroups": "Forked Agent Groups","user.forkedAgents": "Forked Agents",+ "user.githubUrl": "GitHub Repository URL",+ "user.githubUrlInvalid": "Please enter a valid GitHub repository URL",+ "user.githubUrlRequired": "Please enter a GitHub repository URL","user.login": "Become a Creator","user.logout": "Logout","user.myProfile": "My Profile",@@ -624,9 +628,13 @@"user.noFavoritePlugins": "No saved Skills yet","user.noForkedAgentGroups": "No forked Agent Groups yet","user.noForkedAgents": "No forked Agents yet",+ "user.noPlugins": "This user hasn't published any Plugins yet",+ "user.noSkills": "This user hasn't published any Skills yet",+ "user.plugins": "Plugins","user.publishedAgents": "Created Agents","user.publishedGroups": "Created Groups","user.searchPlaceholder": "Search by name or description...",+ "user.skills": "Skills","user.statusFilter.all": "All","user.statusFilter.archived": "Archived","user.statusFilter.deprecated": "Deprecated",@@ -634,6 +642,13 @@"user.statusFilter.forked": "Forked","user.statusFilter.published": "Published","user.statusFilter.unpublished": "Under Review",+ "user.submit": "Submit",+ "user.submitRepo": "Submit Repo",+ "user.submitRepoDescription": "Submit your GitHub repository to import your Skills or MCPs to the community.",+ "user.submitRepoError": "Failed to submit repository. Please try again.",+ "user.submitRepoHint": "The repository will be reviewed before being published.",+ "user.submitRepoSuccess": "Repository submitted successfully! It will be reviewed shortly.",+ "user.submitRepoTitle": "Submit Your Repository","user.tabs.favorites": "Favorites","user.tabs.forkedAgents": "Forked","user.tabs.publishedAgents": "Created",diff --git a/locales/en-US/marketAuth.json b/locales/en-US/marketAuth.jsonindex 568b523919d..398fc18376b 100644--- a/locales/en-US/marketAuth.json+++ b/locales/en-US/marketAuth.json@@ -16,6 +16,15 @@"callback.titles.error": "Authorization Failed","callback.titles.loading": "LobeHub Market Authorization","callback.titles.success": "Authorization Successful",+ "claimResources.claim": "Claim Selected",+ "claimResources.description": "We found resources linked to your account that you can claim:",+ "claimResources.error": "Failed to claim resources. Please try again.",+ "claimResources.mcpSection": "MCP Servers",+ "claimResources.selectedCount": "{{count}} item(s) selected",+ "claimResources.skillSection": "Skills",+ "claimResources.skip": "Skip",+ "claimResources.success": "Successfully claimed {{count}} resource(s)",+ "claimResources.title": "Claim Your Resources","errors.authorizationFailed": "Authorization failed, please try again.","errors.browserOnly": "The authorization process can only be initiated in a browser.","errors.codeConsumed": "The authorization code has already been used. Please try again.",@@ -75,6 +84,10 @@"profileSetup.fields.website.placeholder": "Personal website URL","profileSetup.getStarted": "Get Started","profileSetup.save": "Save",+ "profileSetup.socialLinks.connectProvider": "Connect {{provider}}",+ "profileSetup.socialLinks.connected": "Connected",+ "profileSetup.socialLinks.connecting": "Connecting...",+ "profileSetup.socialLinks.disconnect": "Disconnect","profileSetup.socialLinks.title": "Social Links","profileSetup.success": "Profile updated successfully","profileSetup.titleEdit": "Edit Profile",diff --git a/locales/zh-CN/discover.json b/locales/zh-CN/discover.jsonindex d16090e8bfa..f777f063ab9 100644--- a/locales/zh-CN/discover.json+++ b/locales/zh-CN/discover.json@@ -607,6 +607,7 @@"time.today": "今天","time.yesterday": "昨天","user.agents": "助理",+ "user.cancel": "取消","user.downloads": "下载","user.editProfile": "编辑个人资料","user.favoriteAgents": "收藏的助手",@@ -616,6 +617,9 @@"user.following": "关注","user.forkedAgentGroups": "已派生的代理组","user.forkedAgents": "已派生的代理",+ "user.githubUrl": "GitHub 仓库地址",+ "user.githubUrlInvalid": "请输入有效的 GitHub 仓库地址",+ "user.githubUrlRequired": "请输入 GitHub 仓库地址","user.login": "成为创作者","user.logout": "退出登录","user.myProfile": "我的主页",@@ -624,9 +628,13 @@"user.noFavoritePlugins": "暂无收藏的插件","user.noForkedAgentGroups": "尚无已派生的代理组","user.noForkedAgents": "尚无已派生的代理",+ "user.noPlugins": "该用户暂未发布插件",+ "user.noSkills": "该用户暂未发布技能",+ "user.plugins": "插件","user.publishedAgents": "创作的助理","user.publishedGroups": "创作的群组","user.searchPlaceholder": "搜索名称或描述...",+ "user.skills": "技能","user.statusFilter.all": "全部","user.statusFilter.archived": "已归档","user.statusFilter.deprecated": "已废弃",@@ -634,6 +642,13 @@"user.statusFilter.forked": "已派生","user.statusFilter.published": "已发布","user.statusFilter.unpublished": "审核中",+ "user.submit": "提交",+ "user.submitRepo": "提交仓库",+ "user.submitRepoDescription": "提交你的 GitHub 仓库,将你的 Skills 或 MCP 导入到社区。",+ "user.submitRepoError": "提交仓库失败,请重试。",+ "user.submitRepoHint": "仓库将在审核后发布。",+ "user.submitRepoSuccess": "仓库提交成功!审核通过后将自动发布。",+ "user.submitRepoTitle": "提交你的仓库","user.tabs.favorites": "收藏","user.tabs.forkedAgents": "已派生","user.tabs.publishedAgents": "创作",diff --git a/locales/zh-CN/marketAuth.json b/locales/zh-CN/marketAuth.jsonindex 11856b60318..7b421d28b16 100644--- a/locales/zh-CN/marketAuth.json+++ b/locales/zh-CN/marketAuth.json@@ -16,6 +16,15 @@"callback.titles.error": "授权失败","callback.titles.loading": "LobeHub Market 授权","callback.titles.success": "授权成功",+ "claimResources.claim": "认领所选",+ "claimResources.description": "我们发现了与你的账户关联的资源,你可以认领它们:",+ "claimResources.error": "认领资源失败,请重试。",+ "claimResources.mcpSection": "MCP 服务器",+ "claimResources.selectedCount": "已选择 {{count}} 项",+ "claimResources.skillSection": "Skills",+ "claimResources.skip": "跳过",+ "claimResources.success": "成功认领 {{count}} 个资源",+ "claimResources.title": "认领你的资源","errors.authorizationFailed": "授权失败,请重试。","errors.browserOnly": "授权流程只能在浏览器中发起。","errors.codeConsumed": "授权码已被使用,请重新尝试。",@@ -75,6 +84,10 @@"profileSetup.fields.website.placeholder": "个人网站链接","profileSetup.getStarted": "开始使用","profileSetup.save": "保存",+ "profileSetup.socialLinks.connectProvider": "连接 {{provider}}",+ "profileSetup.socialLinks.connected": "已连接",+ "profileSetup.socialLinks.connecting": "连接中…",+ "profileSetup.socialLinks.disconnect": "断开连接","profileSetup.socialLinks.title": "社交链接","profileSetup.success": "个人资料已更新","profileSetup.titleEdit": "编辑个人资料",diff --git a/packages/types/src/discover/index.ts b/packages/types/src/discover/index.tsindex 6d67077b789..6291d00b97d 100644--- a/packages/types/src/discover/index.ts+++ b/packages/types/src/discover/index.ts@@ -1,5 +1,7 @@import type { DiscoverAssistantItem } from './assistants';import type { DiscoverGroupAgentItem } from './groupAgents';+import type { DiscoverPluginItem } from './plugins';+import type { DiscoverSkillItem } from './skills';export * from './assistants';export * from './fork';@@ -86,5 +88,13 @@ export interface DiscoverUserProfile {* Agents forked by the user*/forkedAgents?: DiscoverAssistantItem[];+ /**+ * Plugins owned by the user+ */+ plugins?: DiscoverPluginItem[];+ /**+ * Skills owned by the user+ */+ skills?: DiscoverSkillItem[];user: DiscoverUserInfo;}diff --git a/src/app/[variants]/(auth)/oauth/callback/social/page.tsx b/src/app/[variants]/(auth)/oauth/callback/social/page.tsxnew file mode 100644index 00000000000..4c425974ee8--- /dev/null+++ b/src/app/[variants]/(auth)/oauth/callback/social/page.tsx@@ -0,0 +1,107 @@+'use client';++import { FluentEmoji, Text } from '@lobehub/ui';+import { Result } from 'antd';+import { useSearchParams } from 'next/navigation';+import React, { memo, useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';++type CallbackStatus = 'error' | 'success';++const SocialOAuthCallbackPage = memo(() => {+ const { t } = useTranslation('oauth');+ const searchParams = useSearchParams();+ const [countdown, setCountdown] = useState(3);+ const [errorMessage, setErrorMessage] = useState<string | null>(null);+ const [status, setStatus] = useState<CallbackStatus>('success');++ useEffect(() => {+ const provider = searchParams.get('provider');+ const error = searchParams.get('error');+ const errorDescription = searchParams.get('error_description');++ if (error) {+ const message = errorDescription || error;++ setStatus('error');+ setErrorMessage(message);++ if (provider && window.opener) {+ window.opener.postMessage(+ {+ error: message,+ provider,+ type: 'SOCIAL_PROFILE_AUTH_ERROR',+ },+ window.location.origin,+ );+ }++ return;+ }++ if (provider && window.opener) {+ setStatus('success');+ setErrorMessage(null);++ // Notify parent window that callback has completed. Parent window will confirm the connection state.+ window.opener.postMessage(+ {+ provider,+ type: 'SOCIAL_PROFILE_AUTH_CALLBACK',+ },+ window.location.origin,+ );++ // Start countdown and close window after 3 seconds+ let timeLeft = 3;+ setCountdown(timeLeft);++ const countdownTimer = setInterval(() => {+ timeLeft -= 1;+ setCountdown(timeLeft);++ if (timeLeft <= 0) {+ clearInterval(countdownTimer);+ window.close();+ }+ }, 1000);++ return () => clearInterval(countdownTimer);+ }++ setStatus('error');+ setErrorMessage('Missing provider parameter');+ }, [searchParams]);++ const provider = searchParams.get('provider');++ return (+ <Result+ icon={<FluentEmoji emoji={status === 'success' ? '✅' : '🥵'} size={96} type={'anim'} />}+ status={status}+ subTitle={+ <Text fontSize={16} type="secondary">+ {status === 'success' && provider+ ? t('success.subTitleWithCountdown', {+ countdown,+ defaultValue: `You may close this page. Auto-closing in ${countdown}s...`,+ })+ : t('error.desc', {+ defaultValue: `OAuth authorization failed, reason: ${errorMessage}`,+ reason: errorMessage,+ })}+ </Text>+ }+ title={+ <Text fontSize={32} weight={'bold'}>+ {status === 'success' ? t('success.title') : t('error.title')}+ </Text>+ }+ />+ );+});++SocialOAuthCallbackPage.displayName = 'SocialOAuthCallbackPage';++export default SocialOAuthCallbackPage;diff --git a/src/layout/AuthProvider/MarketAuth/ClaimResourcesModal.test.tsx b/src/layout/AuthProvider/MarketAuth/ClaimResourcesModal.test.tsxnew file mode 100644index 00000000000..ac3ccc67067--- /dev/null+++ b/src/layout/AuthProvider/MarketAuth/ClaimResourcesModal.test.tsx@@ -0,0 +1,147 @@+/**+ * @vitest-environment happy-dom+ */+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import type { HTMLAttributes, ReactNode } from 'react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import ClaimResourcesModal from './ClaimResourcesModal';++const messageErrorMock = vi.hoisted(() => vi.fn());+const messageSuccessMock = vi.hoisted(() => vi.fn());++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, options?: Record<string, string | number>) =>+ String(options?.defaultValue || key),+ }),+}));++vi.mock('@lobehub/ui', () => ({+ Flexbox: ({ children, ...props }: HTMLAttributes<HTMLDivElement>) => (+ <div {...props}>{children}</div>+ ),+ Modal: ({+ cancelText,+ children,+ okText,+ onCancel,+ onOk,+ open,+ }: {+ cancelText?: string;+ children: ReactNode;+ okText?: string;+ onCancel?: () => void;+ onOk?: () => void;+ open?: boolean;+ }) =>+ open ? (+ <div>+ <button onClick={onOk}>{okText || 'ok'}</button>+ <button onClick={onCancel}>{cancelText || 'cancel'}</button>+ {children}+ </div>+ ) : null,+ Text: ({ children, ...props }: HTMLAttributes<HTMLSpanElement>) => (+ <span {...props}>{children}</span>+ ),+}));++vi.mock('antd', () => {+ const ListItem = ({ children, onClick }: { children: ReactNode; onClick?: () => void }) => (+ <div role="listitem" onClick={onClick}>+ {children}+ </div>+ );++ const List = ({+ dataSource,+ renderItem,+ }: {+ dataSource: any[];+ renderItem: (item: any) => ReactNode;+ }) => <div>{dataSource.map((item) => renderItem(item))}</div>;++ List.Item = ListItem;++ return {+ App: {+ useApp: () => ({+ message: {+ error: messageErrorMock,+ success: messageSuccessMock,+ },+ }),+ },+ Checkbox: ({ checked }: { checked?: boolean }) => (+ <input readOnly checked={checked} role="checkbox" type="checkbox" />+ ),+ List,+ };+});++vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: {+ market: {+ socialProfile: {+ claimResources: { mutate: vi.fn() },+ },+ },+ },+}));++describe('ClaimResourcesModal', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('should reset selected resources when a new resource set is shown', async () => {+ const { rerender } = render(+ <ClaimResourcesModal+ open={true}+ resources={{+ plugins: [{ id: 1, identifier: 'plugin-a', type: 'plugin' }],+ skills: [{ id: 2, identifier: 'skill-a', type: 'skill' }],+ }}+ onClose={vi.fn()}+ />,+ );++ await waitFor(() => {+ const checkboxes = screen.getAllByRole('checkbox') as HTMLInputElement[];++ expect(checkboxes[0].checked).toBe(true);+ expect(checkboxes[1].checked).toBe(true);+ });++ fireEvent.click(screen.getByText('plugin-a'));++ await waitFor(() => {+ const checkboxes = screen.getAllByRole('checkbox') as HTMLInputElement[];++ expect(checkboxes[0].checked).toBe(false);+ expect(checkboxes[1].checked).toBe(true);+ });++ rerender(+ <ClaimResourcesModal+ open={true}+ resources={{+ plugins: [{ id: 3, identifier: 'plugin-b', type: 'plugin' }],+ skills: [{ id: 4, identifier: 'skill-b', type: 'skill' }],+ }}+ onClose={vi.fn()}+ />,+ );++ await waitFor(() => {+ const checkboxes = screen.getAllByRole('checkbox') as HTMLInputElement[];++ expect(screen.queryByText('plugin-a')).toBeNull();+ expect(screen.getByText('plugin-b')).toBeTruthy();+ expect(checkboxes[0].checked).toBe(true);+ expect(checkboxes[1].checked).toBe(true);+ });+ });+});diff --git a/src/layout/AuthProvider/MarketAuth/ClaimResourcesModal.tsx b/src/layout/AuthProvider/MarketAuth/ClaimResourcesModal.tsxnew file mode 100644index 00000000000..d0e6823a9f8--- /dev/null+++ b/src/layout/AuthProvider/MarketAuth/ClaimResourcesModal.tsx@@ -0,0 +1,217 @@+'use client';++import { Flexbox, Modal, Text } from '@lobehub/ui';+import { App, Checkbox, List } from 'antd';+import { cssVar } from 'antd-style';+import { Package, Wrench } from 'lucide-react';+import { memo, useCallback, useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { lambdaClient } from '@/libs/trpc/client';++import { type ClaimableResource, type ClaimableResources } from './useSocialConnect';++interface ClaimResourcesModalProps {+ onClose: () => void;+ onSuccess?: (claimedCount: number) => void;+ open: boolean;+ resources: ClaimableResources;+}++export const ClaimResourcesModal = memo<ClaimResourcesModalProps>(+ ({ open, onClose, resources, onSuccess }) => {+ const { t } = useTranslation('marketAuth');+ const { message } = App.useApp();++ const [selectedPlugins, setSelectedPlugins] = useState<Set<string>>(new Set());+ const [selectedSkills, setSelectedSkills] = useState<Set<string>>(new Set());+ const [isClaiming, setIsClaiming] = useState(false);++ useEffect(() => {+ if (!open) {+ setSelectedPlugins(new Set());+ setSelectedSkills(new Set());+ return;+ }++ setSelectedPlugins(new Set(resources.plugins.map((resource) => String(resource.id))));+ setSelectedSkills(new Set(resources.skills.map((resource) => String(resource.id))));+ }, [open, resources]);++ const togglePlugin = useCallback((id: string) => {+ setSelectedPlugins((prev) => {+ const next = new Set(prev);+ if (next.has(id)) {+ next.delete(id);+ } else {+ next.add(id);+ }+ return next;+ });+ }, []);++ const toggleSkill = useCallback((id: string) => {+ setSelectedSkills((prev) => {+ const next = new Set(prev);+ if (next.has(id)) {+ next.delete(id);+ } else {+ next.add(id);+ }+ return next;+ });+ }, []);++ const handleClaim = useCallback(async () => {+ const pluginIds = [...selectedPlugins];+ const skillIds = [...selectedSkills];++ if (pluginIds.length === 0 && skillIds.length === 0) {+ onClose();+ return;+ }++ setIsClaiming(true);+ try {+ await lambdaClient.market.socialProfile.claimResources.mutate({+ pluginIds,+ skillIds,+ });++ const totalClaimed = pluginIds.length + skillIds.length;+ message.success(+ t('claimResources.success', {+ count: totalClaimed,+ defaultValue: `Successfully claimed ${totalClaimed} resource(s)`,+ }),+ );+ onSuccess?.(totalClaimed);+ onClose();+ } catch (error) {+ console.error('[ClaimResources] Failed to claim:', error);+ message.error(+ t('claimResources.error', {+ defaultValue: 'Failed to claim resources. Please try again.',+ }),+ );+ } finally {+ setIsClaiming(false);+ }+ }, [selectedPlugins, selectedSkills, message, t, onSuccess, onClose]);++ const totalSelected = selectedPlugins.size + selectedSkills.size;++ const renderItem = (+ item: ClaimableResource,+ selected: boolean,+ onToggle: () => void,+ icon: React.ReactNode,+ ) => {+ // Use name, or fallback to parsedUrl.fullName, or identifier+ const displayName = item.name || item.parsedUrl?.fullName || item.identifier;++ return (+ <List.Item+ style={{+ cursor: 'pointer',+ padding: '8px 12px',+ }}+ onClick={onToggle}+ >+ <Flexbox horizontal align="center" gap={12} style={{ width: '100%' }}>+ <Checkbox checked={selected} />+ {icon}+ <Flexbox flex={1} gap={2}>+ <Text style={{ fontSize: 14 }}>{displayName}</Text>+ {item.description && (+ <Text style={{ fontSize: 12 }} type="secondary">+ {item.description}+ </Text>+ )}+ </Flexbox>+ </Flexbox>+ </List.Item>+ );+ };++ return (+ <Modal+ centered+ cancelText={t('claimResources.skip', { defaultValue: 'Skip' })}+ confirmLoading={isClaiming}+ okText={t('claimResources.claim', { defaultValue: 'Claim Selected' })}+ open={open}+ title={false}+ width={480}+ onCancel={onClose}+ onOk={handleClaim}+ >+ <Text strong fontSize={20} style={{ display: 'block', marginBottom: 8, marginTop: 16 }}>+ {t('claimResources.title', { defaultValue: 'Claim Your Resources' })}+ </Text>+ <Text style={{ display: 'block', marginBottom: 16 }} type="secondary">+ {t('claimResources.description', {+ defaultValue: 'We found resources linked to your account that you can claim:',+ })}+ </Text>++ {resources.plugins.length > 0 && (+ <Flexbox gap={8} style={{ marginBottom: 16 }}>+ <Text style={{ fontSize: 13 }} type="secondary">+ {t('claimResources.pluginSection', { defaultValue: 'Plugins' })}+ </Text>+ <List+ bordered+ dataSource={resources.plugins}+ size="small"+ style={{ borderRadius: cssVar.borderRadiusLG }}+ renderItem={(item) =>+ renderItem(+ item,+ selectedPlugins.has(String(item.id)),+ () => togglePlugin(String(item.id)),+ <Package size={18} style={{ color: cssVar.colorTextSecondary }} />,+ )+ }+ />+ </Flexbox>+ )}++ {resources.skills.length > 0 && (+ <Flexbox gap={8}>+ <Text style={{ fontSize: 13 }} type="secondary">+ {t('claimResources.skillSection', { defaultValue: 'Skills' })}+ </Text>+ <List+ bordered+ dataSource={resources.skills}+ size="small"+ style={{ borderRadius: cssVar.borderRadiusLG }}+ renderItem={(item) =>+ renderItem(+ item,+ selectedSkills.has(String(item.id)),+ () => toggleSkill(String(item.id)),+ <Wrench size={18} style={{ color: cssVar.colorTextSecondary }} />,+ )+ }+ />+ </Flexbox>+ )}++ {totalSelected > 0 && (+ <Text style={{ display: 'block', fontSize: 12, marginTop: 12 }} type="secondary">+ {t('claimResources.selectedCount', {+ count: totalSelected,+ defaultValue: `${totalSelected} item(s) selected`,+ })}+ </Text>+ )}+ </Modal>+ );+ },+);++ClaimResourcesModal.displayName = 'ClaimResourcesModal';++export default ClaimResourcesModal;diff --git a/src/layout/AuthProvider/MarketAuth/MarketAuthProvider.tsx b/src/layout/AuthProvider/MarketAuth/MarketAuthProvider.tsxindex 358ce912810..b2d1bb88709 100644--- a/src/layout/AuthProvider/MarketAuth/MarketAuthProvider.tsx+++ b/src/layout/AuthProvider/MarketAuth/MarketAuthProvider.tsx@@ -13,6 +13,7 @@ import { serverConfigSelectors } from '@/store/serverConfig/selectors';import { useUserStore } from '@/store/user';import { settingsSelectors } from '@/store/user/slices/settings/selectors/settings';+import ClaimResourcesModal from './ClaimResourcesModal';import { MarketAuthError } from './errors';import { marketAuthEvents } from './events';import MarketAuthConfirmModal from './MarketAuthConfirmModal';@@ -26,6 +27,7 @@ import {type OIDCConfig,} from './types';import { useMarketUserProfile } from './useMarketUserProfile';+import { type ClaimableResources } from './useSocialConnect';const MarketAuthContext = createContext<MarketAuthContextType | null>(null);@@ -148,6 +150,11 @@ export const MarketAuthProvider = ({ children, isDesktop }: MarketAuthProviderPrconst [pendingProfileSuccessCallback, setPendingProfileSuccessCallback] = useState<((_profile: MarketUserProfile) => void) | null>(null);+ const [claimableResources, setClaimableResources] = useState<ClaimableResources | null>(null);+ const [showClaimModal, setShowClaimModal] = useState(false);+ const [pendingClaimSuccessCallback, setPendingClaimSuccessCallback] = useState<+ (() => void) | null+ >(null);// Subscribe to user store init state; when isUserStateInit is true, settings data is fully loadedconst isUserStateInit = useUserStore((s) => s.isUserStateInit);@@ -486,6 +493,74 @@ export const MarketAuthProvider = ({ children, isDesktop }: MarketAuthProviderPrsetPendingProfileSuccessCallback(null);}, []);+ /**+ * Show claim resources modal (called from ProfileSetupModal after save)+ */+ const handleShowClaimResources = useCallback((resources: ClaimableResources) => {+ setClaimableResources(resources);+ setShowClaimModal(true);+ }, []);++ /**+ * Close claim resources modal+ */+ const handleCloseClaimModal = useCallback(() => {+ setShowClaimModal(false);+ setClaimableResources(null);+ setPendingClaimSuccessCallback(null);+ }, []);++ /**+ * Handle claim success - refresh user profile data+ */+ const handleClaimSuccess = useCallback(() => {+ setShowClaimModal(false);+ setClaimableResources(null);++ // Call the pending success callback if provided (e.g., page-level mutate)+ if (pendingClaimSuccessCallback) {+ pendingClaimSuccessCallback();+ setPendingClaimSuccessCallback(null);+ }++ // Also refresh all user-profile related SWR cache as fallback+ globalMutate((key) => typeof key === 'string' && key.startsWith('user-profile'), undefined, {+ revalidate: true,+ });+ }, [pendingClaimSuccessCallback]);++ /**+ * Check for claimable resources and show modal if any found+ * Call this when user enters their profile page+ * @param onClaimSuccess - Optional callback to run after successful claim (e.g., to refresh page data)+ */+ const checkAndShowClaimableResources = useCallback(+ async (onClaimSuccess?: () => void): Promise<boolean> => {+ // Only check if user is authenticated+ if (status !== 'authenticated') {+ return false;+ }++ try {+ const result = await lambdaClient.market.socialProfile.scanClaimableResources.query();+ if (result.plugins.length > 0 || result.skills.length > 0) {+ // Store the callback for when claim succeeds+ if (onClaimSuccess) {+ setPendingClaimSuccessCallback(() => onClaimSuccess);+ }+ setClaimableResources(result);+ setShowClaimModal(true);+ return true;+ }+ return false;+ } catch (error) {+ console.error('[MarketAuth] Failed to check claimable resources:', error);+ return false;+ }+ },+ [status],+ );+/*** Profile update success callback*/@@ -637,6 +712,7 @@ export const MarketAuthProvider = ({ children, isDesktop }: MarketAuthProviderPr}, [handleUnauthorized]);const contextValue: MarketAuthContextType = {+ checkAndShowClaimableResources,getAccessToken,getCurrentUserInfo,getRefreshToken,@@ -701,8 +777,17 @@ export const MarketAuthProvider = ({ children, isDesktop }: MarketAuthProviderPropen={showProfileSetupModal}userProfile={userProfile}onClose={handleCloseProfileSetup}+ onShowClaimResources={handleShowClaimResources}onSuccess={handleProfileSuccess}/>+ {claimableResources && (+ <ClaimResourcesModal+ open={showClaimModal}+ resources={claimableResources}+ onClose={handleCloseClaimModal}+ onSuccess={handleClaimSuccess}+ />+ )}</MarketAuthContext>);};diff --git a/src/layout/AuthProvider/MarketAuth/ProfileSetupModal.tsx b/src/layout/AuthProvider/MarketAuth/ProfileSetupModal.tsxindex 6e259e77927..39cd0864270 100644--- a/src/layout/AuthProvider/MarketAuth/ProfileSetupModal.tsx+++ b/src/layout/AuthProvider/MarketAuth/ProfileSetupModal.tsx@@ -1,6 +1,5 @@'use client';-import { SiGithub, SiX } from '@icons-pack/react-simple-icons';import { Center, Flexbox, Icon, Input, Modal, Text, TextArea, Tooltip } from '@lobehub/ui';import { type UploadProps } from 'antd';import { App, Form, Modal as AntModal, Upload } from 'antd';@@ -19,7 +18,9 @@ import { serverConfigSelectors } from '@/store/serverConfig/selectors';import { useUserStore } from '@/store/user';import { userProfileSelectors } from '@/store/user/selectors';+import SocialConnectButton from './SocialConnectButton';import { type MarketUserProfile } from './types';+import useSocialConnect, { type ClaimableResources } from './useSocialConnect';const MAX_FILE_SIZE = 2 * 1024 * 1024; // 2MB limit@@ -34,6 +35,10 @@ interface ProfileSetupModalProps {*/isFirstTimeSetup?: boolean;onClose: () => void;+ /**+ * Callback to show claim resources modal (managed by parent)+ */+ onShowClaimResources?: (resources: ClaimableResources) => void;/*** Callback when profile is successfully updated*/@@ -48,8 +53,6 @@ interface ProfileSetupModalProps {interface FormValues {description?: string;displayName: string;- github?: string;- twitter?: string;userName: string;website?: string;}@@ -58,6 +61,7 @@ const ProfileSetupModal = memo<ProfileSetupModalProps>(({open,onClose,+ onShowClaimResources,onSuccess,accessToken,defaultDisplayName,@@ -86,9 +90,45 @@ const ProfileSetupModal = memo<ProfileSetupModalProps>(const [bannerUrl, setBannerUrl] = useState<string | null>(null);const [bannerUploading, setBannerUploading] = useState(false);+ // Social profiles loading state+ const [isLoadingSocialProfiles, setIsLoadingSocialProfiles] = useState(false);+// File uploadconst uploadWithProgress = useFileStore((s) => s.uploadWithProgress);+ // Social connect hooks+ const handleClaimableResourcesFound = useCallback(+ (resources: ClaimableResources) => {+ onShowClaimResources?.(resources);+ },+ [onShowClaimResources],+ );++ const githubConnect = useSocialConnect({+ onClaimableResourcesFound: handleClaimableResourcesFound,+ provider: 'github',+ });++ const twitterConnect = useSocialConnect({+ onClaimableResourcesFound: handleClaimableResourcesFound,+ provider: 'twitter',+ });++ // Fetch social profiles when modal opens+ useEffect(() => {+ if (open && !isFirstTimeSetup) {+ const fetchProfiles = async () => {+ setIsLoadingSocialProfiles(true);+ try {+ await Promise.all([githubConnect.fetchProfile(), twitterConnect.fetchProfile()]);+ } finally {+ setIsLoadingSocialProfiles(false);+ }+ };+ fetchProfiles();+ }+ }, [open, isFirstTimeSetup, githubConnect.fetchProfile, twitterConnect.fetchProfile]);+// Reset form when modal opensuseEffect(() => {if (open) {@@ -104,8 +144,6 @@ const ProfileSetupModal = memo<ProfileSetupModalProps>(form.setFieldsValue({description: userProfile?.description || '',displayName: existingDisplayName,- github: userProfile?.socialLinks?.github || '',- twitter: userProfile?.socialLinks?.twitter || '',userName: existingUserName || generatedUserName,website: userProfile?.socialLinks?.website || '',});@@ -196,10 +234,10 @@ const ProfileSetupModal = memo<ProfileSetupModalProps>(const values = await form.validateFields();setLoading(true);- // Build socialLinks object (only include non-empty values)+ // Build socialLinks from OAuth profiles and website inputconst socialLinks: { github?: string; twitter?: string; website?: string } = {};- if (values.github) socialLinks.github = values.github;- if (values.twitter) socialLinks.twitter = values.twitter;+ if (githubConnect.profile?.username) socialLinks.github = githubConnect.profile.username;+ if (twitterConnect.profile?.username) socialLinks.twitter = twitterConnect.profile.username;if (values.website) socialLinks.website = values.website;// Build meta object (socialLinks should be inside meta)@@ -233,6 +271,25 @@ const ProfileSetupModal = memo<ProfileSetupModalProps>(type: result.user?.type || null,userName: values.userName || null,};++ // Check for claimable resources after saving (if GitHub is connected)+ if (githubConnect.profile) {+ try {+ const claimResult =+ await lambdaClient.market.socialProfile.scanClaimableResources.query();+ if (claimResult.plugins.length > 0 || claimResult.skills.length > 0) {+ // Close profile modal first, then show claim modal via parent callback+ onSuccess?.(userProfile);+ onClose();+ // Trigger claim modal in parent (MarketAuthProvider)+ onShowClaimResources?.(claimResult);+ return;+ }+ } catch (err) {+ console.error('[ProfileSetupModal] Failed to scan claimable resources:', err);+ }+ }+onSuccess?.(userProfile);onClose();} catch (error) {@@ -258,8 +315,11 @@ const ProfileSetupModal = memo<ProfileSetupModalProps>(bannerUrl,enableMarketTrustedClient,form,+ githubConnect.profile,+ twitterConnect.profile,message,onClose,+ onShowClaimResources,onSuccess,t,]);@@ -509,28 +569,31 @@ const ProfileSetupModal = memo<ProfileSetupModalProps>({t('profileSetup.socialLinks.title')}</Text>- <Form.Item name="github">- <Input- placeholder={t('profileSetup.fields.github.placeholder')}- prefix={- <Icon- fill={cssVar.colorTextSecondary}- icon={SiGithub}- style={{ marginRight: 8 }}- />- }+ {/* GitHub OAuth Connect Button */}+ <Flexbox gap={12} style={{ marginBottom: 16 }}>+ <SocialConnectButton+ disabled={isLoadingSocialProfiles}+ isConnecting={githubConnect.isConnecting}+ isDisconnecting={githubConnect.isDisconnecting}+ profile={githubConnect.profile}+ provider="github"+ onConnect={githubConnect.connect}+ onDisconnect={githubConnect.disconnect}/>- </Form.Item>- <Form.Item name="twitter">- <Input- placeholder={t('profileSetup.fields.twitter.placeholder')}- prefix={- <Icon fill={cssVar.colorTextSecondary} icon={SiX} style={{ marginRight: 8 }} />- }+ {/* Twitter OAuth Connect Button */}+ <SocialConnectButton+ disabled={isLoadingSocialProfiles}+ isConnecting={twitterConnect.isConnecting}+ isDisconnecting={twitterConnect.isDisconnecting}+ profile={twitterConnect.profile}+ provider="twitter"+ onConnect={twitterConnect.connect}+ onDisconnect={twitterConnect.disconnect}/>- </Form.Item>+ </Flexbox>+ {/* Website - Manual Input */}<Form.Itemname="website"rules={[diff --git a/src/layout/AuthProvider/MarketAuth/SocialConnectButton.tsx b/src/layout/AuthProvider/MarketAuth/SocialConnectButton.tsxnew file mode 100644index 00000000000..c3fd95da9b2--- /dev/null+++ b/src/layout/AuthProvider/MarketAuth/SocialConnectButton.tsx@@ -0,0 +1,114 @@+'use client';++import { SiGithub, SiX } from '@icons-pack/react-simple-icons';+import { ActionIcon, Flexbox, Text, Tooltip } from '@lobehub/ui';+import { Button, Spin } from 'antd';+import { cssVar } from 'antd-style';+import { ArrowRight, Link2Off, Loader2 } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { type SocialProfile, type SocialProvider } from './useSocialConnect';++interface SocialConnectButtonProps {+ disabled?: boolean;+ isConnecting?: boolean;+ isDisconnecting?: boolean;+ onConnect: () => void;+ onDisconnect: () => void;+ profile: SocialProfile | null;+ provider: SocialProvider;+}++const providerIcons: Record<SocialProvider, React.ComponentType<{ size?: number }>> = {+ github: SiGithub,+ twitter: SiX,+};++const providerNames: Record<SocialProvider, string> = {+ github: 'GitHub',+ twitter: 'X (Twitter)',+};++export const SocialConnectButton = memo<SocialConnectButtonProps>(+ ({ provider, profile, isConnecting, isDisconnecting, disabled, onConnect, onDisconnect }) => {+ const { t } = useTranslation('marketAuth');+ const ProviderIcon = providerIcons[provider];+ const providerName = providerNames[provider];++ const isLoading = isConnecting || isDisconnecting;+ const isDisabled = isLoading || disabled;++ if (profile) {+ // Connected state+ return (+ <Flexbox+ horizontal+ align="center"+ gap={12}+ justify="space-between"+ style={{+ background: cssVar.colorFillQuaternary,+ borderRadius: cssVar.borderRadiusLG,+ padding: '8px 12px',+ }}+ >+ <Flexbox horizontal align="center" gap={8}>+ <ProviderIcon size={18} />+ <Flexbox gap={2}>+ <Text style={{ fontSize: 13 }}>@{profile.username}</Text>+ <Text style={{ fontSize: 11 }} type="secondary">+ {t('profileSetup.socialLinks.connected', {+ defaultValue: 'Connected',+ })}+ </Text>+ </Flexbox>+ </Flexbox>+ <Tooltip title={t('profileSetup.socialLinks.disconnect', { defaultValue: 'Disconnect' })}>+ <ActionIcon+ disabled={isDisabled}+ icon={isDisconnecting ? Loader2 : Link2Off}+ loading={isDisconnecting}+ size="small"+ onClick={onDisconnect}+ />+ </Tooltip>+ </Flexbox>+ );+ }++ // Not connected state+ return (+ <Button+ block+ disabled={isDisabled}+ icon={isConnecting ? <Spin size="small" /> : <ProviderIcon size={16} />}+ style={{+ alignItems: 'center',+ display: 'flex',+ gap: 8,+ height: 40,+ justifyContent: 'flex-start',+ paddingLeft: 12,+ }}+ onClick={onConnect}+ >+ <Flexbox horizontal align="center" flex={1} justify="space-between">+ <span>+ {isConnecting+ ? t('profileSetup.socialLinks.connecting', { defaultValue: 'Connecting...' })+ : t('profileSetup.socialLinks.connectProvider', {+ defaultValue: `Connect ${providerName}`,+ provider: providerName,+ })}+ </span>+ {!isConnecting && <ArrowRight size={14} style={{ opacity: 0.5 }} />}+ </Flexbox>+ </Button>+ );+ },+);++SocialConnectButton.displayName = 'SocialConnectButton';++export default SocialConnectButton;diff --git a/src/layout/AuthProvider/MarketAuth/types.ts b/src/layout/AuthProvider/MarketAuth/types.tsindex b6a40093e3f..36cec2ffca7 100644--- a/src/layout/AuthProvider/MarketAuth/types.ts+++ b/src/layout/AuthProvider/MarketAuth/types.ts@@ -56,6 +56,13 @@ export interface MarketAuthState {}export interface MarketAuthContextType extends MarketAuthState {+ /**+ * Check for claimable resources and show modal if any found+ * Call this when user enters their profile page+ * @param onClaimSuccess - Optional callback to run after successful claim (e.g., to refresh page data)+ * @returns true if claimable resources were found and modal was shown+ */+ checkAndShowClaimableResources: (onClaimSuccess?: () => void) => Promise<boolean>;getAccessToken: () => string | null;getCurrentUserInfo: () => MarketUserInfo | null;getRefreshToken: () => string | null;diff --git a/src/layout/AuthProvider/MarketAuth/useSocialConnect.test.ts b/src/layout/AuthProvider/MarketAuth/useSocialConnect.test.tsnew file mode 100644index 00000000000..4322ace5e81--- /dev/null+++ b/src/layout/AuthProvider/MarketAuth/useSocialConnect.test.ts@@ -0,0 +1,119 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { useSocialConnect } from './useSocialConnect';++const connectGetStatusQueryMock = vi.hoisted(() => vi.fn());+const connectGetAuthorizeUrlQueryMock = vi.hoisted(() => vi.fn());+const connectRevokeMutateMock = vi.hoisted(() => vi.fn());+const scanClaimableResourcesQueryMock = vi.hoisted(() => vi.fn());++vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: {+ market: {+ socialProfile: {+ scanClaimableResources: { query: scanClaimableResourcesQueryMock },+ },+ },+ },+ toolsClient: {+ market: {+ connectGetAuthorizeUrl: { query: connectGetAuthorizeUrlQueryMock },+ connectGetStatus: { query: connectGetStatusQueryMock },+ connectRevoke: { mutate: connectRevokeMutateMock },+ },+ },+}));++describe('useSocialConnect', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.useFakeTimers();+ scanClaimableResourcesQueryMock.mockResolvedValue({ plugins: [], skills: [] });+ });++ afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ });++ it('should keep polling after callback notification until the profile becomes available', async () => {+ const onConnectSuccess = vi.fn();++ connectGetStatusQueryMock.mockResolvedValueOnce({ connected: false }).mockResolvedValueOnce({+ connected: true,+ connection: { providerUsername: 'octocat' },+ });++ const { result } = renderHook(() =>+ useSocialConnect({+ onConnectSuccess,+ provider: 'github',+ }),+ );++ await act(async () => {+ const event = new MessageEvent('message', {+ data: {+ provider: 'github',+ type: 'SOCIAL_PROFILE_AUTH_CALLBACK',+ },+ });++ Object.defineProperty(event, 'origin', {+ configurable: true,+ value: window.location.origin,+ });++ window.dispatchEvent(event);+ await Promise.resolve();+ });++ expect(connectGetStatusQueryMock).toHaveBeenCalledTimes(1);+ expect(result.current.isConnecting).toBe(true);++ await act(async () => {+ await vi.advanceTimersByTimeAsync(1000);+ await Promise.resolve();+ });++ expect(onConnectSuccess).toHaveBeenCalledWith({+ id: 'github',+ provider: 'github',+ username: 'octocat',+ });+ expect(connectGetStatusQueryMock).toHaveBeenCalledTimes(2);+ expect(scanClaimableResourcesQueryMock).toHaveBeenCalledTimes(1);+ expect(result.current.isConnected).toBe(true);+ expect(result.current.isConnecting).toBe(false);+ });++ it('should stop waiting and expose the callback error without polling', async () => {+ const { result } = renderHook(() =>+ useSocialConnect({+ provider: 'github',+ }),+ );++ await act(async () => {+ const event = new MessageEvent('message', {+ data: {+ error: 'Access denied',+ provider: 'github',+ type: 'SOCIAL_PROFILE_AUTH_ERROR',+ },+ });++ Object.defineProperty(event, 'origin', {+ configurable: true,+ value: window.location.origin,+ });++ window.dispatchEvent(event);+ await Promise.resolve();+ });++ expect(result.current.error).toBe('Access denied');+ expect(connectGetStatusQueryMock).not.toHaveBeenCalled();+ });+});diff --git a/src/layout/AuthProvider/MarketAuth/useSocialConnect.ts b/src/layout/AuthProvider/MarketAuth/useSocialConnect.tsnew file mode 100644index 00000000000..ad3476e1fb2--- /dev/null+++ b/src/layout/AuthProvider/MarketAuth/useSocialConnect.ts@@ -0,0 +1,307 @@+'use client';++import { useCallback, useEffect, useRef, useState } from 'react';++import { lambdaClient, toolsClient } from '@/libs/trpc/client';++const POLL_INTERVAL_MS = 1000;+const POLL_TIMEOUT_MS = 15_000;+const SOCIAL_PROFILE_AUTH_CALLBACK = 'SOCIAL_PROFILE_AUTH_CALLBACK';+const SOCIAL_PROFILE_AUTH_ERROR = 'SOCIAL_PROFILE_AUTH_ERROR';++export type SocialProvider = 'github' | 'twitter';++export interface SocialProfile {+ avatarUrl?: string;+ connectedAt?: string;+ id: string;+ profileUrl?: string;+ provider: SocialProvider;+ username: string;+}++export interface ClaimableResource {+ description?: string;+ id: number;+ identifier: string;+ name?: string;+ parsedUrl?: {+ fullName: string;+ owner: string;+ repo: string;+ };+ type: 'plugin' | 'skill';+ url?: string;+}++export interface ClaimableResources {+ plugins: ClaimableResource[];+ skills: ClaimableResource[];+}++interface UseSocialConnectOptions {+ onClaimableResourcesFound?: (resources: ClaimableResources) => void;+ onConnectSuccess?: (profile: SocialProfile) => void;+ onDisconnectSuccess?: () => void;+ provider: SocialProvider;+}++export const useSocialConnect = ({+ provider,+ onConnectSuccess,+ onDisconnectSuccess,+ onClaimableResourcesFound,+}: UseSocialConnectOptions) => {+ const [isConnecting, setIsConnecting] = useState(false);+ const [isWaitingAuth, setIsWaitingAuth] = useState(false);+ const [isDisconnecting, setIsDisconnecting] = useState(false);+ const [profile, setProfile] = useState<SocialProfile | null>(null);+ const [error, setError] = useState<string | null>(null);++ const oauthWindowRef = useRef<Window | null>(null);+ const windowCheckIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);+ const pollIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);+ const pollTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const authCompletedRef = useRef(false);++ const cleanup = useCallback(() => {+ if (windowCheckIntervalRef.current) {+ clearInterval(windowCheckIntervalRef.current);+ windowCheckIntervalRef.current = null;+ }+ if (pollIntervalRef.current) {+ clearInterval(pollIntervalRef.current);+ pollIntervalRef.current = null;+ }+ if (pollTimeoutRef.current) {+ clearTimeout(pollTimeoutRef.current);+ pollTimeoutRef.current = null;+ }+ oauthWindowRef.current = null;+ setIsWaitingAuth(false);+ }, []);++ // Cleanup on unmount+ useEffect(() => {+ return () => {+ cleanup();+ };+ }, [cleanup]);++ // Fetch current profile status using existing connect API+ const fetchProfile = useCallback(async () => {+ try {+ const result = await toolsClient.market.connectGetStatus.query({ provider });+ if (result.connected && result.connection) {+ const profile: SocialProfile = {+ id: provider,+ provider: provider as SocialProvider,+ username: result.connection.providerUsername || provider,+ };+ setProfile(profile);+ return profile;+ }+ setProfile(null);+ return null;+ } catch (err) {+ console.error('[SocialConnect] Failed to fetch profile:', err);+ setProfile(null);+ return null;+ }+ }, [provider]);++ // Check for claimable resources+ const checkClaimableResources = useCallback(async () => {+ try {+ const result = await lambdaClient.market.socialProfile.scanClaimableResources.query();+ if (result.plugins.length > 0 || result.skills.length > 0) {+ onClaimableResourcesFound?.(result);+ }+ return result;+ } catch (err) {+ console.error('[SocialConnect] Failed to scan claimable resources:', err);+ return { plugins: [], skills: [] };+ }+ }, [onClaimableResourcesFound]);++ const handleConnectedProfile = useCallback(+ async (newProfile: SocialProfile) => {+ if (authCompletedRef.current) return;++ authCompletedRef.current = true;+ cleanup();+ setProfile(newProfile);+ onConnectSuccess?.(newProfile);+ await checkClaimableResources();+ },+ [checkClaimableResources, cleanup, onConnectSuccess],+ );++ const confirmConnection = useCallback(async () => {+ const newProfile = await fetchProfile();++ if (!newProfile) return false;++ await handleConnectedProfile(newProfile);++ return true;+ }, [fetchProfile, handleConnectedProfile]);++ // Fallback polling when popup callback arrives before the connection state is queryable+ const startFallbackPolling = useCallback(() => {+ if (pollIntervalRef.current || authCompletedRef.current) return;++ setIsWaitingAuth(true);++ const runCheck = async () => {+ try {+ await confirmConnection();+ } catch (err) {+ console.error('[SocialConnect] Polling check failed:', err);+ }+ };++ pollIntervalRef.current = setInterval(runCheck, POLL_INTERVAL_MS);+ void runCheck();++ pollTimeoutRef.current = setTimeout(() => {+ if (pollIntervalRef.current) {+ clearInterval(pollIntervalRef.current);+ pollIntervalRef.current = null;+ }+ if (!authCompletedRef.current) {+ setIsWaitingAuth(false);+ }+ }, POLL_TIMEOUT_MS);+ }, [confirmConnection]);++ // Listen for OAuth success message from popup window+ useEffect(() => {+ const handleMessage = async (event: MessageEvent) => {+ if (event.origin !== window.location.origin) return;++ if (event.data?.provider !== provider) return;++ if (event.data?.type === SOCIAL_PROFILE_AUTH_CALLBACK) {+ startFallbackPolling();+ }++ if (event.data?.type === SOCIAL_PROFILE_AUTH_ERROR) {+ cleanup();+ setError(event.data?.error || 'Failed to connect');+ }+ };++ window.addEventListener('message', handleMessage);+ return () => window.removeEventListener('message', handleMessage);+ }, [cleanup, provider, startFallbackPolling]);++ // Monitor OAuth window close+ const startWindowMonitor = useCallback(+ (oauthWindow: Window) => {+ windowCheckIntervalRef.current = setInterval(async () => {+ try {+ if (oauthWindow.closed) {+ if (windowCheckIntervalRef.current) {+ clearInterval(windowCheckIntervalRef.current);+ windowCheckIntervalRef.current = null;+ }+ oauthWindowRef.current = null;+ // Check if OAuth was successful+ const connected = await confirmConnection();+ if (!connected) {+ startFallbackPolling();+ }+ }+ } catch {+ // COOP headers prevent access to window.closed+ if (windowCheckIntervalRef.current) {+ clearInterval(windowCheckIntervalRef.current);+ windowCheckIntervalRef.current = null;+ }+ startFallbackPolling();+ }+ }, 500);+ },+ [confirmConnection, startFallbackPolling],+ );++ // Open OAuth popup window+ const openOAuthWindow = useCallback(+ (oauthUrl: string) => {+ cleanup();+ authCompletedRef.current = false;+ setIsWaitingAuth(true);+ setError(null);++ const oauthWindow = window.open(oauthUrl, '_blank', 'width=600,height=700');+ if (oauthWindow) {+ oauthWindowRef.current = oauthWindow;+ startWindowMonitor(oauthWindow);+ } else {+ // Popup blocked, fall back to polling+ startFallbackPolling();+ }+ },+ [cleanup, startWindowMonitor, startFallbackPolling],+ );++ // Connect handler using existing connect API+ const connect = useCallback(async () => {+ if (profile) return; // Already connected++ setIsConnecting(true);+ setError(null);++ try {+ const redirectUri = `${window.location.origin}/oauth/callback/social?provider=${encodeURIComponent(provider)}`;+ const result = await toolsClient.market.connectGetAuthorizeUrl.query({+ provider,+ redirectUri,+ });++ if (result.authorizeUrl) {+ openOAuthWindow(result.authorizeUrl);+ } else {+ throw new Error('No authorize URL returned');+ }+ } catch (err) {+ console.error('[SocialConnect] Failed to get authorize URL:', err);+ setError(err instanceof Error ? err.message : 'Failed to connect');+ } finally {+ setIsConnecting(false);+ }+ }, [provider, profile, openOAuthWindow]);++ // Disconnect handler using existing connect API+ const disconnect = useCallback(async () => {+ if (!profile) return;++ setIsDisconnecting(true);+ setError(null);++ try {+ await toolsClient.market.connectRevoke.mutate({ provider });+ setProfile(null);+ onDisconnectSuccess?.();+ } catch (err) {+ console.error('[SocialConnect] Failed to disconnect:', err);+ setError(err instanceof Error ? err.message : 'Failed to disconnect');+ } finally {+ setIsDisconnecting(false);+ }+ }, [profile, provider, onDisconnectSuccess]);++ return {+ connect,+ disconnect,+ error,+ fetchProfile,+ isConnected: !!profile,+ isConnecting: isConnecting || isWaitingAuth,+ isDisconnecting,+ profile,+ };+};++export default useSocialConnect;diff --git a/src/locales/default/discover.ts b/src/locales/default/discover.tsindex 79a0b4d5468..75505a892b1 100644--- a/src/locales/default/discover.ts+++ b/src/locales/default/discover.ts@@ -1155,12 +1155,20 @@ export default {'user.noForkedAgents': 'No forked Agents yet',+ 'user.noPlugins': "This user hasn't published any Plugins yet",++ 'user.noSkills': "This user hasn't published any Skills yet",++ 'user.plugins': 'Plugins',+'user.publishedAgents': 'Created Agents','user.publishedGroups': 'Created Groups','user.searchPlaceholder': 'Search by name or description...',+ 'user.skills': 'Skills',+'user.statusFilter.all': 'All','user.statusFilter.archived': 'Archived','user.statusFilter.deprecated': 'Deprecated',@@ -1181,4 +1189,17 @@ export default {'user.unfavoriteSuccess': 'Unsaved','user.unfollow': 'Unfollow','user.website': 'Website',++ 'user.cancel': 'Cancel',+ 'user.githubUrl': 'GitHub Repository URL',+ 'user.githubUrlInvalid': 'Please enter a valid GitHub repository URL',+ 'user.githubUrlRequired': 'Please enter a GitHub repository URL',+ 'user.submit': 'Submit',+ 'user.submitRepo': 'Submit Repo',+ 'user.submitRepoDescription':+ 'Submit your GitHub repository to import your Skills or MCPs to the community.',+ 'user.submitRepoError': 'Failed to submit repository. Please try again.',+ 'user.submitRepoHint': 'The repository will be reviewed before being published.',+ 'user.submitRepoSuccess': 'Repository submitted successfully! It will be reviewed shortly.',+ 'user.submitRepoTitle': 'Submit Your Repository',};diff --git a/src/locales/default/marketAuth.ts b/src/locales/default/marketAuth.tsindex e868c275532..1e93ffa55b1 100644--- a/src/locales/default/marketAuth.ts+++ b/src/locales/default/marketAuth.ts@@ -10,6 +10,15 @@ export default {'Create a community profile to submit and manage listings within the community.','authorize.title': 'Create Community Profile','callback.buttons.close': 'Close Window',+ 'claimResources.claim': 'Claim Selected',+ 'claimResources.description': 'We found resources linked to your account that you can claim:',+ 'claimResources.error': 'Failed to claim resources. Please try again.',+ 'claimResources.mcpSection': 'MCP Servers',+ 'claimResources.selectedCount': '{{count}} item(s) selected',+ 'claimResources.skip': 'Skip',+ 'claimResources.skillSection': 'Skills',+ 'claimResources.success': 'Successfully claimed {{count}} resource(s)',+ 'claimResources.title': 'Claim Your Resources','callback.messages.authFailed': 'Authorization failed: {{error}}','callback.messages.missingParams': 'Missing authorization parameters','callback.messages.processing': 'Processing authorization...',@@ -81,6 +90,10 @@ export default {'profileSetup.fields.website.placeholder': 'Personal website URL','profileSetup.getStarted': 'Get Started','profileSetup.save': 'Save',+ 'profileSetup.socialLinks.connected': 'Connected',+ 'profileSetup.socialLinks.connecting': 'Connecting...',+ 'profileSetup.socialLinks.connectProvider': 'Connect {{provider}}',+ 'profileSetup.socialLinks.disconnect': 'Disconnect','profileSetup.socialLinks.title': 'Social Links','profileSetup.confirmChangeUserId.cancel': 'Cancel','profileSetup.confirmChangeUserId.confirm': 'Change User ID',diff --git a/src/routes/(main)/community/(detail)/user/features/DetailProvider.tsx b/src/routes/(main)/community/(detail)/user/features/DetailProvider.tsxindex 91112e67765..ae6449669cc 100644--- a/src/routes/(main)/community/(detail)/user/features/DetailProvider.tsx+++ b/src/routes/(main)/community/(detail)/user/features/DetailProvider.tsx@@ -7,6 +7,8 @@ import { type MarketUserProfile } from '@/layout/AuthProvider/MarketAuth/types';import {type DiscoverAssistantItem,type DiscoverGroupAgentItem,+ type DiscoverPluginItem,+ type DiscoverSkillItem,type DiscoverUserInfo,} from '@/types/discover';@@ -27,6 +29,8 @@ export interface UserDetailContextConfig {action: 'publish' | 'unpublish' | 'deprecate',type?: 'agent' | 'group',) => void;+ plugins?: DiscoverPluginItem[];+ skills?: DiscoverSkillItem[];totalInstalls: number;user: DiscoverUserInfo;}diff --git a/src/routes/(main)/community/(detail)/user/features/SubmitRepoModal.tsx b/src/routes/(main)/community/(detail)/user/features/SubmitRepoModal.tsxnew file mode 100644index 00000000000..d442f96646b--- /dev/null+++ b/src/routes/(main)/community/(detail)/user/features/SubmitRepoModal.tsx@@ -0,0 +1,101 @@+'use client';++import { Flexbox, Modal, Text } from '@lobehub/ui';+import { App, Form, Input } from 'antd';+import { memo, useCallback, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { lambdaClient } from '@/libs/trpc/client';++interface SubmitRepoModalProps {+ onClose: () => void;+ onSuccess?: () => void;+ open: boolean;+}++const GITHUB_URL_REGEX = /^https?:\/\/github\.com\/[\w-]+\/[\w.-]+\/?$/;++export const SubmitRepoModal = memo<SubmitRepoModalProps>(({ open, onClose, onSuccess }) => {+ const { t } = useTranslation('discover');+ const { message } = App.useApp();+ const [form] = Form.useForm();++ const [isSubmitting, setIsSubmitting] = useState(false);++ const handleSubmit = useCallback(async () => {+ try {+ const values = await form.validateFields();+ const gitUrl = values.gitUrl?.trim();++ if (!gitUrl) {+ return;+ }++ setIsSubmitting(true);++ await lambdaClient.market.socialProfile.submitRepo.mutate({ gitUrl, type: 'skill' });++ message.success(t('user.submitRepoSuccess'));+ onSuccess?.();+ onClose();+ form.resetFields();+ } catch (error) {+ console.error('[SubmitRepoModal] Failed to submit:', error);+ message.error(error instanceof Error ? error.message : t('user.submitRepoError'));+ } finally {+ setIsSubmitting(false);+ }+ }, [form, message, t, onSuccess, onClose]);++ const handleCancel = useCallback(() => {+ form.resetFields();+ onClose();+ }, [form, onClose]);++ return (+ <Modal+ centered+ cancelText={t('user.cancel')}+ confirmLoading={isSubmitting}+ okText={t('user.submit')}+ open={open}+ title={false}+ width={480}+ onCancel={handleCancel}+ onOk={handleSubmit}+ >+ <Text strong fontSize={20} style={{ display: 'block', marginBottom: 8, marginTop: 16 }}>+ {t('user.submitRepoTitle')}+ </Text>+ <Text style={{ display: 'block', marginBottom: 16 }} type="secondary">+ {t('user.submitRepoDescription')}+ </Text>++ <Form form={form} layout="vertical">+ <Form.Item+ label={t('user.githubUrl')}+ name="gitUrl"+ rules={[+ { required: true, message: t('user.githubUrlRequired') },+ {+ pattern: GITHUB_URL_REGEX,+ message: t('user.githubUrlInvalid'),+ },+ ]}+ >+ <Input placeholder="https://github.com/username/repo" />+ </Form.Item>+ </Form>++ <Flexbox style={{ marginTop: 8 }}>+ <Text style={{ fontSize: 12 }} type="secondary">+ {t('user.submitRepoHint')}+ </Text>+ </Flexbox>+ </Modal>+ );+});++SubmitRepoModal.displayName = 'SubmitRepoModal';++export default SubmitRepoModal;diff --git a/src/routes/(main)/community/(detail)/user/features/UserContent.tsx b/src/routes/(main)/community/(detail)/user/features/UserContent.tsxindex 2e36048b897..2306e8161e3 100644--- a/src/routes/(main)/community/(detail)/user/features/UserContent.tsx+++ b/src/routes/(main)/community/(detail)/user/features/UserContent.tsx@@ -5,12 +5,16 @@ import { memo } from 'react';import UserAgentList from './UserAgentList';import UserGroupList from './UserGroupList';+import UserPluginList from './UserPluginList';+import UserSkillList from './UserSkillList';const UserContent = memo(() => {return (<Flexbox gap={32}><UserAgentList /><UserGroupList />+ <UserSkillList />+ <UserPluginList /></Flexbox>);});diff --git a/src/routes/(main)/community/(detail)/user/features/UserPluginCard.tsx b/src/routes/(main)/community/(detail)/user/features/UserPluginCard.tsxnew file mode 100644index 00000000000..897074795d6--- /dev/null+++ b/src/routes/(main)/community/(detail)/user/features/UserPluginCard.tsx@@ -0,0 +1,140 @@+'use client';++import { Avatar, Block, Flexbox, Text } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';+import { memo, useCallback } from 'react';+import { useTranslation } from 'react-i18next';+import { Link, useNavigate } from 'react-router-dom';+import urlJoin from 'url-join';++import { type DiscoverPluginItem } from '@/types/discover';++const styles = createStaticStyles(({ css, cssVar }) => {+ return {+ author: css`+ color: ${cssVar.colorTextDescription};+ `,+ desc: css`+ flex: 1;+ margin: 0 !important;+ color: ${cssVar.colorTextSecondary};+ `,+ footer: css`+ margin-block-start: 16px;+ border-block-start: 1px dashed ${cssVar.colorBorder};+ background: ${cssVar.colorBgContainer};+ `,+ secondaryDesc: css`+ font-size: 12px;+ color: ${cssVar.colorTextDescription};+ `,+ title: css`+ margin: 0 !important;+ font-size: 16px !important;+ font-weight: 500 !important;++ &:hover {+ color: ${cssVar.colorLink};+ }+ `,+ };+});++type UserPluginCardProps = DiscoverPluginItem;++const UserPluginCard = memo<UserPluginCardProps>(+ ({ title, avatar, author, description, identifier, category }) => {+ const { t } = useTranslation('discover');+ const navigate = useNavigate();+ const link = urlJoin('/community/plugin', identifier);++ const handleClick = useCallback(() => {+ navigate(link);+ }, [link, navigate]);++ return (+ <Block+ clickable+ data-testid="user-plugin-item"+ height={'100%'}+ variant={'outlined'}+ width={'100%'}+ style={{+ overflow: 'hidden',+ position: 'relative',+ }}+ onClick={handleClick}+ >+ <Flexbox+ horizontal+ align={'flex-start'}+ gap={16}+ justify={'space-between'}+ padding={16}+ width={'100%'}+ >+ <Flexbox+ horizontal+ gap={12}+ title={identifier}+ style={{+ overflow: 'hidden',+ }}+ >+ <Avatar avatar={avatar || title} size={40} style={{ flex: 'none' }} />+ <Flexbox+ flex={1}+ gap={6}+ style={{+ overflow: 'hidden',+ }}+ >+ <Flexbox+ horizontal+ align={'center'}+ flex={1}+ gap={8}+ style={{+ overflow: 'hidden',+ }}+ >+ <Link style={{ color: 'inherit', overflow: 'hidden' }} to={link}>+ <Text ellipsis as={'h2'} className={styles.title}>+ {title}+ </Text>+ </Link>+ </Flexbox>+ <Flexbox horizontal align={'center'} className={styles.author} gap={8}>+ {author && <div>{author}</div>}+ </Flexbox>+ </Flexbox>+ </Flexbox>+ </Flexbox>+ <Flexbox flex={1} gap={12} paddingInline={16}>+ <Text+ as={'p'}+ className={styles.desc}+ ellipsis={{+ rows: 3,+ }}+ >+ {description}+ </Text>+ </Flexbox>+ <Flexbox+ horizontal+ align={'center'}+ className={styles.footer}+ justify={'space-between'}+ padding={16}+ >+ <Flexbox horizontal align={'center'} className={styles.secondaryDesc} gap={8}>+ {category && t(`plugins.categories.${category}.name` as any)}+ </Flexbox>+ </Flexbox>+ </Block>+ );+ },+);++export default UserPluginCard;diff --git a/src/routes/(main)/community/(detail)/user/features/UserPluginList.tsx b/src/routes/(main)/community/(detail)/user/features/UserPluginList.tsxnew file mode 100644index 00000000000..4bf2f61b69a--- /dev/null+++ b/src/routes/(main)/community/(detail)/user/features/UserPluginList.tsx@@ -0,0 +1,91 @@+'use client';++import { Flexbox, Grid, Tag, Text } from '@lobehub/ui';+import { Input, Pagination } from 'antd';+import { memo, useEffect, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useUserDetailContext } from './DetailProvider';+import UserPluginCard from './UserPluginCard';++interface UserPluginListProps {+ pageSize?: number;+ rows?: number;+}++const UserPluginList = memo<UserPluginListProps>(({ rows = 4, pageSize = 8 }) => {+ const { t } = useTranslation('discover');+ const { plugins = [], isOwner } = useUserDetailContext();+ const [currentPage, setCurrentPage] = useState(1);+ const [searchQuery, setSearchQuery] = useState('');++ const filteredPlugins = useMemo(() => {+ let allPlugins = [...plugins];++ // Apply search filter+ if (searchQuery.trim()) {+ const query = searchQuery.toLowerCase();+ allPlugins = allPlugins.filter((plugin) => {+ const title = plugin?.title?.toLowerCase() || '';+ const description = plugin?.description?.toLowerCase() || '';+ return title.includes(query) || description.includes(query);+ });+ }++ return allPlugins;+ }, [plugins, searchQuery]);++ const paginatedPlugins = useMemo(() => {+ const startIndex = (currentPage - 1) * pageSize;+ return filteredPlugins.slice(startIndex, startIndex + pageSize);+ }, [filteredPlugins, currentPage, pageSize]);++ // Reset to page 1 when search changes+ useEffect(() => {+ setCurrentPage(1);+ }, [searchQuery]);++ if (plugins.length === 0) return null;++ const showPagination = filteredPlugins.length > pageSize;++ return (+ <Flexbox gap={16}>+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>+ <Flexbox horizontal align={'center'} gap={8}>+ <Text fontSize={16} weight={500}>+ {t('user.plugins')}+ </Text>+ {plugins.length > 0 && <Tag>{filteredPlugins.length}</Tag>}+ </Flexbox>+ {isOwner && plugins.length > 0 && (+ <Input.Search+ allowClear+ placeholder={t('user.searchPlaceholder')}+ style={{ width: 200 }}+ value={searchQuery}+ onChange={(e) => setSearchQuery(e.target.value)}+ />+ )}+ </Flexbox>+ <Grid rows={rows} width={'100%'}>+ {paginatedPlugins.map((item, index) => (+ <UserPluginCard key={item.identifier || index} {...item} />+ ))}+ </Grid>+ {showPagination && (+ <Flexbox align={'center'} justify={'center'}>+ <Pagination+ current={currentPage}+ pageSize={pageSize}+ showSizeChanger={false}+ total={filteredPlugins.length}+ onChange={(page) => setCurrentPage(page)}+ />+ </Flexbox>+ )}+ </Flexbox>+ );+});++export default UserPluginList;diff --git a/src/routes/(main)/community/(detail)/user/features/UserSkillCard.tsx b/src/routes/(main)/community/(detail)/user/features/UserSkillCard.tsxnew file mode 100644index 00000000000..b6c8a339d21--- /dev/null+++ b/src/routes/(main)/community/(detail)/user/features/UserSkillCard.tsx@@ -0,0 +1,205 @@+'use client';++import { Github } from '@lobehub/icons';+import { ActionIcon, Avatar, Block, Flexbox, Icon, stopPropagation, Tag, Text } from '@lobehub/ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { ClockIcon, FileTextIcon, StarIcon } from 'lucide-react';+import { memo, useCallback } from 'react';+import { useTranslation } from 'react-i18next';+import { Link, useNavigate } from 'react-router-dom';+import urlJoin from 'url-join';++import PublishedTime from '@/components/PublishedTime';+import { discoverService } from '@/services/discover';+import { type DiscoverSkillItem } from '@/types/discover';++const styles = createStaticStyles(({ css, cssVar }) => {+ return {+ author: css`+ color: ${cssVar.colorTextDescription};+ `,+ desc: css`+ flex: 1;+ margin: 0 !important;+ color: ${cssVar.colorTextSecondary};+ `,+ footer: css`+ margin-block-start: 16px;+ border-block-start: 1px dashed ${cssVar.colorBorder};+ background: ${cssVar.colorBgContainer};+ `,+ secondaryDesc: css`+ font-size: 12px;+ color: ${cssVar.colorTextDescription};+ `,+ title: css`+ margin: 0 !important;+ font-size: 16px !important;+ font-weight: 500 !important;++ &:hover {+ color: ${cssVar.colorLink};+ }+ `,+ };+});++type UserSkillCardProps = DiscoverSkillItem;++const UserSkillCard = memo<UserSkillCardProps>(+ ({+ name,+ icon,+ author,+ description,+ identifier,+ category,+ updatedAt,+ installCount,+ github,+ ratingAvg,+ commentCount,+ resourcesCount = 0,+ }) => {+ const { t } = useTranslation('discover');+ const navigate = useNavigate();+ const link = urlJoin('/community/skill', identifier);++ const handleClick = useCallback(() => {+ discoverService+ .reportSkillEvent({+ event: 'click',+ identifier,+ source: location.pathname,+ })+ .catch(() => {});++ navigate(link);+ }, [identifier, link, navigate]);++ return (+ <Block+ clickable+ data-testid="user-skill-item"+ height={'100%'}+ variant={'outlined'}+ width={'100%'}+ style={{+ overflow: 'hidden',+ position: 'relative',+ }}+ onClick={handleClick}+ >+ <Flexbox+ horizontal+ align={'flex-start'}+ gap={16}+ justify={'space-between'}+ padding={16}+ width={'100%'}+ >+ <Flexbox+ horizontal+ gap={12}+ title={identifier}+ style={{+ overflow: 'hidden',+ }}+ >+ <Avatar avatar={icon || name} size={40} style={{ flex: 'none' }} />+ <Flexbox+ flex={1}+ gap={6}+ style={{+ overflow: 'hidden',+ }}+ >+ <Flexbox+ horizontal+ align={'center'}+ flex={1}+ gap={8}+ style={{+ overflow: 'hidden',+ }}+ >+ <Link style={{ color: 'inherit', overflow: 'hidden' }} to={link}>+ <Text ellipsis as={'h2'} className={styles.title}>+ {name}+ </Text>+ </Link>+ </Flexbox>+ <Flexbox horizontal align={'center'} className={styles.author} gap={8}>+ {Boolean(ratingAvg) && (+ <Flexbox horizontal align={'center'} gap={4} style={{ fontSize: 13 }}>+ <Icon fill={cssVar.colorTextDescription} icon={StarIcon} size={12} />+ {ratingAvg?.toFixed(1)}+ </Flexbox>+ )}+ {author && <div>{author}</div>}+ </Flexbox>+ </Flexbox>+ </Flexbox>+ <Flexbox horizontal align={'center'} gap={4}>+ {github?.url && (+ <a+ href={github.url}+ rel="noopener noreferrer"+ target={'_blank'}+ onClick={stopPropagation}+ >+ <ActionIcon fill={cssVar.colorTextDescription} icon={Github} />+ </a>+ )}+ </Flexbox>+ </Flexbox>+ <Flexbox flex={1} gap={12} paddingInline={16}>+ <Text+ as={'p'}+ className={styles.desc}+ ellipsis={{+ rows: 3,+ }}+ >+ {description}+ </Text>+ <Flexbox+ horizontal+ align={'center'}+ className={styles.secondaryDesc}+ justify={'space-between'}+ >+ <Tag+ icon={<Icon icon={FileTextIcon} />}+ size={'small'}+ variant={'filled'}+ style={{+ color: 'inherit',+ fontSize: 'inherit',+ }}+ >+ {(resourcesCount || 0) + 1}+ </Tag>+ <Flexbox horizontal align={'center'} className={styles.secondaryDesc} gap={8}>+ {category && t(`skills.categories.${category}.name` as any)}+ </Flexbox>+ </Flexbox>+ </Flexbox>+ <Flexbox+ horizontal+ align={'center'}+ className={styles.footer}+ justify={'space-between'}+ padding={16}+ >+ <Flexbox horizontal align={'center'} gap={4}>+ <Icon className={styles.secondaryDesc} icon={ClockIcon} size={14} />+ <PublishedTime className={styles.secondaryDesc} date={updatedAt} />+ </Flexbox>+ </Flexbox>+ </Block>+ );+ },+);++export default UserSkillCard;diff --git a/src/routes/(main)/community/(detail)/user/features/UserSkillList.tsx b/src/routes/(main)/community/(detail)/user/features/UserSkillList.tsxnew file mode 100644index 00000000000..ffd0a851de1--- /dev/null+++ b/src/routes/(main)/community/(detail)/user/features/UserSkillList.tsx@@ -0,0 +1,110 @@+'use client';++import { Flexbox, Grid, Tag, Text } from '@lobehub/ui';+import { Button, Input, Pagination } from 'antd';+import { Plus } from 'lucide-react';+import { memo, useEffect, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useUserDetailContext } from './DetailProvider';+import SubmitRepoModal from './SubmitRepoModal';+import UserSkillCard from './UserSkillCard';++interface UserSkillListProps {+ pageSize?: number;+ rows?: number;+}++const UserSkillList = memo<UserSkillListProps>(({ rows = 4, pageSize = 8 }) => {+ const { t } = useTranslation('discover');+ const { skills = [], isOwner } = useUserDetailContext();+ const [currentPage, setCurrentPage] = useState(1);+ const [searchQuery, setSearchQuery] = useState('');+ const [submitModalOpen, setSubmitModalOpen] = useState(false);++ const filteredSkills = useMemo(() => {+ let allSkills = [...skills];++ // Apply search filter+ if (searchQuery.trim()) {+ const query = searchQuery.toLowerCase();+ allSkills = allSkills.filter((skill) => {+ const name = skill?.name?.toLowerCase() || '';+ const description = skill?.description?.toLowerCase() || '';+ return name.includes(query) || description.includes(query);+ });+ }++ return allSkills;+ }, [skills, searchQuery]);++ const paginatedSkills = useMemo(() => {+ const startIndex = (currentPage - 1) * pageSize;+ return filteredSkills.slice(startIndex, startIndex + pageSize);+ }, [filteredSkills, currentPage, pageSize]);++ // Reset to page 1 when search changes+ useEffect(() => {+ setCurrentPage(1);+ }, [searchQuery]);++ if (skills.length === 0 && !isOwner) return null;++ const showPagination = filteredSkills.length > pageSize;++ return (+ <>+ <Flexbox gap={16}>+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>+ <Flexbox horizontal align={'center'} gap={8}>+ <Text fontSize={16} weight={500}>+ {t('user.skills')}+ </Text>+ {skills.length > 0 && <Tag>{filteredSkills.length}</Tag>}+ </Flexbox>+ <Flexbox horizontal align={'center'} gap={8}>+ {isOwner && skills.length > 0 && (+ <Input.Search+ allowClear+ placeholder={t('user.searchPlaceholder')}+ style={{ width: 200 }}+ value={searchQuery}+ onChange={(e) => setSearchQuery(e.target.value)}+ />+ )}+ {isOwner && (+ <Button icon={<Plus size={14} />} onClick={() => setSubmitModalOpen(true)}>+ {t('user.submitRepo')}+ </Button>+ )}+ </Flexbox>+ </Flexbox>+ {skills.length > 0 ? (+ <Grid rows={rows} width={'100%'}>+ {paginatedSkills.map((item, index) => (+ <UserSkillCard key={item.identifier || index} {...item} />+ ))}+ </Grid>+ ) : (+ <Flexbox align={'center'} justify={'center'} style={{ minHeight: 120, opacity: 0.5 }}>+ <Text type={'secondary'}>{t('user.noSkills')}</Text>+ </Flexbox>+ )}+ {showPagination && (+ <Flexbox align={'center'} justify={'center'}>+ <Pagination+ current={currentPage}+ pageSize={pageSize}+ showSizeChanger={false}+ total={filteredSkills.length}+ onChange={(page) => setCurrentPage(page)}+ />+ </Flexbox>+ )}+ </Flexbox>+ <SubmitRepoModal open={submitModalOpen} onClose={() => setSubmitModalOpen(false)} />+ </>+ );+});++export default UserSkillList;diff --git a/src/routes/(main)/community/(detail)/user/index.tsx b/src/routes/(main)/community/(detail)/user/index.tsxindex 102970835d1..c0caa019b37 100644--- a/src/routes/(main)/community/(detail)/user/index.tsx+++ b/src/routes/(main)/community/(detail)/user/index.tsx@@ -1,6 +1,6 @@'use client';-import { memo, useCallback, useMemo } from 'react';+import { memo, useCallback, useEffect, useMemo, useRef } from 'react';import { useNavigate, useParams } from 'react-router-dom';import { useMarketAuth, useMarketUserProfile } from '@/layout/AuthProvider/MarketAuth';@@ -23,7 +23,8 @@ const UserDetailPage = memo<UserDetailPageProps>(({ mobile }) => {const username = decodeURIComponent(params.slug ?? '');const navigate = useNavigate();- const { getCurrentUserInfo, isAuthenticated, openProfileSetup } = useMarketAuth();+ const { checkAndShowClaimableResources, getCurrentUserInfo, isAuthenticated, openProfileSetup } =+ useMarketAuth();const useUserProfile = useDiscoverStore((s) => s.useUserProfile);const { data, isLoading, mutate } = useUserProfile({ username });@@ -36,6 +37,20 @@ const UserDetailPage = memo<UserDetailPageProps>(({ mobile }) => {const isOwner =isAuthenticated && !!currentUser && data?.user?.namespace === currentUserProfile?.namespace;+ // Track if we've already checked for claimable resources in this session+ const hasCheckedClaimable = useRef(false);++ // Check for claimable resources when owner visits their profile+ useEffect(() => {+ if (isOwner && !hasCheckedClaimable.current) {+ hasCheckedClaimable.current = true;+ // Pass mutate callback to refresh page data after claim+ checkAndShowClaimableResources(() => {+ mutate();+ });+ }+ }, [isOwner, checkAndShowClaimableResources, mutate]);+const { handleStatusChange } = useUserDetail({ onMutate: mutate });// Handle profile edit with navigation on userName change@@ -61,7 +76,17 @@ const UserDetailPage = memo<UserDetailPageProps>(({ mobile }) => {const contextConfig = useMemo(() => {if (!data || !data.user) return null;- const { user, agents, agentGroups, forkedAgents, forkedAgentGroups, favoriteAgents, favoriteAgentGroups } = data;+ const {+ user,+ agents,+ agentGroups,+ forkedAgents,+ forkedAgentGroups,+ favoriteAgents,+ favoriteAgentGroups,+ skills,+ plugins,+ } = data;const totalInstalls = agents.reduce((sum, agent) => sum + (agent.installCount || 0), 0);return {agentCount: agents.length,@@ -76,6 +101,8 @@ const UserDetailPage = memo<UserDetailPageProps>(({ mobile }) => {mobile,onEditProfile: handleEditProfile,onStatusChange: isOwner ? handleStatusChange : undefined,+ plugins: plugins || [],+ skills: skills || [],totalInstalls,user,};diff --git a/src/server/routers/lambda/market/index.ts b/src/server/routers/lambda/market/index.tsindex 24e681386cf..83ae254bfe3 100644--- a/src/server/routers/lambda/market/index.ts+++ b/src/server/routers/lambda/market/index.ts@@ -23,6 +23,7 @@ import { credsRouter } from './creds';import { oidcRouter } from './oidc';import { skillRouter } from './skill';import { socialRouter } from './social';+import { socialProfileRouter } from './socialProfile';import { userRouter } from './user';const log = debug('lambda-router:market');@@ -893,6 +894,9 @@ export const marketRouter = router({// ============================== Social Features ==============================social: socialRouter,+ // ============================== Social Profile OAuth ==============================+ socialProfile: socialProfileRouter,+submitFeedback: marketProcedure.input(z.object({diff --git a/src/server/routers/lambda/market/socialProfile.ts b/src/server/routers/lambda/market/socialProfile.tsnew file mode 100644index 00000000000..4073765dc76--- /dev/null+++ b/src/server/routers/lambda/market/socialProfile.ts@@ -0,0 +1,237 @@+import { TRPCError } from '@trpc/server';+import debug from 'debug';+import { z } from 'zod';++import { authedProcedure, router } from '@/libs/trpc/lambda';+import { marketSDK, marketUserInfo, serverDatabase } from '@/libs/trpc/lambda/middleware';++const log = debug('lambda-router:market:socialProfile');++const MARKET_BASE_URL = process.env.MARKET_BASE_URL || 'https://market.lobehub.com';++// Authenticated procedure for social profile operations+const socialProfileAuthProcedure = authedProcedure+ .use(serverDatabase)+ .use(marketUserInfo)+ .use(marketSDK);++export interface ClaimableResource {+ description?: string;+ id: number;+ identifier: string;+ name?: string;+ parsedUrl?: {+ fullName: string;+ owner: string;+ repo: string;+ };+ type: 'plugin' | 'skill';+ url?: string;+}++export interface ClaimableResources {+ plugins: ClaimableResource[];+ skills: ClaimableResource[];+}++export const socialProfileRouter = router({+ /**+ * Claim resources (Plugins and/or Skills)+ * API expects one asset at a time: { assetId: number, assetType: 'skill' | 'plugin' }+ */+ claimResources: socialProfileAuthProcedure+ .input(+ z.object({+ pluginIds: z.array(z.string()).optional(),+ skillIds: z.array(z.string()).optional(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ log('claimResources input: %O', input);++ try {+ // @ts-ignore - headers is protected but we need it for custom API calls+ const headers = ctx.marketSDK.headers as Record<string, string>;++ const claimed: Array<{ assetId: number; assetType: string }> = [];+ const errors: string[] = [];++ // Claim each skill one by one+ for (const skillId of input.skillIds || []) {+ try {+ const response = await fetch(`${MARKET_BASE_URL}/api/v1/user/claims`, {+ body: JSON.stringify({+ assetId: Number(skillId),+ assetType: 'skill',+ }),+ headers: {+ ...headers,+ 'Content-Type': 'application/json',+ },+ method: 'POST',+ });++ if (response.ok) {+ claimed.push({ assetId: Number(skillId), assetType: 'skill' });+ } else {+ const error = await response.json().catch(() => ({}));+ errors.push(error.error || `Failed to claim skill ${skillId}`);+ }+ } catch (err) {+ errors.push(`Failed to claim skill ${skillId}`);+ }+ }++ // Claim each plugin one by one+ for (const pluginId of input.pluginIds || []) {+ try {+ const response = await fetch(`${MARKET_BASE_URL}/api/v1/user/claims`, {+ body: JSON.stringify({+ assetId: Number(pluginId),+ assetType: 'plugin',+ }),+ headers: {+ ...headers,+ 'Content-Type': 'application/json',+ },+ method: 'POST',+ });++ if (response.ok) {+ claimed.push({ assetId: Number(pluginId), assetType: 'plugin' });+ } else {+ const error = await response.json().catch(() => ({}));+ errors.push(error.error || `Failed to claim plugin ${pluginId}`);+ }+ } catch (err) {+ errors.push(`Failed to claim plugin ${pluginId}`);+ }+ }++ // If nothing was claimed and there were errors, throw+ if (claimed.length === 0 && errors.length > 0) {+ throw new Error(errors[0]);+ }++ return {+ claimed,+ errors: errors.length > 0 ? errors : undefined,+ success: claimed.length > 0,+ };+ } catch (error) {+ log('Error claiming resources: %O', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: error instanceof Error ? error.message : 'Failed to claim resources',+ });+ }+ }),++ /**+ * Scan for claimable resources (MCPs and Skills)+ */+ scanClaimableResources: socialProfileAuthProcedure.query(async ({ ctx }) => {+ log('scanClaimableResources');++ try {+ // @ts-ignore - headers is protected but we need it for custom API calls+ const headers = ctx.marketSDK.headers as Record<string, string>;++ const response = await fetch(`${MARKET_BASE_URL}/api/v1/user/claims/scan`, {+ headers,+ method: 'GET',+ });++ if (!response.ok) {+ const errorData = await response.json().catch(() => ({}));+ const errorMessage =+ errorData.error || `Failed to scan claimable resources: ${response.status}`;+ throw new TRPCError({+ code: response.status === 400 ? 'BAD_REQUEST' : 'INTERNAL_SERVER_ERROR',+ message: errorMessage,+ });+ }++ const responseData = await response.json();+ // API returns { data: { plugins: [], skills: [] } }+ const data = responseData.data || responseData;+ return {+ plugins: (data.plugins || []) as ClaimableResource[],+ skills: (data.skills || []) as ClaimableResource[],+ };+ } catch (error) {+ log('Error scanning claimable resources: %O', error);+ if (error instanceof TRPCError) {+ throw error;+ }+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: error instanceof Error ? error.message : 'Failed to scan claimable resources',+ });+ }+ }),++ /**+ * Submit a GitHub repository URL for import+ */+ submitRepo: socialProfileAuthProcedure+ .input(+ z.object({+ branch: z.string().optional(),+ gitUrl: z.string().url(),+ type: z.enum(['skill', 'plugin']).default('skill'),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ log('submitRepo input: %O', input);++ try {+ // @ts-ignore - headers is protected but we need it for custom API calls+ const headers = ctx.marketSDK.headers as Record<string, string>;++ const response = await fetch(`${MARKET_BASE_URL}/api/v1/user/claims/submit-repo`, {+ body: JSON.stringify({+ branch: input.branch,+ gitUrl: input.gitUrl,+ type: input.type,+ }),+ headers: {+ ...headers,+ 'Content-Type': 'application/json',+ },+ method: 'POST',+ });++ if (!response.ok) {+ const errorData = await response.json().catch(() => ({}));+ const errorMessage = errorData.error || `Failed to submit repository: ${response.status}`;+ // Use BAD_REQUEST for 400 errors (user input errors)+ throw new TRPCError({+ code: response.status === 400 ? 'BAD_REQUEST' : 'INTERNAL_SERVER_ERROR',+ message: errorMessage,+ });+ }++ const data = await response.json();+ return {+ message: data.message,+ success: true,+ };+ } catch (error) {+ log('Error submitting repository: %O', error);+ // Re-throw TRPCError as-is+ if (error instanceof TRPCError) {+ throw error;+ }+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: error instanceof Error ? error.message : 'Failed to submit repository',+ });+ }+ }),+});++export type SocialProfileRouter = typeof socialProfileRouter;diff --git a/src/server/services/discover/index.ts b/src/server/services/discover/index.tsindex b58204a32f2..63815a49f78 100644--- a/src/server/services/discover/index.ts+++ b/src/server/services/discover/index.ts@@ -20,6 +20,7 @@ import {type DiscoverPluginItem,type DiscoverProviderDetail,type DiscoverProviderItem,+ type DiscoverSkillItem,type DiscoverUserProfile,type IdentifiersResponse,type McpListResponse,@@ -1793,6 +1794,8 @@ export class DiscoverService {favoriteAgents?: any[];forkedAgentGroups?: any[];forkedAgents?: any[];+ plugins?: any[];+ skills?: any[];};if (!response?.user) {@@ -1808,6 +1811,8 @@ export class DiscoverService {forkedAgentGroups,favoriteAgents,favoriteAgentGroups,+ skills,+ plugins,} = response;// Transform agents to DiscoverAssistantItem format@@ -1950,6 +1955,53 @@ export class DiscoverService {updatedAt: group.updatedAt,}));+ // Transform skills to DiscoverSkillItem format+ const transformedSkills: DiscoverSkillItem[] = (skills || []).map((skill: any) => ({+ author: skill.author || '',+ category: skill.category,+ commentCount: skill.commentCount,+ createdAt: skill.createdAt,+ description: skill.description || '',+ github: skill.github,+ homepage: skill.homepage,+ icon: skill.icon,+ identifier: skill.identifier,+ installCount: skill.installCount || 0,+ isFeatured: skill.isFeatured || false,+ isOfficial: skill.isOfficial || false,+ isValidated: skill.isValidated || false,+ name: skill.name || skill.identifier,+ ratingAvg: skill.ratingAvg,+ ratingCount: skill.ratingCount || 0,+ resourcesCount: skill.resourcesCount,+ status: skill.status,+ tags: skill.tags || [],+ updatedAt: skill.updatedAt,+ version: skill.version || 'latest',+ }));++ // Transform plugins to DiscoverPluginItem format+ const transformedPlugins: DiscoverPluginItem[] = (plugins || []).map((plugin: any) => ({+ author: plugin.author || '',+ avatar: plugin.avatar,+ category: plugin.category,+ createdAt: plugin.createdAt,+ description: plugin.description || '',+ homepage: `https://lobehub.com/discover/plugin/${plugin.identifier}`,+ identifier: plugin.identifier,+ installCount: plugin.installCount || 0,+ isClaimed: plugin.isClaimed || false,+ isFeatured: plugin.isFeatured || false,+ isOfficial: plugin.isOfficial || false,+ isValidated: plugin.isValidated || false,+ manifest: plugin.manifest || '',+ schemaVersion: 1,+ status: plugin.status,+ tags: plugin.tags || [],+ title: plugin.name || plugin.identifier,+ updatedAt: plugin.updatedAt,+ }));+const result: DiscoverUserProfile = {agentGroups: transformedAgentGroups,agents: transformedAgents,@@ -1957,6 +2009,8 @@ export class DiscoverService {favoriteAgents: transformedFavoriteAgents,forkedAgentGroups: transformedForkedAgentGroups,forkedAgents: transformedForkedAgents,+ plugins: transformedPlugins,+ skills: transformedSkills,user: {avatarUrl: user.avatarUrl || null,bannerUrl: user.meta?.bannerUrl || null,@@ -1974,13 +2028,15 @@ export class DiscoverService {};log(- 'getUserInfo: returning user profile with %d agents, %d groups, %d forked agents, %d forked groups, %d favorite agents, %d favorite groups',+ 'getUserInfo: returning user profile with %d agents, %d groups, %d forked agents, %d forked groups, %d favorite agents, %d favorite groups, %d skills, %d plugins',result.agents.length,result.agentGroups?.length || 0,result.forkedAgents?.length || 0,result.forkedAgentGroups?.length || 0,result.favoriteAgents?.length || 0,result.favoriteAgentGroups?.length || 0,+ result.skills?.length || 0,+ result.plugins?.length || 0,);return result;} catch (error) {