Let's use AI to Earn!
TypeScript auto-publishdouyindouyin-apielectron-appelectron-reactkuaishoukwaipublishedshipinhaotoolxiaohongshu
feat(web): Homepage UI optimization (#428)
yikaf9acba4a097b
diff --git a/project/web/src/app/[lng]/chat/[taskId]/components/ChatMessageList/index.tsx b/project/web/src/app/[lng]/chat/[taskId]/components/ChatMessageList/index.tsxindex 6c7750b6..94af8ac5 100644--- a/project/web/src/app/[lng]/chat/[taskId]/components/ChatMessageList/index.tsx+++ b/project/web/src/app/[lng]/chat/[taskId]/components/ChatMessageList/index.tsx@@ -71,6 +71,7 @@ export function ChatMessageList({createdAt={message.createdAt}steps={message.steps}workflowSteps={isLastAssistant && isGenerating ? workflowSteps : undefined}+ actions={message.actions}/>)})}diff --git a/project/web/src/app/[lng]/chat/[taskId]/hooks/useChatState.ts b/project/web/src/app/[lng]/chat/[taskId]/hooks/useChatState.tsindex bcc2fb49..0ca4421c 100644--- a/project/web/src/app/[lng]/chat/[taskId]/hooks/useChatState.ts+++ b/project/web/src/app/[lng]/chat/[taskId]/hooks/useChatState.ts@@ -102,6 +102,12 @@ export function useChatState(options: IChatStateOptions): IChatStateReturn {* 加载任务详情*/useEffect(() => {+ // 如果是 "new" 任务,不加载历史数据,等待创建+ if (taskId === 'new') {+ setIsLoading(false)+ return+ }+// 如果已经加载过,不再重复加载if (hasLoadedRef.current) {setIsLoading(false)diff --git a/project/web/src/app/[lng]/chat/[taskId]/page.tsx b/project/web/src/app/[lng]/chat/[taskId]/page.tsxindex 9540a7e9..c803800f 100644--- a/project/web/src/app/[lng]/chat/[taskId]/page.tsx+++ b/project/web/src/app/[lng]/chat/[taskId]/page.tsx@@ -45,7 +45,7 @@ export default function ChatDetailPage() {const lng = params.lng as string// Store 方法- const { continueTask, stopTask, setActionContext, handleSSEMessage } = useAgentStore()+ const { createTask, continueTask, stopTask, setActionContext, handleSSEMessage, consumePendingTask } = useAgentStore()// 聊天状态管理const {@@ -98,6 +98,44 @@ export default function ChatDetailPage() {})}, [router, lng, tHome, setActionContext])+ /**+ * 处理新任务:当 taskId 为 "new" 时,从 store 获取待处理任务并发起请求+ */+ useEffect(() => {+ if (taskId !== 'new') return++ const pendingTask = consumePendingTask()+ if (!pendingTask) {+ // 没有待处理任务,返回首页+ router.replace(`/${lng}`)+ return+ }++ // 发起任务创建+ const startTask = async () => {+ setLocalIsGenerating(true)+ try {+ await createTask({+ prompt: pendingTask.prompt,+ medias: pendingTask.medias,+ t: t as (key: string) => string,+ onTaskIdReady: (newTaskId) => {+ console.log('[ChatPage] Task ID ready:', newTaskId)+ // 使用 replace 替换 URL,不添加历史记录+ router.replace(`/${lng}/chat/${newTaskId}`)+ },+ })+ } catch (error: any) {+ console.error('[ChatPage] Create task failed:', error)+ toast.error(error.message || t('message.error' as any))+ // 出错时返回首页+ router.replace(`/${lng}`)+ }+ }++ startTask()+ }, [taskId, lng, router, consumePendingTask, createTask, t, setLocalIsGenerating])+/*** 智能滚动:用户在底部附近时自动滚动*/diff --git a/project/web/src/app/[lng]/data-monitoring/page.tsx b/project/web/src/app/[lng]/data-monitoring/page.tsxindex efffe25a..28525b1d 100644--- a/project/web/src/app/[lng]/data-monitoring/page.tsx+++ b/project/web/src/app/[lng]/data-monitoring/page.tsx@@ -13,6 +13,7 @@ import {} from '@/api/monitoring'import { AccountPlatInfoMap, PlatType } from '@/app/config/platConfig'import http from '@/utils/request'+import { openLoginModal } from '@/store/loginModal'import { urlReg } from '@/utils/regulars'import styles from './dataMonitoring.module.scss'@@ -112,7 +113,7 @@ export default function DataMonitoringPage() {setNoteLink('')loadMonitoringList(1, filterPlatform === 'all' ? undefined : filterPlatform)} else if (response && response.code === 401) {- router.push('/auth/login')+ openLoginModal()} else if (response) {// 其他错误toast.error(response.message || t('error.addFailed'))diff --git a/project/web/src/app/[lng]/page.tsx b/project/web/src/app/[lng]/page.tsxindex 700307fd..1980b9f4 100644--- a/project/web/src/app/[lng]/page.tsx+++ b/project/web/src/app/[lng]/page.tsx@@ -5,15 +5,12 @@'use client'import { useState, useCallback, useEffect } from 'react'-import { useRouter } from 'next/navigation'import { ArrowUp } from 'lucide-react'import { HomeChat } from '@/components/Home/HomeChat'import { TaskPreview } from '@/components/Home/TaskPreview'import PromptGallery from '@/components/Home/PromptGallery'import { Button } from '@/components/ui/button'import { cn } from '@/lib/utils'-// store-import { useUserStore } from '@/store/user'/*** 回到顶部按钮组件@@ -58,24 +55,11 @@ function BackToTop({ position = 'left' }: { position?: 'left' | 'right' }) {}export default function Home() {- // 获取登录状态- const token = useUserStore((state) => state.token)- const router = useRouter()-- /** 检查登录状态 */- const handleLoginRequired = () => {- if (!token) {- router.push('/auth/login')- }- }-return (<div className="min-h-screen bg-background">{/* 首屏 Chat 区域 */}<section className="min-h-[70vh] flex items-center justify-center px-4 pt-32 pb-12">- <HomeChat- onLoginRequired={token ? undefined : handleLoginRequired}- />+ <HomeChat /></section>{/* 任务预览区域 - 无数据时自动隐藏 */}diff --git a/project/web/src/app/[lng]/pricing/components/PricingContent/index.tsx b/project/web/src/app/[lng]/pricing/components/PricingContent/index.tsxindex 3ac149c8..92120ba6 100644--- a/project/web/src/app/[lng]/pricing/components/PricingContent/index.tsx+++ b/project/web/src/app/[lng]/pricing/components/PricingContent/index.tsx@@ -17,6 +17,7 @@ import { Skeleton } from '@/components/ui/skeleton'import { toast } from '@/lib/toast'import { createPaymentOrderApi, PaymentType } from '@/api/vip'import { useSettingsModalStore } from '@/components/SettingsModal/store'+import { openLoginModal } from '@/store/loginModal'/** 企业版联系邮箱 */const ENTERPRISE_EMAIL = '[email protected]'@@ -125,7 +126,7 @@ export const PricingContent = memo(({ lng }: PricingContentProps) => {// 检查用户是否已登录if (!userStore.userInfo?.id) {toast.error(t('pleaseLoginFirst'))- router.push('/auth/login')+ openLoginModal()return}diff --git a/project/web/src/app/i18n/locales/en/chat.json b/project/web/src/app/i18n/locales/en/chat.jsonindex ddaff070..baa27233 100644--- a/project/web/src/app/i18n/locales/en/chat.json+++ b/project/web/src/app/i18n/locales/en/chat.json@@ -35,7 +35,8 @@"aiCreation": "AI Creation","supportUpload": "Support image/video upload","enterToSend": "Press Enter to send",- "connectTools": "Publish to"+ "connectTools": "Publish to",+ "loginRequired": "Please login first"},"history": {"title": "Task History",@@ -62,6 +63,23 @@"toolCallCompleted": "Tool Calls Completed","toolResult": "Result Returned","processing": "Processing..."+ },+ "action": {+ "connectChannel": "Connect Channel",+ "connectChannelDesc": "You haven't connected your {{platform}} account yet. Please connect your channel account to publish content.",+ "connectNow": "Connect Now",+ "updateAuth": "Update Authorization",+ "updateAuthDesc": "Your {{platform}} account authorization has expired. Please re-authorize.",+ "reauthorize": "Re-authorize",+ "loginChannel": "Login Channel",+ "loginChannelDesc": "Please login to your {{platform}} account first.",+ "goLogin": "Go Login",+ "readyToPublish": "Ready to Publish",+ "readyToPublishDesc": "Content is ready and can be published to {{platform}}.",+ "goPublish": "Go Publish",+ "action": "Action",+ "actionDesc": "Please complete the following action",+ "continue": "Continue"}}diff --git a/project/web/src/app/i18n/locales/en/home.json b/project/web/src/app/i18n/locales/en/home.jsonindex be3ee521..142f84c0 100644--- a/project/web/src/app/i18n/locales/en/home.json+++ b/project/web/src/app/i18n/locales/en/home.json@@ -100,10 +100,10 @@"needLogin": "Need to Login","pleaseLoginChannel": "Please login to this channel account first","goLogin": "Go Login",- "needBindChannel": "Need to Bind Account",- "needBindChannelTitle": "Need to Bind Account",- "needBindChannelContent": "Please bind your account first to publish content",- "goBind": "Go Bind",+ "needBindChannel": "Connect Channel",+ "needBindChannelTitle": "Connect Channel",+ "needBindChannelContent": "{{platform}} account not found. Please add a {{platform}} account to publish.",+ "goBind": "Add Channel","platformRequiresPlugin": "This platform requires plugin publishing, please authorize the plugin first","needAuthorizePlugin": "Need to Authorize Plugin","pluginAuthorizeDescription": "This platform requires plugin publishing, please click here to authorize the plugin",diff --git a/project/web/src/app/i18n/locales/en/settings.json b/project/web/src/app/i18n/locales/en/settings.jsonindex 47686a98..ad5a2e87 100644--- a/project/web/src/app/i18n/locales/en/settings.json+++ b/project/web/src/app/i18n/locales/en/settings.json@@ -3,8 +3,8 @@"tabs": {"profile": "Profile","agent": "Agent",- "subscription": "Subscription",- "membership": "Membership",+ "subscription": "Credits",+ "membership": "Subscription","general": "General"},"profile": {diff --git a/project/web/src/app/i18n/locales/zh-CN/chat.json b/project/web/src/app/i18n/locales/zh-CN/chat.jsonindex 423ca3d7..ff64d8bd 100644--- a/project/web/src/app/i18n/locales/zh-CN/chat.json+++ b/project/web/src/app/i18n/locales/zh-CN/chat.json@@ -35,7 +35,8 @@"aiCreation": "AI 智能创作","supportUpload": "支持图片/视频上传","enterToSend": "按 Enter 发送",- "connectTools": "发布到"+ "connectTools": "发布到",+ "loginRequired": "请先登录"},"history": {"title": "任务记录",@@ -62,6 +63,23 @@"toolCallCompleted": "工具调用完成","toolResult": "返回结果","processing": "处理中..."+ },+ "action": {+ "connectChannel": "连接频道",+ "connectChannelDesc": "您还未连接 {{platform}} 账号,请先连接频道账号才能发布内容。",+ "connectNow": "立即连接",+ "updateAuth": "更新授权",+ "updateAuthDesc": "您的 {{platform}} 账号授权已过期,请重新授权。",+ "reauthorize": "重新授权",+ "loginChannel": "登录频道",+ "loginChannelDesc": "请先登录 {{platform}} 账号。",+ "goLogin": "去登录",+ "readyToPublish": "准备发布",+ "readyToPublishDesc": "内容已准备好,可以发布到 {{platform}}。",+ "goPublish": "去发布",+ "action": "操作",+ "actionDesc": "请完成以下操作",+ "continue": "继续"}}diff --git a/project/web/src/app/i18n/locales/zh-CN/home.json b/project/web/src/app/i18n/locales/zh-CN/home.jsonindex e25e13da..e582b451 100644--- a/project/web/src/app/i18n/locales/zh-CN/home.json+++ b/project/web/src/app/i18n/locales/zh-CN/home.json@@ -99,10 +99,10 @@"needLogin": "需要登录","pleaseLoginChannel": "请先登录该频道账号","goLogin": "去登录",- "needBindChannel": "需要绑定账号",- "needBindChannelTitle": "需要绑定账号",- "needBindChannelContent": "请先绑定账号才能发布内容",- "goBind": "去绑定",+ "needBindChannel": "连接频道",+ "needBindChannelTitle": "连接频道",+ "needBindChannelContent": "未找到 {{platform}} 账号,请先添加 {{platform}} 账号后再发布",+ "goBind": "添加频道","platformRequiresPlugin": "该平台需要使用插件发布,请先授权插件","needAuthorizePlugin": "需要授权插件","pluginAuthorizeDescription": "该平台需要使用插件发布,请点击这里授权插件",diff --git a/project/web/src/app/i18n/locales/zh-CN/settings.json b/project/web/src/app/i18n/locales/zh-CN/settings.jsonindex 77baec29..06d44855 100644--- a/project/web/src/app/i18n/locales/zh-CN/settings.json+++ b/project/web/src/app/i18n/locales/zh-CN/settings.json@@ -3,8 +3,8 @@"tabs": {"profile": "个人资料","agent": "Agent",- "subscription": "订阅",- "membership": "会员",+ "subscription": "额度",+ "membership": "订阅","general": "通用"},"profile": {diff --git a/project/web/src/app/layout/LayoutSidebar/components/BottomSection/VipEntry.tsx b/project/web/src/app/layout/LayoutSidebar/components/BottomSection/VipEntry.tsxindex 09b4b910..66605668 100644--- a/project/web/src/app/layout/LayoutSidebar/components/BottomSection/VipEntry.tsx+++ b/project/web/src/app/layout/LayoutSidebar/components/BottomSection/VipEntry.tsx@@ -33,16 +33,23 @@ export function VipEntry({ collapsed }: SidebarCommonProps) {<Linkhref={`/${lng}/pricing`}className={cn(- 'flex items-center rounded-lg text-muted-foreground transition-colors hover:bg-accent hover:text-foreground',- collapsed ? 'h-9 w-9 justify-center' : 'justify-between px-3 py-2',+ 'flex flex-col rounded-lg text-muted-foreground transition-colors hover:bg-accent hover:text-foreground',+ collapsed ? 'h-9 w-9 items-center justify-center' : 'px-3 py-2',)}>- <div className="flex items-center gap-2">- <Crown size={18} className="text-warning" />- {!collapsed && <span className="text-sm">{t('vip')}</span>}+ <div className={cn('flex items-center', collapsed ? 'justify-center' : 'justify-between w-full')}>+ <div className="flex items-center gap-2">+ <Crown size={18} className="text-warning" />+ {!collapsed && <span className="text-sm">{t('vip')}</span>}+ </div>+ {!collapsed && !isVip && (+ <span className="text-xs text-muted-foreground">{t('subscribe')}</span>+ )}</div>{!collapsed && !isVip && (- <span className="text-xs text-muted-foreground">{t('subscribe')}</span>+ <div className="mt-1 ml-[26px]">+ <span className="text-[10px] text-orange-500 font-medium">$19→$50 Credits</span>+ </div>)}</Link></TooltipTrigger>diff --git a/project/web/src/app/layout/LayoutSidebar/index.tsx b/project/web/src/app/layout/LayoutSidebar/index.tsxindex 4990c560..d966fd28 100644--- a/project/web/src/app/layout/LayoutSidebar/index.tsx+++ b/project/web/src/app/layout/LayoutSidebar/index.tsx@@ -12,6 +12,7 @@ import { useNotification } from '@/hooks/useNotification'import { cn } from '@/lib/utils'import { useUserStore } from '@/store/user'import { toast } from '@/lib/toast'+import { openLoginModal } from '@/store/loginModal'import NotificationPanel from '@/components/notification/NotificationPanel'import SettingsModal, { type SettingsTab } from '@/components/SettingsModal'import AddAccountModal from '@/app/[lng]/accounts/components/AddAccountModal'@@ -142,9 +143,9 @@ const LayoutSidebar = () => {return null}- // 处理登录跳转+ // 处理登录弹窗const handleLogin = () => {- router.push(`/auth/login`)+ openLoginModal()}// 打开设置弹框@@ -161,7 +162,7 @@ const LayoutSidebar = () => {const handleAddChannel = () => {if (!token) {toast.warning('请先登录')- router.push('/auth/login')+ openLoginModal(() => setAddAccountVisible(true))return}setAddAccountVisible(true)diff --git a/project/web/src/app/layout/MobileNav/index.tsx b/project/web/src/app/layout/MobileNav/index.tsxindex 50baec17..22966c23 100644--- a/project/web/src/app/layout/MobileNav/index.tsx+++ b/project/web/src/app/layout/MobileNav/index.tsx@@ -16,6 +16,7 @@ import { Button } from '@/components/ui/button'import { useGetClientLng } from '@/hooks/useSystem'import { cn } from '@/lib/utils'import { useUserStore } from '@/store/user'+import { openLoginModal } from '@/store/loginModal'/*** 移动端导航项组件@@ -80,7 +81,7 @@ const MobileNav = () => {const handleLogin = () => {handleClose()- router.push(`/auth/login`)+ openLoginModal()}return (diff --git a/project/web/src/app/layout/Providers.tsx b/project/web/src/app/layout/Providers.tsxindex e9f055ef..4b7efdd3 100644--- a/project/web/src/app/layout/Providers.tsx+++ b/project/web/src/app/layout/Providers.tsx@@ -14,6 +14,7 @@ import en_US from 'antd/es/locale/en_US'import zh_CN from 'antd/es/locale/zh_CN'import { Suspense, useEffect } from 'react'import { Toaster } from '@/components/ui/sonner'+import { GlobalLoginModal } from '@/components/common/GlobalLoginModal'import { useDataStatisticsStore } from '@/app/[lng]/dataStatistics/useDataStatistics'import useCssVariables from '@/app/hooks/useCssVariables'import { fallbackLng } from '@/app/i18n/settings'@@ -77,6 +78,7 @@ export function Providers({<Suspense><AntdRegistry><Toaster position="top-center" richColors />+ <GlobalLoginModal />{children}</AntdRegistry></Suspense>diff --git a/project/web/src/components/Chat/ActionCard/index.tsx b/project/web/src/components/Chat/ActionCard/index.tsxnew file mode 100644index 00000000..eed90d82--- /dev/null+++ b/project/web/src/components/Chat/ActionCard/index.tsx@@ -0,0 +1,199 @@+/**+ * ActionCard - Action 卡片组件+ * 用于在聊天消息中显示可交互的 action 卡片+ * 支持:连接频道、更新授权、跳转发布等+ */++'use client'++import { useRouter, useParams } from 'next/navigation'+import { Link2, RefreshCw, Send, ArrowRight, AlertCircle } from 'lucide-react'+import { cn } from '@/lib/utils'+import { useTransClient } from '@/app/i18n/client'+import { Button } from '@/components/ui/button'+import type { IActionCard } from '@/store/agent/agent.types'++export interface IActionCardProps {+ /** Action 数据 */+ action: IActionCard+ /** 自定义类名 */+ className?: string+}++/** 平台名称映射 */+const PLATFORM_NAMES: Record<string, string> = {+ douyin: '抖音',+ xhs: '小红书',+ wxSph: '微信视频号',+ KWAI: '快手',+ youtube: 'YouTube',+ wxGzh: '微信公众号',+ bilibili: 'Bilibili',+ twitter: 'Twitter',+ tiktok: 'TikTok',+ facebook: 'Facebook',+ instagram: 'Instagram',+ threads: 'Threads',+ pinterest: 'Pinterest',+ linkedin: 'LinkedIn',+}++/** 获取平台显示名称 */+function getPlatformDisplayName(platform?: string): string {+ if (!platform) return 'Platform'+ return PLATFORM_NAMES[platform] || platform.charAt(0).toUpperCase() + platform.slice(1)+}++/** Action 卡片配置 */+interface IActionConfig {+ icon: React.ReactNode+ title: string+ description: string+ buttonText: string+ bgClass: string+ borderClass: string+ iconClass: string+}++/**+ * ActionCard - 渲染单个 Action 卡片+ */+export function ActionCard({ action, className }: IActionCardProps) {+ const router = useRouter()+ const { lng } = useParams()+ const { t } = useTransClient('chat')++ const platformName = getPlatformDisplayName(action.platform)++ // 根据 action 类型获取配置+ const getActionConfig = (): IActionConfig => {+ switch (action.type) {+ case 'createChannel':+ return {+ icon: <Link2 className="w-5 h-5" />,+ title: t('action.connectChannel' as any) || '连接频道',+ description: t('action.connectChannelDesc' as any, { platform: platformName }) || `您还未连接 ${platformName} 账号,请先连接频道账号才能发布内容`,+ buttonText: t('action.connectNow' as any) || '立即连接',+ bgClass: 'bg-gradient-to-br from-blue-50 to-indigo-50 dark:from-blue-950/30 dark:to-indigo-950/30',+ borderClass: 'border-blue-200 dark:border-blue-800',+ iconClass: 'text-blue-600 dark:text-blue-400 bg-blue-100 dark:bg-blue-900/50',+ }+ case 'updateChannel':+ return {+ icon: <RefreshCw className="w-5 h-5" />,+ title: t('action.updateAuth' as any) || '更新授权',+ description: t('action.updateAuthDesc' as any, { platform: platformName }) || `${platformName} 账号授权已过期,请重新授权`,+ buttonText: t('action.reauthorize' as any) || '重新授权',+ bgClass: 'bg-gradient-to-br from-amber-50 to-orange-50 dark:from-amber-950/30 dark:to-orange-950/30',+ borderClass: 'border-amber-200 dark:border-amber-800',+ iconClass: 'text-amber-600 dark:text-amber-400 bg-amber-100 dark:bg-amber-900/50',+ }+ case 'loginChannel':+ return {+ icon: <AlertCircle className="w-5 h-5" />,+ title: t('action.loginChannel' as any) || '登录频道',+ description: t('action.loginChannelDesc' as any, { platform: platformName }) || `请先登录 ${platformName} 账号`,+ buttonText: t('action.goLogin' as any) || '去登录',+ bgClass: 'bg-gradient-to-br from-purple-50 to-pink-50 dark:from-purple-950/30 dark:to-pink-950/30',+ borderClass: 'border-purple-200 dark:border-purple-800',+ iconClass: 'text-purple-600 dark:text-purple-400 bg-purple-100 dark:bg-purple-900/50',+ }+ case 'navigateToPublish':+ return {+ icon: <Send className="w-5 h-5" />,+ title: t('action.readyToPublish' as any) || '准备发布',+ description: t('action.readyToPublishDesc' as any, { platform: platformName }) || `内容已准备好,可以发布到 ${platformName}`,+ buttonText: t('action.goPublish' as any) || '去发布',+ bgClass: 'bg-gradient-to-br from-green-50 to-emerald-50 dark:from-green-950/30 dark:to-emerald-950/30',+ borderClass: 'border-green-200 dark:border-green-800',+ iconClass: 'text-green-600 dark:text-green-400 bg-green-100 dark:bg-green-900/50',+ }+ default:+ return {+ icon: <Link2 className="w-5 h-5" />,+ title: t('action.action' as any) || '操作',+ description: t('action.actionDesc' as any) || '请完成以下操作',+ buttonText: t('action.continue' as any) || '继续',+ bgClass: 'bg-gradient-to-br from-gray-50 to-slate-50 dark:from-gray-950/30 dark:to-slate-950/30',+ borderClass: 'border-gray-200 dark:border-gray-800',+ iconClass: 'text-gray-600 dark:text-gray-400 bg-gray-100 dark:bg-gray-900/50',+ }+ }+ }++ const config = getActionConfig()++ // 处理按钮点击+ const handleClick = () => {+ const platform = action.platform || ''++ switch (action.type) {+ case 'createChannel':+ router.push(`/${lng}/accounts?addChannel=${platform}`)+ break+ case 'updateChannel':+ router.push(`/${lng}/accounts?updateChannel=${platform}`)+ break+ case 'loginChannel':+ router.push(`/${lng}/accounts?loginChannel=${platform}`)+ break+ case 'navigateToPublish':+ // 构建发布参数+ const params = new URLSearchParams()+ params.set('action', 'publish')+ params.set('aiGenerated', 'true')+ if (platform) params.set('platform', platform)+ if (action.accountId) params.set('accountId', action.accountId)+ if (action.title) params.set('title', action.title)+ if (action.description) params.set('description', action.description)+ if (action.tags?.length) params.set('tags', JSON.stringify(action.tags))+ if (action.medias?.length) params.set('medias', JSON.stringify(action.medias))+ router.push(`/${lng}/accounts?${params.toString()}`)+ break+ default:+ router.push(`/${lng}/accounts`)+ }+ }++ return (+ <div+ className={cn(+ 'rounded-xl border p-4 transition-all hover:shadow-md',+ config.bgClass,+ config.borderClass,+ className,+ )}+ >+ {/* 头部:图标 + 标题 */}+ <div className="flex items-center gap-3 mb-3">+ <div className={cn('p-2 rounded-lg', config.iconClass)}>+ {config.icon}+ </div>+ <div className="flex-1">+ <h4 className="font-semibold text-foreground">{config.title}</h4>+ {action.platform && (+ <span className="text-xs text-muted-foreground">{platformName}</span>+ )}+ </div>+ </div>++ {/* 描述 */}+ <p className="text-sm text-muted-foreground mb-4 leading-relaxed">+ {config.description}+ </p>++ {/* 操作按钮 */}+ <Button+ onClick={handleClick}+ className="w-full group"+ variant="default"+ >+ {config.buttonText}+ <ArrowRight className="w-4 h-4 ml-2 transition-transform group-hover:translate-x-1" />+ </Button>+ </div>+ )+}++export default ActionCard+diff --git a/project/web/src/components/Chat/ChatMessage/index.tsx b/project/web/src/components/Chat/ChatMessage/index.tsxindex 55cef342..c0c62912 100644--- a/project/web/src/components/Chat/ChatMessage/index.tsx+++ b/project/web/src/components/Chat/ChatMessage/index.tsx@@ -14,10 +14,11 @@ import { cn } from '@/lib/utils'import { getOssUrl } from '@/utils/oss'import { useTransClient } from '@/app/i18n/client'import type { IUploadedMedia } from '../MediaUpload'-import type { IMessageStep, IWorkflowStep } from '@/store/agent'+import type { IMessageStep, IWorkflowStep, IActionCard } from '@/store/agent'import logo from '@/assets/images/logo.png'import styles from './ChatMessage.module.scss'import { MediaPreview } from '@/components/common/MediaPreview'+import { ActionCard } from '../ActionCard'export type { IWorkflowStep }@@ -38,6 +39,8 @@ export interface IChatMessageProps {steps?: IMessageStep[]/** 工作流步骤列表(兼容旧接口,用于无steps时的显示) */workflowSteps?: IWorkflowStep[]+ /** Action 卡片列表(用于显示可交互的 action) */+ actions?: IActionCard[]/** 自定义类名 */className?: string}@@ -248,6 +251,7 @@ export function ChatMessage({errorMessage,steps = [],workflowSteps = [],+ actions = [],className,}: IChatMessageProps) {const { t } = useTransClient('chat')@@ -449,6 +453,18 @@ export function ChatMessage({<span className="text-sm">{errorMessage || 'Generation failed, please retry'}</span></div>)}++ {/* Action 卡片 */}+ {!isUser && actions && actions.length > 0 && (+ <div className="w-full space-y-3 mt-2">+ {actions.map((action, index) => (+ <ActionCard+ key={`action-${index}-${action.type}-${action.platform || ''}`}+ action={action}+ />+ ))}+ </div>+ )}</div>{/* 全局媒体预览(图片 / 视频) */}diff --git a/project/web/src/components/Home/HomeChat/index.tsx b/project/web/src/components/Home/HomeChat/index.tsxindex 2f62776d..bad28fb4 100644--- a/project/web/src/components/Home/HomeChat/index.tsx+++ b/project/web/src/components/Home/HomeChat/index.tsx@@ -12,11 +12,13 @@ import { Sparkles } from 'lucide-react'import { ChatInput } from '@/components/Chat/ChatInput'import { useTransClient } from '@/app/i18n/client'import { useAgentStore } from '@/store/agent'+import { useUserStore } from '@/store/user'import { useMediaUpload } from '@/hooks/useMediaUpload'import { toast } from '@/lib/toast'import { cn } from '@/lib/utils'import { AccountPlatInfoArr } from '@/app/config/platConfig'import AddAccountModal from '@/app/[lng]/accounts/components/AddAccountModal'+import { openLoginModal } from '@/store/loginModal'export interface IHomeChatProps {/** 登录检查回调 */@@ -36,6 +38,7 @@ export function HomeChat({const { t: tHome } = useTransClient('home')const router = useRouter()const { lng } = useParams()+ const token = useUserStore(state => state.token)// 获取默认提示文本const defaultPrompt = t('input.placeholder' as any) || 'Help me create a cat dancing video and post it directly on YouTube'@@ -45,6 +48,16 @@ export function HomeChat({const [isSubmitting, setIsSubmitting] = useState(false)const [addAccountVisible, setAddAccountVisible] = useState(false)+ // 处理添加账号点击 - 未登录时跳转登录+ const handleAddChannelClick = useCallback(() => {+ if (!token) {+ toast.warning(t('home.loginRequired' as any) || 'Please login first')+ router.push('/auth/login')+ return+ }+ setAddAccountVisible(true)+ }, [token, router, t])+// 使用媒体上传 Hookconst {medias,@@ -57,7 +70,7 @@ export function HomeChat({})// 全局 Store- const { createTask, setActionContext } = useAgentStore()+ const { setPendingTask, setActionContext } = useAgentStore()/*** 设置 Action 上下文(用于处理任务结果的 action)@@ -70,13 +83,11 @@ export function HomeChat({})}, [router, lng, tHome, setActionContext])- /** 处理发送消息 */- const handleSend = useCallback(async () => {+ /** 实际执行发送的函数 */+ const doSend = useCallback(() => {if (!inputValue.trim()) return- setIsSubmitting(true)-- // 保存当前输入(因为下面会清空)+ // 保存当前输入const currentPrompt = inputValueconst currentMedias = [...medias]@@ -84,28 +95,29 @@ export function HomeChat({setInputValue('')clearMedias()- try {- // 使用全局 Store 创建任务- await createTask({- prompt: currentPrompt,- medias: currentMedias,- t: t as (key: string) => string,- onLoginRequired,- onTaskIdReady: (taskId) => {- console.log('[HomeChat] Task ID ready:', taskId)- // 收到 taskId 后立即跳转到对话详情页- router.push(`/${lng}/chat/${taskId}`)- },- })- } catch (error: any) {- toast.error(error.message || t('message.error' as any))- console.error('Create task failed:', error)- // 恢复输入- setInputValue(currentPrompt)- } finally {- setIsSubmitting(false)+ // 将任务存入 store,立即跳转+ setPendingTask({+ prompt: currentPrompt,+ medias: currentMedias,+ })++ // 立即跳转到聊天页面(使用 "new" 作为临时 taskId)+ router.push(`/${lng}/chat/new`)+ }, [inputValue, medias, router, lng, setPendingTask, clearMedias])++ /** 处理发送消息 */+ const handleSend = useCallback(async () => {+ if (!inputValue.trim()) return++ // 检查登录状态 - 未登录时显示登录弹窗+ if (!token) {+ openLoginModal(doSend)+ return}- }, [inputValue, medias, onLoginRequired, router, lng, t, createTask, clearMedias])++ // 执行发送逻辑+ doSend()+ }, [inputValue, token, doSend])return (<div className={cn('w-full max-w-3xl mx-auto', className)}>@@ -144,7 +156,7 @@ export function HomeChat({marginTop: '-12px',position: 'relative',}}- onClick={() => setAddAccountVisible(true)}+ onClick={handleAddChannelClick}><span className="text-sm text-muted-foreground whitespace-nowrap">{t('home.connectTools' as any)}diff --git a/project/web/src/components/SettingsModal/index.tsx b/project/web/src/components/SettingsModal/index.tsxindex 27a9e816..7d59d04c 100644--- a/project/web/src/components/SettingsModal/index.tsx+++ b/project/web/src/components/SettingsModal/index.tsx@@ -118,8 +118,8 @@ export const SettingsModal = ({ open, onClose, defaultTab }: SettingsModalProps)<div className="flex w-52 shrink-0 flex-col border-r border-border">{/* 侧边栏头部 - Logo + 项目名称 */}<div className="flex shrink-0 items-center gap-2 px-5 py-4">- <Image src={logo} alt="AIToEarn" width={28} height={28} />- <span className="text-base font-semibold tracking-tight text-foreground">AIToEarn</span>+ <Image src={logo} alt="Aitoearn" width={28} height={28} />+ <span className="text-base font-semibold tracking-tight text-foreground">Aitoearn</span></div>{/* Tab 列表 */}diff --git a/project/web/src/components/SettingsModal/tabs/ProfileTab.tsx b/project/web/src/components/SettingsModal/tabs/ProfileTab.tsxindex 2ee838e1..e8af7f3b 100644--- a/project/web/src/components/SettingsModal/tabs/ProfileTab.tsx+++ b/project/web/src/components/SettingsModal/tabs/ProfileTab.tsx@@ -147,7 +147,7 @@ export function ProfileTab({ onClose }: ProfileTabProps) {clearLoginStatus()toast.success(tCommon('logout'))onClose()- router.push('/auth/login')+ router.push('/')}const totalIncome = ((userInfo as any)?.totalIncome || 0) / 100diff --git a/project/web/src/components/common/GlobalLoginModal/index.tsx b/project/web/src/components/common/GlobalLoginModal/index.tsxnew file mode 100644index 00000000..ae3800fc--- /dev/null+++ b/project/web/src/components/common/GlobalLoginModal/index.tsx@@ -0,0 +1,15 @@+/**+ * GlobalLoginModal - 全局登录弹窗+ * 使用全局 store 管理状态,放在根布局中+ */++'use client'++import { LoginModal } from '../LoginModal'++export function GlobalLoginModal() {+ return <LoginModal useGlobalStore />+}++export default GlobalLoginModal+diff --git a/project/web/src/components/common/LoginModal/index.tsx b/project/web/src/components/common/LoginModal/index.tsxnew file mode 100644index 00000000..87830261--- /dev/null+++ b/project/web/src/components/common/LoginModal/index.tsx@@ -0,0 +1,493 @@+/**+ * LoginModal - 登录弹窗组件+ * 支持 Google 登录和邮箱登录/注册+ * 移动端友好:底部抽屉式弹出+ */++'use client'++import { zodResolver } from '@hookform/resolvers/zod'+import { GoogleLogin } from '@react-oauth/google'+import { AnimatePresence, motion } from 'framer-motion'+import { ArrowLeft, Loader2, X } from 'lucide-react'+import Image from 'next/image'+import Link from 'next/link'+import { useMemo, useState, useEffect } from 'react'+import { useForm } from 'react-hook-form'+import { z } from 'zod'++import {+ googleLoginApi,+ GoogleLoginParams,+ loginWithMailApi,+ mailRegistApi,+} from '@/api/apiReq'+import { useTransClient } from '@/app/i18n/client'+import logo from '@/assets/images/logo.png'+import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { toast } from '@/lib/toast'+import { useUserStore } from '@/store/user'+import { useLoginModalStore } from '@/store/loginModal'+import { cn } from '@/lib/utils'++export interface ILoginModalProps {+ /** 是否打开(可选,不传则使用全局 store) */+ open?: boolean+ /** 关闭回调(可选,不传则使用全局 store) */+ onClose?: () => void+ /** 登录成功回调(可选,不传则使用全局 store) */+ onSuccess?: () => void+ /** 是否使用全局 store 管理状态 */+ useGlobalStore?: boolean+}++// 页面步骤类型+type Step = 'login' | 'register'++// 动画配置+const fadeInUp = {+ initial: { opacity: 0, y: 10 },+ animate: { opacity: 1, y: 0 },+ exit: { opacity: 0, y: -10 },+}++// 表单数据类型+interface LoginFormData {+ email: string+ password: string+}++interface RegisterFormData {+ verifyCode: string+ password: string+ inviteCode?: string+}++export function LoginModal({+ open: propOpen,+ onClose: propOnClose,+ onSuccess: propOnSuccess,+ useGlobalStore = false,+}: ILoginModalProps) {+ const { setToken, setUserInfo } = useUserStore()+ const { t } = useTransClient('login')++ // 全局 store 状态+ const {+ isOpen: globalOpen,+ closeLoginModal: globalClose,+ handleLoginSuccess: globalHandleSuccess,+ } = useLoginModalStore()++ // 根据 useGlobalStore 决定使用哪个状态源+ const isOpen = useGlobalStore ? globalOpen : (propOpen ?? false)+ const handleClose = useGlobalStore ? globalClose : (propOnClose ?? (() => {}))+ const handleSuccess = useGlobalStore ? globalHandleSuccess : (propOnSuccess ?? (() => {}))++ // 步骤状态+ const [step, setStep] = useState<Step>('login')+ const [userEmail, setUserEmail] = useState('')++ // 登录表单 Schema(国际化)+ const loginSchema = useMemo(() => z.object({+ email: z.string().min(1, t('emailRequired')).email(t('emailInvalid')),+ password: z.string().min(1, t('passwordRequired')),+ }), [t])++ // 注册表单 Schema(国际化)+ const registerSchema = useMemo(() => z.object({+ verifyCode: z.string().length(6, t('emailCodeLength')),+ password: z.string().min(6, t('passwordMinLength')),+ inviteCode: z.string().optional(),+ }), [t])++ // 登录表单+ const loginForm = useForm<LoginFormData>({+ resolver: zodResolver(loginSchema),+ defaultValues: {+ email: '',+ password: '',+ },+ })++ // 注册表单+ const registerForm = useForm<RegisterFormData>({+ resolver: zodResolver(registerSchema),+ defaultValues: {+ verifyCode: '',+ password: '',+ inviteCode: '',+ },+ })++ // 重置状态当弹窗关闭时+ useEffect(() => {+ if (!isOpen) {+ setStep('login')+ setUserEmail('')+ loginForm.reset()+ registerForm.reset()+ }+ }, [isOpen, loginForm, registerForm])++ // 登录成功后的处理+ const onLoginSuccess = (token: string, userInfo?: any) => {+ setToken(token)+ if (userInfo) {+ setUserInfo(userInfo)+ }+ toast.success(t('loginSuccess'))+ handleClose()+ handleSuccess()+ }++ // 处理邮箱登录+ const handleEmailLogin = async (data: LoginFormData) => {+ try {+ const response = await loginWithMailApi({ mail: data.email, password: data.password })+ if (!response) {+ return+ }++ if (response.code === 0) {+ if (response.data.type === 'regist') {+ // 用户未注册,切换到注册步骤+ setUserEmail(data.email)+ registerForm.setValue('password', data.password)+ setStep('register')+ } else if (response.data.token) {+ // 登录成功+ onLoginSuccess(response.data.token, response.data.userInfo)+ }+ } else {+ toast.error(response.message || t('loginFailed'))+ }+ } catch (error) {+ toast.error(t('loginError'))+ }+ }++ // 处理注册提交+ const handleRegisterSubmit = async (data: RegisterFormData) => {+ try {+ const response = await mailRegistApi({+ mail: userEmail,+ code: data.verifyCode,+ password: data.password,+ inviteCode: data.inviteCode || '',+ })++ if (!response) {+ toast.error(t('registerError'))+ return+ }++ if (response.code === 0 && response.data.token) {+ // 注册成功+ onLoginSuccess(response.data.token, response.data.userInfo)+ } else {+ toast.error(response.message || t('registerError'))+ }+ } catch (error) {+ toast.error(t('registerError'))+ }+ }++ // 处理 Google 登录成功+ const handleGoogleSuccess = async (credentialResponse: any) => {+ try {+ const params: GoogleLoginParams = {+ clientId: credentialResponse.clientId,+ credential: credentialResponse.credential,+ }++ const response = await googleLoginApi(params)+ if (!response) {+ toast.error(t('googleLoginFailed'))+ return+ }++ if (response.code === 0 && response.data.token) {+ // Google 登录成功+ onLoginSuccess(response.data.token, response.data.userInfo)+ } else {+ toast.error(response.message || t('googleLoginFailed'))+ }+ } catch (error) {+ toast.error(t('googleLoginFailed'))+ }+ }++ const handleGoogleError = () => {+ toast.error(t('googleLoginFailed'))+ }++ const handleBackToLogin = () => {+ setStep('login')+ registerForm.reset()+ }++ if (!isOpen) return null++ return (+ <>+ {/* 遮罩层 */}+ <div+ className="fixed inset-0 z-50 bg-black/50 backdrop-blur-sm"+ onClick={handleClose}+ />++ {/* 弹窗内容 - 移动端底部抽屉,桌面端居中 */}+ <div className={cn(+ 'fixed z-50 bg-background rounded-t-2xl sm:rounded-2xl shadow-2xl overflow-hidden',+ // 移动端:底部全宽抽屉+ 'inset-x-0 bottom-0 max-h-[90vh]',+ // 桌面端:居中弹窗+ 'sm:inset-auto sm:left-1/2 sm:top-1/2 sm:-translate-x-1/2 sm:-translate-y-1/2',+ 'sm:w-full sm:max-w-[420px] sm:max-h-[85vh]',+ )}>+ {/* 移动端拖拽指示条 */}+ <div className="flex justify-center pt-3 sm:hidden">+ <div className="w-12 h-1.5 bg-muted-foreground/20 rounded-full" />+ </div>++ {/* 关闭按钮 */}+ <button+ onClick={handleClose}+ className="absolute right-4 top-4 p-1.5 rounded-full hover:bg-muted transition-colors z-10"+ >+ <X className="w-5 h-5 text-muted-foreground" />+ </button>++ {/* 内容区域 - 可滚动 */}+ <div className="overflow-y-auto max-h-[calc(90vh-20px)] sm:max-h-[85vh] p-6 pt-4 sm:pt-6">+ <AnimatePresence mode="wait">+ {step === 'login' && (+ <motion.div+ key="login"+ variants={fadeInUp}+ initial="initial"+ animate="animate"+ exit="exit"+ transition={{ duration: 0.2 }}+ >+ {/* Logo 和标题 */}+ <div className="mb-6 flex flex-col items-center">+ <div className="mb-4 flex h-16 w-16 items-center justify-center">+ <Image src={logo} alt="AiToEarn" width={56} height={56} className="drop-shadow-md" />+ </div>+ <h2 className="text-xl font-semibold text-foreground">+ {t('welcomeBack')}+ </h2>+ <p className="mt-1 text-sm text-muted-foreground">+ {t('loginSubtitle')}+ </p>+ </div>++ {/* Google 登录按钮 */}+ <div className="flex justify-center">+ <GoogleLogin+ onSuccess={handleGoogleSuccess}+ onError={handleGoogleError}+ useOneTap={false}+ theme="outline"+ shape="rectangular"+ text="continue_with"+ locale="zh_CN"+ size="large"+ width="320"+ />+ </div>++ {/* 分隔线 */}+ <div className="my-5 flex items-center gap-4">+ <div className="h-px flex-1 bg-border" />+ <span className="text-sm text-muted-foreground/70">{t('or')}</span>+ <div className="h-px flex-1 bg-border" />+ </div>++ {/* 邮箱登录表单 */}+ <form onSubmit={loginForm.handleSubmit(handleEmailLogin)} className="space-y-3">+ <div>+ <Input+ type="email"+ placeholder={t('emailPlaceholder')}+ {...loginForm.register('email')}+ className="h-11 rounded-xl border-input bg-background px-4 text-base placeholder:text-muted-foreground/70 focus:border-ring focus:ring-0"+ />+ {loginForm.formState.errors.email && (+ <p className="mt-1 text-xs text-destructive">{loginForm.formState.errors.email.message}</p>+ )}+ </div>++ <div>+ <Input+ type="password"+ placeholder={t('enterPassword')}+ {...loginForm.register('password')}+ className="h-11 rounded-xl border-input bg-background px-4 text-base placeholder:text-muted-foreground/70 focus:border-ring focus:ring-0"+ />+ {loginForm.formState.errors.password && (+ <p className="mt-1 text-xs text-destructive">{loginForm.formState.errors.password.message}</p>+ )}+ </div>++ <Button+ type="submit"+ disabled={loginForm.formState.isSubmitting}+ className="h-11 w-full rounded-xl text-base font-medium"+ >+ {loginForm.formState.isSubmitting ? (+ <>+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />+ {t('waitingForActivation')}+ </>+ ) : (+ t('login')+ )}+ </Button>+ </form>++ {/* 忘记密码链接 */}+ <div className="mt-4 text-center">+ <Link+ href="/auth/forgot-password"+ onClick={handleClose}+ className="text-sm text-muted-foreground hover:text-foreground hover:underline transition-colors"+ >+ {t('forgotPassword')}+ </Link>+ </div>++ {/* 条款 */}+ <p className="mt-5 text-center text-xs text-muted-foreground/70">+ {t('termsText')}{' '}+ <Link href="/websit/terms-of-service" onClick={handleClose} className="text-muted-foreground underline hover:text-foreground">+ {t('termsOfService')}+ </Link>+ {' '}{t('and')}{' '}+ <Link href="/websit/privacy-policy" onClick={handleClose} className="text-muted-foreground underline hover:text-foreground">+ {t('privacyPolicy')}+ </Link>+ </p>+ </motion.div>+ )}++ {step === 'register' && (+ <motion.div+ key="register"+ variants={fadeInUp}+ initial="initial"+ animate="animate"+ exit="exit"+ transition={{ duration: 0.2 }}+ >+ {/* 返回按钮 */}+ <button+ type="button"+ onClick={handleBackToLogin}+ className="mb-4 flex cursor-pointer items-center gap-1.5 border-none bg-transparent text-muted-foreground hover:text-foreground transition-colors"+ >+ <ArrowLeft className="h-4 w-4" />+ <span className="text-sm">{t('backToLogin')}</span>+ </button>++ {/* 标题 */}+ <div className="mb-5 flex flex-col items-center">+ <div className="mb-3 flex h-14 w-14 items-center justify-center">+ <Image src={logo} alt="AiToEarn" width={48} height={48} />+ </div>+ <h2 className="text-xl font-semibold text-foreground">+ {t('completeRegistration')}+ </h2>+ <p className="mt-1 text-sm text-muted-foreground">+ {t('registerSubtitle')}+ </p>+ </div>++ {/* 邮箱提示 */}+ <div className="mb-5 rounded-xl bg-accent p-3">+ <p className="text-sm text-muted-foreground">+ {t('activationEmailSent')}+ </p>+ <p className="mt-1 text-sm font-medium text-foreground">{userEmail}</p>+ </div>++ {/* 注册表单 */}+ <form onSubmit={registerForm.handleSubmit(handleRegisterSubmit)} className="space-y-3">+ <div>+ <label className="mb-1 block text-sm text-muted-foreground">+ {t('emailCode')}+ </label>+ <Input+ type="text"+ placeholder={t('enterEmailCode')}+ maxLength={6}+ {...registerForm.register('verifyCode', {+ onChange: (e) => {+ e.target.value = e.target.value.replace(/\D/g, '').slice(0, 6)+ },+ })}+ className="h-11 rounded-xl border-input bg-background px-4 text-center text-xl tracking-[0.5em] placeholder:text-muted-foreground/70 placeholder:tracking-normal focus:border-ring focus:ring-0"+ />+ {registerForm.formState.errors.verifyCode && (+ <p className="mt-1 text-xs text-destructive">{registerForm.formState.errors.verifyCode.message}</p>+ )}+ </div>++ <div>+ <label className="mb-1 block text-sm text-muted-foreground">+ {t('setPassword')}+ </label>+ <Input+ type="password"+ placeholder={t('enterPassword')}+ {...registerForm.register('password')}+ className="h-11 rounded-xl border-input bg-background px-4 text-base placeholder:text-muted-foreground/70 focus:border-ring focus:ring-0"+ />+ {registerForm.formState.errors.password ? (+ <p className="mt-1 text-xs text-destructive">{registerForm.formState.errors.password.message}</p>+ ) : (+ <p className="mt-1 text-xs text-muted-foreground/70">{t('passwordMinLength')}</p>+ )}+ </div>++ <div>+ <label className="mb-1 block text-sm text-muted-foreground">+ {t('inviteCode')}+ </label>+ <Input+ type="text"+ placeholder={t('enterInviteCode')}+ {...registerForm.register('inviteCode')}+ className="h-11 rounded-xl border-input bg-background px-4 text-base placeholder:text-muted-foreground/70 focus:border-ring focus:ring-0"+ />+ </div>++ <Button+ type="submit"+ disabled={registerForm.formState.isSubmitting}+ className="h-11 w-full rounded-xl text-base font-medium"+ >+ {registerForm.formState.isSubmitting ? (+ <>+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />+ {t('registering')}+ </>+ ) : (+ t('completeRegistration')+ )}+ </Button>+ </form>+ </motion.div>+ )}+ </AnimatePresence>+ </div>+ </div>+ </>+ )+}++export default LoginModal+diff --git a/project/web/src/store/agent/agent.methods.ts b/project/web/src/store/agent/agent.methods.tsindex dac1993a..7f68cc25 100644--- a/project/web/src/store/agent/agent.methods.ts+++ b/project/web/src/store/agent/agent.methods.ts@@ -20,6 +20,8 @@ import type {ICreateTaskParams,ITaskData,IActionContext,+ IActionCard,+ IPendingTask,} from './agent.types'// ============ 方法工厂上下文 ============@@ -60,6 +62,35 @@ export function createStoreMethods(ctx: IMethodsContext) {set({ currentCost: resultMsg.total_cost_usd })}+ // 从 result 中提取需要显示为卡片的 actions+ const actionCards: IActionCard[] = []+ // 需要显示卡片的 action 类型(这些不会自动执行,而是显示卡片让用户点击)+ const cardActionTypes = ['createChannel', 'updateChannel', 'loginChannel']+ // 需要自动执行的 action(如发布、保存草稿等)+ const autoExecuteActions: ITaskData[] = []++ if (resultMsg.result) {+ const resultArray: ITaskData[] = Array.isArray(resultMsg.result) ? resultMsg.result : [resultMsg.result]++ resultArray.forEach((taskData) => {+ if (taskData.action && cardActionTypes.includes(taskData.action)) {+ // 转换为 ActionCard 格式+ actionCards.push({+ type: taskData.action,+ platform: taskData.platform,+ accountId: taskData.accountId,+ title: taskData.title,+ description: taskData.description,+ medias: taskData.medias,+ tags: taskData.tags,+ })+ } else {+ // 其他 action 自动执行+ autoExecuteActions.push(taskData)+ }+ })+ }+// 显示结果消息if (resultMsg.message) {messageUtils.addMarkdownMessage(resultMsg.message)@@ -72,17 +103,27 @@ export function createStoreMethods(ctx: IMethodsContext) {)if (hasAssistantMessage && currentAssistantId) {- // 如果 assistant 消息存在,更新其内容- messageUtils.updateMessageContent(resultMsg.message)+ // 如果 assistant 消息存在,更新其内容和 actions+ if (actionCards.length > 0) {+ messageUtils.updateMessageWithActions(resultMsg.message, actionCards)+ } else {+ messageUtils.updateMessageContent(resultMsg.message)+ }} else {// 如果没有 assistant 消息,创建一个新的const assistantMessage = messageUtils.createAssistantMessage()assistantMessage.content = resultMsg.messageassistantMessage.status = 'done'+ if (actionCards.length > 0) {+ assistantMessage.actions = actionCards+ }messageUtils.addMessage(assistantMessage)// 更新 refs 以便后续更新refs.currentAssistantMessageId.value = assistantMessage.id}+ } else if (actionCards.length > 0) {+ // 如果没有消息但有 action cards,也要更新+ messageUtils.updateMessageActions(actionCards)}set({@@ -91,14 +132,10 @@ export function createStoreMethods(ctx: IMethodsContext) {workflowSteps: [],})- // 处理任务结果的 actions- if (resultMsg.result && refs.actionContext.value) {- const resultArray: ITaskData[] = Array.isArray(resultMsg.result) ? resultMsg.result : [resultMsg.result]-- if (resultArray.length > 0) {- console.log('[AgentStore] Processing result actions, count:', resultArray.length)- ActionRegistry.executeBatch(resultArray, refs.actionContext.value)- }+ // 处理需要自动执行的 actions+ if (autoExecuteActions.length > 0 && refs.actionContext.value) {+ console.log('[AgentStore] Processing auto-execute actions, count:', autoExecuteActions.length)+ ActionRegistry.executeBatch(autoExecuteActions, refs.actionContext.value)}// 刷新用户 Credits 余额@@ -391,6 +428,27 @@ export function createStoreMethods(ctx: IMethodsContext) {set({ currentTaskId: taskId })},+ // ============ 待处理任务管理 ============++ /** 设置待处理任务(从首页跳转时使用) */+ setPendingTask(task: IPendingTask) {+ set({ pendingTask: task })+ },++ /** 获取并清除待处理任务 */+ consumePendingTask(): IPendingTask | null {+ const task = get().pendingTask+ if (task) {+ set({ pendingTask: null })+ }+ return task+ },++ /** 清除待处理任务 */+ clearPendingTask() {+ set({ pendingTask: null })+ },+// ============ Action 上下文管理 ============/** 设置 Action 上下文 */diff --git a/project/web/src/store/agent/agent.state.ts b/project/web/src/store/agent/agent.state.tsindex c822fa62..70d90274 100644--- a/project/web/src/store/agent/agent.state.ts+++ b/project/web/src/store/agent/agent.state.ts@@ -24,6 +24,9 @@ export const initialState: IAgentState = {// 消费状态currentCost: 0,++ // 待处理任务+ pendingTask: null,}/**diff --git a/project/web/src/store/agent/agent.types.ts b/project/web/src/store/agent/agent.types.tsindex 38b7654b..8f5de9c6 100644--- a/project/web/src/store/agent/agent.types.ts+++ b/project/web/src/store/agent/agent.types.ts@@ -74,6 +74,24 @@ export interface IMessageStep {timestamp?: number}+/** Action 卡片数据 */+export interface IActionCard {+ /** Action 类型 */+ type: ActionType+ /** 平台 */+ platform?: PlatformType+ /** 账号ID */+ accountId?: string+ /** 标题 */+ title?: string+ /** 描述 */+ description?: string+ /** 媒体数据(用于发布) */+ medias?: IMediaItem[]+ /** 标签 */+ tags?: string[]+}+/** 显示消息项 */export interface IDisplayMessage {id: string@@ -85,6 +103,8 @@ export interface IDisplayMessage {createdAt?: number/** AI 消息的步骤列表(仅 assistant 消息使用) */steps?: IMessageStep[]+ /** Action 卡片列表(用于显示可交互的 action) */+ actions?: IActionCard[]}// ============ 任务结果相关类型 ============@@ -164,6 +184,12 @@ export interface IWorkflowStep {// ============ Store 状态类型 ============+/** 待处理的任务(用于首页跳转后在聊天页创建) */+export interface IPendingTask {+ prompt: string+ medias: IUploadedMedia[]+}+/** Agent Store 状态 */export interface IAgentState {// === 任务状态 ===@@ -189,6 +215,10 @@ export interface IAgentState {// === 消费状态 ===/** 本次消费金额 */currentCost: number++ // === 待处理任务 ===+ /** 待处理的任务(从首页跳转时设置) */+ pendingTask: IPendingTask | null}// ============ Action Handler 相关类型 ============diff --git a/project/web/src/store/agent/handlers/action.handlers.ts b/project/web/src/store/agent/handlers/action.handlers.tsindex 68c0c153..3fead743 100644--- a/project/web/src/store/agent/handlers/action.handlers.ts+++ b/project/web/src/store/agent/handlers/action.handlers.ts@@ -455,12 +455,13 @@ const createChannelHandler: IActionHandler = {async execute(taskData, context) {const { router, lng, t } = contextconst platform = taskData.platform+ const platformName = platform ? platform.charAt(0).toUpperCase() + platform.slice(1) : 'Platform'- toast.warning(taskData.errorMessage || (t('aiGeneration.needBindChannel' as any) as string))+ toast.warning(t('aiGeneration.needBindChannel' as any) as string)confirm({title: t('aiGeneration.needBindChannelTitle' as any) as string,- content: taskData.errorMessage || (t('aiGeneration.needBindChannelContent' as any) as string),+ content: t('aiGeneration.needBindChannelContent' as any, { platform: platformName }) as string,okText: t('aiGeneration.goBind' as any) as string,cancelText: undefined, // 不显示取消按钮onOk: () => {diff --git a/project/web/src/store/agent/utils/message.ts b/project/web/src/store/agent/utils/message.tsindex 8c3a8b6a..d4737250 100644--- a/project/web/src/store/agent/utils/message.ts+++ b/project/web/src/store/agent/utils/message.ts@@ -3,7 +3,7 @@* 消息创建和状态管理工具*/-import type { IDisplayMessage, IUploadedMedia } from '../agent.types'+import type { IDisplayMessage, IUploadedMedia, IActionCard } from '../agent.types'import type { IAgentRefs } from './refs'/** 消息工具上下文 */@@ -83,6 +83,30 @@ export function createMessageUtils(ctx: IMessageContext) {}))},+ /**+ * 更新当前 assistant 消息的 actions+ */+ updateMessageActions(actions: IActionCard[]) {+ set((state: any) => ({+ messages: state.messages.map((m: any) =>+ m.id === refs.currentAssistantMessageId.value ? { ...m, actions } : m,+ ),+ }))+ },++ /**+ * 更新当前 assistant 消息内容和 actions+ */+ updateMessageWithActions(content: string, actions: IActionCard[]) {+ set((state: any) => ({+ messages: state.messages.map((m: any) =>+ m.id === refs.currentAssistantMessageId.value+ ? { ...m, content, status: 'done', actions }+ : m,+ ),+ }))+ },+/*** 添加消息到列表*/diff --git a/project/web/src/store/loginModal.ts b/project/web/src/store/loginModal.tsnew file mode 100644index 00000000..44b2fcdd--- /dev/null+++ b/project/web/src/store/loginModal.ts@@ -0,0 +1,65 @@+/**+ * 登录弹窗全局状态管理+ * 用于在任何地方触发登录弹窗+ */++import { create } from 'zustand'++export interface ILoginModalStore {+ /** 弹窗是否打开 */+ isOpen: boolean+ /** 登录成功后的回调 */+ onSuccessCallback: (() => void) | null+ /** 打开登录弹窗 */+ openLoginModal: (onSuccess?: () => void) => void+ /** 关闭登录弹窗 */+ closeLoginModal: () => void+ /** 触发成功回调并关闭 */+ handleLoginSuccess: () => void+}++export const useLoginModalStore = create<ILoginModalStore>((set, get) => ({+ isOpen: false,+ onSuccessCallback: null,++ openLoginModal: (onSuccess?: () => void) => {+ set({+ isOpen: true,+ onSuccessCallback: onSuccess || null,+ })+ },++ closeLoginModal: () => {+ set({+ isOpen: false,+ onSuccessCallback: null,+ })+ },++ handleLoginSuccess: () => {+ const { onSuccessCallback } = get()+ if (onSuccessCallback) {+ onSuccessCallback()+ }+ set({+ isOpen: false,+ onSuccessCallback: null,+ })+ },+}))++/**+ * 便捷方法:打开登录弹窗+ * 可以在非 React 组件中使用+ */+export function openLoginModal(onSuccess?: () => void) {+ useLoginModalStore.getState().openLoginModal(onSuccess)+}++/**+ * 便捷方法:关闭登录弹窗+ */+export function closeLoginModal() {+ useLoginModalStore.getState().closeLoginModal()+}+diff --git a/project/web/src/store/user.ts b/project/web/src/store/user.tsindex d894b7a3..595ecabb 100644--- a/project/web/src/store/user.ts+++ b/project/web/src/store/user.ts@@ -133,7 +133,7 @@ export const useUserStore = createPersistStore(// 登出logout() {methods.clearLoginStatus()- window.location.href = '/auth/login'+ window.location.href = '/'},}