Let's use AI to Earn!
TypeScript auto-publishdouyindouyin-apielectron-appelectron-reactkuaishoukwaipublishedshipinhaotoolxiaohongshu
fix: Fix some problems (#470)
Gaoa31ec17c1159
diff --git a/project/web/package.json b/project/web/package.jsonindex c2d8f637..03d19e56 100644--- a/project/web/package.json+++ b/project/web/package.json@@ -7,6 +7,7 @@"dev": "next dev -p 6060","dev:local": "cross-env NEXT_PUBLIC_API_URL=http://localhost:7001/api next dev","build": "next build",+ "type-check": "tsc --noEmit","build:copy": "tsc && next build && npm run copy-static","copy-static": "xcopy public .next\\standalone\\public /E /I /Y && if exist .next\\static xcopy .next\\static .next\\standalone\\.next\\static /E /I /Y","start": "next start",diff --git a/project/web/src/app/[lng]/tasks-history/page.tsx b/project/web/src/app/[lng]/tasks-history/page.tsxindex b3af9286..fa50e8e1 100644--- a/project/web/src/app/[lng]/tasks-history/page.tsx+++ b/project/web/src/app/[lng]/tasks-history/page.tsx@@ -9,7 +9,6 @@ import { useParams, useRouter } from 'next/navigation'import { ArrowLeft, History, RefreshCw, Star } from 'lucide-react'import { TaskCard, TaskCardSkeleton } from '@/components/Chat'import TaskHistoryList from '@/components/Chat/TaskHistoryList'-import RatingModal from '@/components/Chat/Rating'import { Button } from '@/components/ui/button'import { Pagination } from '@/components/ui/pagination'import { agentApi, type TaskListItem } from '@/api/agent'@@ -27,7 +26,6 @@ export default function TasksHistoryPage() {const [isLoading, setIsLoading] = useState(true)const [page, setPage] = useState(1)const [total, setTotal] = useState(0)- const [ratingModalFor, setRatingModalFor] = useState<string | null>(null)// 每页 16 条const pageSize = 16@@ -72,21 +70,6 @@ export default function TasksHistoryPage() {loadTasks(nextPage)}- /** 处理删除任务:删除后刷新当前页 */- const handleDelete = async (id: string) => {- try {- const result = await agentApi.deleteTask(id)- if (result && result.code === 0) {- toast.success(t('task.deleteSuccess'))- // 删除成功后,重新加载当前页,避免页码错乱- loadTasks(page)- } else {- toast.error(result?.message || t('task.deleteFailed'))- }- } catch (error) {- toast.error(t('task.deleteFailed'))- }- }/** 返回首页 */const handleBack = () => {@@ -153,21 +136,9 @@ export default function TasksHistoryPage() {<TaskHistoryListtasks={tasks}isLoading={isLoading}- onDelete={handleDelete}- onRateClick={(taskId) => setRatingModalFor(taskId)}- linkBasePath={`/${lng}/chat`}+ onRefresh={() => loadTasks(page)}/></div>- <RatingModal- taskId={ratingModalFor ?? ''}- open={!!ratingModalFor}- onClose={() => setRatingModalFor(null)}- onSaved={(data) => {- setTasks((prev) => prev.map((t) => (t.id === ratingModalFor ? { ...t, rating: data.rating ?? t.rating, ratingComment: data.comment ?? t.ratingComment } : t)))- setRatingModalFor(null)- toast.success(t('rating.saveSuccess') || 'Saved')- }}- />{/* 分页器(使用项目内的 Pagination 组件) */}{totalPages > 1 && (diff --git a/project/web/src/app/i18n/locales/en/common.json b/project/web/src/app/i18n/locales/en/common.jsonindex 20a096e2..99bf57cb 100644--- a/project/web/src/app/i18n/locales/en/common.json+++ b/project/web/src/app/i18n/locales/en/common.json@@ -29,6 +29,8 @@"cancel": "Cancel","confirm": "Confirm","selectAll": "Select All",+ "edit": "Edit",+ "delete": "Delete","loading": "Loading...","noData": "No data","noImage": "No image",diff --git a/project/web/src/app/i18n/locales/en/route.json b/project/web/src/app/i18n/locales/en/route.jsonindex 18ec94e0..52ba7510 100644--- a/project/web/src/app/i18n/locales/en/route.json+++ b/project/web/src/app/i18n/locales/en/route.json@@ -14,5 +14,6 @@"dataMonitoring": "Data Monitoring","navigation": "Navigation","aiRank": "AI Rank",- "addChannel": "Add Channel"+ "addChannel": "Add Channel",+ "sidebar.more": "More"}diff --git a/project/web/src/app/i18n/locales/zh-CN/common.json b/project/web/src/app/i18n/locales/zh-CN/common.jsonindex e43f6a22..d4a510f4 100644--- a/project/web/src/app/i18n/locales/zh-CN/common.json+++ b/project/web/src/app/i18n/locales/zh-CN/common.json@@ -29,6 +29,8 @@"cancel": "取消","confirm": "确认","selectAll": "全选",+ "edit": "编辑",+ "delete": "删除","loading": "加载中...","noData": "暂无数据","noImage": "暂无图片",diff --git a/project/web/src/app/i18n/locales/zh-CN/route.json b/project/web/src/app/i18n/locales/zh-CN/route.jsonindex 0923455d..a45cee20 100644--- a/project/web/src/app/i18n/locales/zh-CN/route.json+++ b/project/web/src/app/i18n/locales/zh-CN/route.json@@ -15,5 +15,6 @@"dataMonitoring": "数据监控","navigation": "导航","aiRank": "AI热榜",- "addChannel": "添加频道"+ "addChannel": "添加频道",+ "sidebar.more": "更多"}diff --git a/project/web/src/app/layout/LayoutSidebar/components/NavSection.tsx b/project/web/src/app/layout/LayoutSidebar/components/NavSection.tsxindex 51edc5cf..e586592f 100644--- a/project/web/src/app/layout/LayoutSidebar/components/NavSection.tsx+++ b/project/web/src/app/layout/LayoutSidebar/components/NavSection.tsx@@ -4,7 +4,7 @@'use client'-import { useState } from 'react'+import { useState, useEffect, useRef } from 'react'import Link from 'next/link'import { FileText, PlusCircle } from 'lucide-react'import { useTransClient } from '@/app/i18n/client'@@ -16,6 +16,11 @@ import {TooltipProvider,TooltipTrigger,} from '@/components/ui/tooltip'+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from '@/components/ui/popover'import type { NavSectionProps, NavItemData, SidebarCommonProps } from '../types'/** 单个导航项 */@@ -48,7 +53,7 @@ function NavItem({ item, isActive, collapsed }: NavItemProps) {</span>{!collapsed && (<span className="overflow-hidden text-ellipsis whitespace-nowrap">- {t(item.translationKey as any)}+ {t(item.translationKey)}</span>)}</Link>@@ -61,7 +66,7 @@ function NavItem({ item, isActive, collapsed }: NavItemProps) {<Tooltip><TooltipTrigger asChild>{content}</TooltipTrigger><TooltipContent side="right">- <p>{t(item.translationKey as any)}</p>+ <p>{t(item.translationKey)}</p></TooltipContent></Tooltip></TooltipProvider>@@ -94,7 +99,7 @@ function AddChannelButton({ collapsed, onClick }: AddChannelButtonProps) {</span>{!collapsed && (<span className="overflow-hidden text-ellipsis whitespace-nowrap">- {t('addChannel' as any)}+ {t('addChannel')}</span>)}</button>@@ -107,7 +112,7 @@ function AddChannelButton({ collapsed, onClick }: AddChannelButtonProps) {<Tooltip><TooltipTrigger asChild>{content}</TooltipTrigger><TooltipContent side="right">- <p>{t('addChannel' as any)}</p>+ <p>{t('addChannel')}</p></TooltipContent></Tooltip></TooltipProvider>@@ -137,6 +142,46 @@ export function NavSection({ items, currentRoute, collapsed, onAddChannel }: Navconst otherItems = items.filter(i => !groupKeys.includes(i.translationKey as string))const [groupOpen, setGroupOpen] = useState(false)+ const [popoverOpen, setPopoverOpen] = useState(false)+ const hoverTimeoutRef = useRef<NodeJS.Timeout>()+ const { t } = useTransClient('route')++ // Auto-expand group if current route is in the grouped items (only for expanded mode)+ useEffect(() => {+ if (!collapsed) {+ const isCurrentRouteInGroup = groupedItems.some(item => item.path === currentRoute)+ if (isCurrentRouteInGroup && !groupOpen) {+ setGroupOpen(true)+ }+ }+ }, [currentRoute, groupedItems, groupOpen, collapsed])++ // Cleanup timeout on unmount+ useEffect(() => {+ return () => {+ if (hoverTimeoutRef.current) {+ clearTimeout(hoverTimeoutRef.current)+ }+ }+ }, [])++ const handleMouseEnter = () => {+ if (hoverTimeoutRef.current) {+ clearTimeout(hoverTimeoutRef.current)+ }+ hoverTimeoutRef.current = setTimeout(() => {+ setPopoverOpen(true)+ }, 200) // 200ms delay to prevent accidental triggers+ }++ const handleMouseLeave = () => {+ if (hoverTimeoutRef.current) {+ clearTimeout(hoverTimeoutRef.current)+ }+ hoverTimeoutRef.current = setTimeout(() => {+ setPopoverOpen(false)+ }, 300) // 300ms delay to allow moving to popover+ }return (<nav className="flex flex-col gap-1">@@ -175,39 +220,92 @@ export function NavSection({ items, currentRoute, collapsed, onAddChannel }: Nav{/* Collapsible group for Task History / Data / Library / Drafts */}{groupedItems.length > 0 && (<div>- <div className="mt-1">- <button- onClick={() => setGroupOpen((s) => !s)}- className={cn(- 'relative flex items-center rounded-lg text-sm font-medium transition-all w-full',- 'text-muted-foreground hover:bg-accent hover:text-foreground',- collapsed ? 'justify-center px-2 py-2.5' : 'gap-3 px-3 py-2.5',- )}- >- <span className="flex shrink-0 items-center justify-center">- <FileText size={20} />- </span>- {!collapsed && (- <span className="overflow-hidden text-ellipsis whitespace-nowrap">- {/* Use a generic label for the grouped section */}- {useTransClient('route').t('sidebar.more' as any) || 'More'}- </span>- )}- </button>- </div>-- {/* Expand list when open */}- {!collapsed && groupOpen && (- <div className="mt-1 flex flex-col gap-1 pl-2">- {groupedItems.map((gitem) => (- <NavItem- key={gitem.path || gitem.translationKey}- item={gitem}- isActive={gitem.path === currentRoute}- collapsed={collapsed}- />- ))}+ {collapsed ? (+ /* Collapsed mode: Show popover menu on hover */+ <div className="mt-1">+ <Popover open={popoverOpen} onOpenChange={setPopoverOpen}>+ <PopoverTrigger asChild>+ <button+ className={cn(+ 'relative flex items-center justify-center rounded-lg text-sm font-medium transition-all w-full',+ 'text-muted-foreground hover:bg-accent hover:text-foreground',+ 'px-2 py-2.5',+ )}+ onMouseEnter={handleMouseEnter}+ onMouseLeave={handleMouseLeave}+ >+ <span className="flex shrink-0 items-center justify-center">+ <FileText size={20} />+ </span>+ </button>+ </PopoverTrigger>+ <PopoverContent+ side="right"+ align="start"+ className="w-48 p-2"+ onMouseEnter={() => {+ if (hoverTimeoutRef.current) {+ clearTimeout(hoverTimeoutRef.current)+ }+ }}+ onMouseLeave={handleMouseLeave}+ >+ <div className="space-y-1">+ {groupedItems.map((gitem) => (+ <NavItem+ key={gitem.path || gitem.translationKey}+ item={gitem}+ isActive={gitem.path === currentRoute}+ collapsed={false} // Always show text in popover+ />+ ))}+ </div>+ </PopoverContent>+ </Popover></div>+ ) : (+ /* Expanded mode: Show traditional collapsible group */+ <>+ <div className="mt-1">+ <button+ onClick={() => setGroupOpen((s) => !s)}+ className={cn(+ 'relative flex items-center rounded-lg text-sm font-medium transition-all w-full',+ 'text-muted-foreground hover:bg-accent hover:text-foreground',+ groupOpen && 'bg-accent text-foreground',+ 'gap-3 px-3 py-2.5',+ )}+ >+ <span className="flex shrink-0 items-center justify-center">+ <FileText size={20} />+ </span>+ <span className="overflow-hidden text-ellipsis whitespace-nowrap">+ {/* Use a generic label for the grouped section */}+ {t('sidebar.more')}+ </span>+ {/* Show expand/collapse indicator */}+ <span className="absolute right-3 top-1/2 -translate-y-1/2 text-xs opacity-60">+ {groupOpen ? '−' : '+'}+ </span>+ </button>+ </div>++ {/* Expand list when open */}+ {groupOpen && (+ <div className="mt-1 pl-2">+ <div className="flex flex-col gap-1">+ {groupedItems.map((gitem) => (+ <NavItem+ key={gitem.path || gitem.translationKey}+ item={gitem}+ isActive={gitem.path === currentRoute}+ collapsed={collapsed}+ />+ ))}+ </div>+ </div>+ )}+ </>)}</div>)}diff --git a/project/web/src/app/layout/LayoutSidebar/index.tsx b/project/web/src/app/layout/LayoutSidebar/index.tsxindex c43c8456..c39bb4e8 100644--- a/project/web/src/app/layout/LayoutSidebar/index.tsx+++ b/project/web/src/app/layout/LayoutSidebar/index.tsx@@ -9,6 +9,7 @@ import type { SettingsTab } from '@/components/SettingsModal'import { BookOpen } from 'lucide-react'import { useRouter, useSelectedLayoutSegments } from 'next/navigation'import { useEffect, useState } from 'react'+import { useShallow } from 'zustand/shallow'import AddAccountModal from '@/app/[lng]/accounts/components/AddAccountModal'import { routerData } from '@/app/layout/routerData'import NotificationPanel from '@/components/notification/NotificationPanel'@@ -118,8 +119,18 @@ function LayoutSidebar() {const route = useSelectedLayoutSegments()const { unreadCount } = useNotification()+ // 获取侧边栏状态和设置方法+ const {+ sidebarCollapsed: collapsed,+ setSidebarCollapsed: setCollapsed,+ } = useUserStore(+ useShallow(state => ({+ sidebarCollapsed: state.sidebarCollapsed,+ setSidebarCollapsed: state.setSidebarCollapsed,+ })),+ )+// UI 状态- const [collapsed, setCollapsed] = useState(false)const [notificationVisible, setNotificationVisible] = useState(false)const [addAccountVisible, setAddAccountVisible] = useState(false)const {diff --git a/project/web/src/components/ChannelManager/components/SpaceItem.tsx b/project/web/src/components/ChannelManager/components/SpaceItem.tsxindex 2bc1ffd0..524b4b82 100644--- a/project/web/src/components/ChannelManager/components/SpaceItem.tsx+++ b/project/web/src/components/ChannelManager/components/SpaceItem.tsx@@ -166,7 +166,7 @@ export function SpaceItem({<DropdownMenuContent align="end"><DropdownMenuItem onClick={onStartEdit}><Edit className="h-4 w-4 mr-2" />- {t('common.edit', '编辑')}+ {t('actions.edit')}</DropdownMenuItem>{canMoveUp && (<DropdownMenuItem@@ -198,7 +198,7 @@ export function SpaceItem({className="text-destructive"><Trash2 className="h-4 w-4 mr-2" />- {t('common.delete', '删除')}+ {t('actions.delete')}</DropdownMenuItem></DropdownMenuContent></DropdownMenu>diff --git a/project/web/src/components/ChannelManager/components/SpaceListSkeleton.tsx b/project/web/src/components/ChannelManager/components/SpaceListSkeleton.tsxindex 74f0ccbd..42235615 100644--- a/project/web/src/components/ChannelManager/components/SpaceListSkeleton.tsx+++ b/project/web/src/components/ChannelManager/components/SpaceListSkeleton.tsx@@ -48,7 +48,7 @@ export function SpaceListSkeleton() {<div className="flex items-center justify-center py-4"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /><span className="ml-2 text-sm text-muted-foreground">- {t('common.loading', '加载中...')}+ {t('common.actions.loading', '加载中...')}</span></div></div>diff --git a/project/web/src/components/Chat/TaskCard/index.tsx b/project/web/src/components/Chat/TaskCard/index.tsxindex 0c63b4c8..8e33368c 100644--- a/project/web/src/components/Chat/TaskCard/index.tsx+++ b/project/web/src/components/Chat/TaskCard/index.tsx@@ -3,76 +3,92 @@* 功能:显示任务简要信息,支持点击跳转到对话详情*/-'use client'--import type React from 'react'-import { AlertCircle, CheckCircle2, Loader2, MessageSquare, Trash2 } from 'lucide-react'-import { useRouter } from 'next/navigation'-import { useState } from 'react'-import { useTransClient } from '@/app/i18n/client'-import { useGetClientLng } from '@/hooks/useSystem'-import { toast } from '@/lib/toast'-import { cn, formatRelativeTime } from '@/lib/utils'+"use client";++import type React from "react";+import {+ AlertCircle,+ CheckCircle2,+ Loader2,+ MessageSquare,+ Star,+ Trash2,+} from "lucide-react";+import { useRouter } from "next/navigation";+import { useState } from "react";+import { useTransClient } from "@/app/i18n/client";+import { useGetClientLng } from "@/hooks/useSystem";+import { toast } from "@/lib/toast";+import { cn, formatRelativeTime } from "@/lib/utils";export interface ITaskCardProps {/** 任务ID */- id: string+ id: string;/** 任务标题 */- title: string+ title: string;/** 任务状态(英文原始状态字符串) */- status?: string+ status?: string;/** 创建时间 */- createdAt: string | number+ createdAt: string | number;/** 更新时间 */- updatedAt?: string | number+ updatedAt?: string | number;+ /** 任务评分(1-5) */+ rating?: number | null;/** 删除回调 */- onDelete?: (id: string) => void | Promise<void>+ onDelete?: (id: string) => void | Promise<void>;/** 评分回调(用于历史列表触发外部评分弹窗) */- onRateClick?: (taskId: string) => void+ onRateClick?: (taskId: string) => void;/** 选择回调(如果提供,点击卡片将触发选择而不是跳转) */- onSelect?: (id: string) => void+ onSelect?: (id: string) => void;/** 在主页展示内联评分控件 */- showInlineRating?: boolean+ showInlineRating?: boolean;/** 自定义类名 */- className?: string+ className?: string;}/** 获取状态显示配置 */-function getStatusConfig(status: string | undefined, t: (key: string) => string) {- const normalizedStatus = status?.toLowerCase()+function getStatusConfig(+ status: string | undefined,+ t: (key: string) => string+) {+ const normalizedStatus = status?.toLowerCase();switch (normalizedStatus) {- case 'requires_action':+ case "requires_action":return {- label: t('task.status.requiresAction') || 'Requires Action',- className: 'bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-400 border-amber-200 dark:border-amber-800',+ label: t("task.status.requiresAction") || "Requires Action",+ className:+ "bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-400 border-amber-200 dark:border-amber-800",icon: AlertCircle,- }- case 'completed':+ };+ case "completed":return {- label: t('task.status.completed') || 'Completed',- className: 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400 border-green-200 dark:border-green-800',+ label: t("task.status.completed") || "Completed",+ className:+ "bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400 border-green-200 dark:border-green-800",icon: CheckCircle2,- }- case 'running':+ };+ case "running":return {- label: t('task.status.running') || 'Running',- className: 'bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400 border-blue-200 dark:border-blue-800',+ label: t("task.status.running") || "Running",+ className:+ "bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400 border-blue-200 dark:border-blue-800",icon: Loader2,- }- case 'error':- case 'failed':+ };+ case "error":+ case "failed":return {- label: t('task.status.failed') || 'Failed',- className: 'bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-400 border-red-200 dark:border-red-800',+ label: t("task.status.failed") || "Failed",+ className:+ "bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-400 border-red-200 dark:border-red-800",icon: AlertCircle,- }+ };default:return {- label: status || '',- className: 'bg-muted text-muted-foreground border-border',+ label: status || "",+ className: "bg-muted text-muted-foreground border-border",icon: null,- }+ };}}@@ -85,44 +101,43 @@ export function TaskCard({status,createdAt,updatedAt,+ rating,onDelete,className,onSelect,onRateClick,}: ITaskCardProps) {- const router = useRouter()- const lng = useGetClientLng()- const { t } = useTransClient('chat')- const [isDeleting, setIsDeleting] = useState(false)- const [isProcessing, setIsProcessing] = useState(false)+ const router = useRouter();+ const lng = useGetClientLng();+ const { t } = useTransClient("chat");+ const [isDeleting, setIsDeleting] = useState(false);+ const [isProcessing, setIsProcessing] = useState(false);- const statusConfig = getStatusConfig(status, t as (key: string) => string)+ const statusConfig = getStatusConfig(status, t as (key: string) => string);/** 跳转到对话详情页 */const handleClick = () => {- if (isDeleting)- return+ if (isDeleting) return;if (onSelect) {- onSelect(id)- return+ onSelect(id);+ return;}- router.push(`/${lng}/chat/${id}`)- }+ router.push(`/${lng}/chat/${id}`);+ };/** 处理删除 */const handleDelete = async (e: React.MouseEvent) => {- e.stopPropagation()- if (!onDelete || isDeleting)- return+ e.stopPropagation();+ e.preventDefault();+ if (!onDelete || isDeleting) return;try {- setIsDeleting(true)- await onDelete(id)+ setIsDeleting(true);+ await onDelete(id);+ } finally {+ setIsDeleting(false);}- finally {- setIsDeleting(false)- }- }+ };// Note: share and public-link actions intentionally removed from UI per request.@@ -130,20 +145,20 @@ export function TaskCard({/** 触发评分回调(由历史列表等外部组件使用) */const handleRateClick = (e: React.MouseEvent) => {- e.stopPropagation()- if (!onRateClick)- return- onRateClick(id)- }+ e.stopPropagation();+ e.preventDefault();+ if (!onRateClick) return;+ onRateClick(id);+ };return (<divonClick={handleClick}className={cn(- 'flex flex-col p-4 rounded-xl border border-border bg-card cursor-pointer transition-all',- 'hover:border-border hover:shadow-md',- isDeleting && 'opacity-60 cursor-wait',- className,+ "flex flex-col p-4 rounded-xl border border-border bg-card cursor-pointer transition-all",+ "hover:border-border hover:shadow-md",+ isDeleting && "opacity-60 cursor-wait",+ className)}>{/* 图标 + 标题 */}@@ -151,8 +166,11 @@ export function TaskCard({<div className="w-8 h-8 rounded-lg bg-muted flex items-center justify-center shrink-0"><MessageSquare className="w-4 h-4 text-muted-foreground" /></div>- <h4 className="text-sm font-medium text-foreground line-clamp-2 flex-1 pt-1">- {title || 'New Chat'}+ <h4+ title={title}+ className="text-sm font-medium text-foreground truncate flex-1 pt-1"+ >+ {title || "New Chat"}</h4></div>@@ -162,16 +180,18 @@ export function TaskCard({{formatRelativeTime(new Date(updatedAt || createdAt))}</span>{status && statusConfig.label && (- <span className={cn(- 'inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] font-medium',- statusConfig.className,- )}+ <span+ className={cn(+ "inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] font-medium",+ statusConfig.className+ )}>{statusConfig.icon && (- <statusConfig.icon className={cn(- 'w-3 h-3',- status?.toLowerCase() === 'running' && 'animate-spin',- )}+ <statusConfig.icon+ className={cn(+ "w-3 h-3",+ status?.toLowerCase() === "running" && "animate-spin"+ )}/>)}{statusConfig.label}@@ -179,22 +199,39 @@ export function TaskCard({)}</div>- {/* Action buttons: subtle delete (share and rating hidden per request) */}- <div className="mt-3 flex items-center justify-end">+ {/* Action buttons: rating and delete */}+ <div className="mt-3 flex items-center justify-end gap-2">+ <button+ onClick={handleRateClick}+ className="flex items-center gap-1 px-2 py-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors text-xs opacity-60 hover:opacity-100"+ aria-label="rate"+ >+ <Star+ className={`w-3 h-3 ${rating ? "text-amber-400" : ""}`}+ {...(rating ? { fill: "currentColor" } : {})}+ />+ <span className="hidden sm:inline">+ {t("task.rate" as any) || "Rate"}+ </span>+ </button><buttononClick={handleDelete}disabled={isDeleting}className="flex items-center gap-1 px-2 py-1.5 rounded-md hover:bg-destructive/10 text-muted-foreground hover:text-destructive transition-colors text-xs opacity-60 hover:opacity-100"aria-label="delete">- {isDeleting ? <Loader2 className="w-3 h-3 animate-spin" /> : <Trash2 className="w-3 h-3" />}- <span className="hidden sm:inline">{t('task.delete' as any) || 'Delete'}</span>+ {isDeleting ? (+ <Loader2 className="w-3 h-3 animate-spin" />+ ) : (+ <Trash2 className="w-3 h-3" />+ )}+ <span className="hidden sm:inline">+ {t("task.delete" as any) || "Delete"}+ </span></button></div>-- {/* Rating UI hidden on TaskCard as requested */}</div>- )+ );}-export default TaskCard+export default TaskCard;diff --git a/project/web/src/components/Chat/TaskHistoryList.tsx b/project/web/src/components/Chat/TaskHistoryList.tsxindex 3f365e3c..222c9509 100644--- a/project/web/src/components/Chat/TaskHistoryList.tsx+++ b/project/web/src/components/Chat/TaskHistoryList.tsx@@ -2,35 +2,79 @@* TaskHistoryList - 可复用的任务卡片列表组件* 用于在不同页面展示任务网格,支持 loading skeleton、删除、评分回调和可选链接包裹*/- 'use client'+"use client";-import React from "react"-import { TaskCard, TaskCardSkeleton } from "@/components/Chat"-import { type TaskListItem } from "@/api/agent"-import { cn } from "@/lib/utils"+import React, { useState } from "react";+import { TaskCard, TaskCardSkeleton } from "@/components/Chat";+import RatingModal from "@/components/Chat/Rating";+import { agentApi, type TaskListItem } from "@/api/agent";+import { toast } from "@/lib/toast";+import { useTransClient } from "@/app/i18n/client";+import { cn } from "@/lib/utils";export interface ITaskHistoryListProps {- tasks: TaskListItem[]- isLoading?: boolean- skeletonCount?: number- onDelete?: (id: string) => void | Promise<void>- onRateClick?: (taskId: string) => void- className?: string+ tasks: TaskListItem[];+ isLoading?: boolean;+ skeletonCount?: number;+ /** 刷新列表回调,由父组件提供 */+ onRefresh?: () => void | Promise<void>;+ className?: string;/** 可选:为每条记录生成链接的前缀(例如 '/en/chat'),若传入则会用 <a> 包裹 TaskCard */- linkBasePath?: string+ linkBasePath?: string;}export const TaskHistoryList = ({tasks,isLoading = false,skeletonCount = 4,- onDelete,- onRateClick,+ onRefresh,className,- linkBasePath,+ linkBasePath = '/chat',}: ITaskHistoryListProps) => {+ const { t } = useTransClient("chat");+ const [ratingModalFor, setRatingModalFor] = useState<string | null>(null);++ const handleRateClick = (taskId: string) => {+ setRatingModalFor(taskId);+ };++ /** 处理删除任务 */+ const handleDelete = async (id: string) => {+ try {+ const result = await agentApi.deleteTask(id);+ if (result && result.code === 0) {+ toast.success(t("task.deleteSuccess" as any));+ // 调用父组件的刷新回调+ if (onRefresh) {+ await onRefresh();+ }+ } else {+ toast.error((result as any)?.message || t("task.deleteFailed" as any));+ }+ } catch (error) {+ toast.error(t("task.deleteFailed" as any));+ }+ };++ /** 处理评分更新 */+ const handleRatingUpdate = async (+ taskId: string,+ data: { rating?: number | null; comment?: string | null }+ ) => {+ // 这里可以更新本地状态,或者让父组件处理+ // 由于父组件有自己的状态管理,我们通过 onRefresh 来更新+ if (onRefresh) {+ await onRefresh();+ }+ toast.success(t("rating.saveSuccess" as any) || "Saved");+ };return (- <div className={cn("grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4", className)}>+ <div+ className={cn(+ "grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4",+ className+ )}+ >{isLoading? Array.from({ length: skeletonCount }).map((_, index) => (<TaskCardSkeleton key={index} />@@ -39,30 +83,41 @@ export const TaskHistoryList = ({const card = (<TaskCardid={String(task.id)}- title={task.title ?? ''}+ title={task.title ?? ""}status={task.status}createdAt={task.createdAt}updatedAt={task.updatedAt}- onDelete={onDelete}- onRateClick={onRateClick}+ rating={task.rating}+ onDelete={() => handleDelete(String(task.id))}+ onRateClick={() => handleRateClick(task.id)}/>- )+ );if (linkBasePath) {- const href = (`${linkBasePath}/${task.id}`) as string+ const href = `${linkBasePath}/${task.id}` as string;return (<a key={task.id} href={href} className="block">{card}</a>- )+ );}- return <React.Fragment key={task.id}>{card}</React.Fragment>+ return <React.Fragment key={task.id}>{card}</React.Fragment>;})}- </div>- )-}--export default TaskHistoryList+ <RatingModal+ taskId={ratingModalFor ?? ""}+ open={!!ratingModalFor}+ onClose={() => setRatingModalFor(null)}+ onSaved={(data) => {+ if (ratingModalFor) {+ handleRatingUpdate(ratingModalFor, data);+ }+ setRatingModalFor(null);+ }}+ />+ </div>+ );+};+export default TaskHistoryList;diff --git a/project/web/src/components/Home/TaskPreview/index.tsx b/project/web/src/components/Home/TaskPreview/index.tsxindex 9e36f476..43d71810 100644--- a/project/web/src/components/Home/TaskPreview/index.tsx+++ b/project/web/src/components/Home/TaskPreview/index.tsx@@ -3,126 +3,95 @@* 功能:显示最近的任务卡片列表,支持"浏览全部"跳转*/-'use client'+"use client";-import { useCallback, useEffect, useState } from 'react'-import { useRouter, useParams } from 'next/navigation'-import { ArrowRight, History } from 'lucide-react'-import { TaskCard, TaskCardSkeleton } from '@/components/Chat'-import { agentApi, type TaskListItem } from '@/api/agent'-import { useTransClient } from '@/app/i18n/client'-import { toast } from '@/lib/toast'-import { cn } from '@/lib/utils'+import { useCallback, useEffect, useState } from "react";+import { useRouter, useParams } from "next/navigation";+import { ArrowRight, History } from "lucide-react";+import TaskHistoryList from "@/components/Chat/TaskHistoryList";+import { agentApi, type TaskListItem } from "@/api/agent";+import { useTransClient } from "@/app/i18n/client";+import { cn } from "@/lib/utils";export interface ITaskPreviewProps {/** 显示数量 */- limit?: number+ limit?: number;/** 自定义类名 */- className?: string+ className?: string;}/*** TaskPreview - 任务预览组件*/export function TaskPreview({ limit = 4, className }: ITaskPreviewProps) {- const { t } = useTransClient('chat')- const router = useRouter()- const { lng } = useParams()+ const { t } = useTransClient("chat");+ const router = useRouter();+ const { lng } = useParams();- const [tasks, setTasks] = useState<TaskListItem[]>([])- const [isLoading, setIsLoading] = useState(true)+ const [tasks, setTasks] = useState<TaskListItem[]>([]);+ const [isLoading, setIsLoading] = useState(true);/** 加载任务列表(始终保证尽量填满 limit 条) */const loadTasks = useCallback(async () => {- setIsLoading(true)+ setIsLoading(true);try {- const result = await agentApi.getTaskList(1, limit)+ const result = await agentApi.getTaskList(1, limit);if (result && result.code === 0 && result.data) {- setTasks(result.data.list || [])+ setTasks(result.data.list || []);}} catch (error) {- console.error('Load task list failed:', error)+ console.error("Load task list failed:", error);} finally {- setIsLoading(false)+ setIsLoading(false);}- }, [limit])+ }, [limit]);useEffect(() => {- void loadTasks()- }, [loadTasks])+ void loadTasks();+ }, [loadTasks]);- /** 处理删除任务 */- const handleDelete = async (id: string) => {- try {- const result = await agentApi.deleteTask(id)- if (result && result.code === 0) {- // 先本地移除,提升交互速度- setTasks((prev) => prev.filter((task) => task.id !== id))- // 再重新拉取列表,确保数量重新补足到 limit(如果后端还有数据)- void loadTasks()- toast.success(t('task.deleteSuccess' as any))- } else {- const msg = (result as any)?.msg as string | undefined- toast.error(msg || t('task.deleteFailed' as any))- }- } catch (error) {- toast.error(t('task.deleteFailed' as any))- }- }/** 跳转到任务记录页 */const handleViewAll = () => {- router.push(`/${lng}/tasks-history`)- }-+ router.push(`/${lng}/tasks-history`);+ };// 如果没有任务且非加载中,不显示该区域if (!isLoading && tasks.length === 0) {- return null+ return null;}return (<section className={className}><div className="w-full max-w-5xl mx-auto">- {/* 标题栏 */}- <div className="flex items-center justify-between mb-4">- <div className="flex items-center gap-2">- <History className="w-5 h-5 text-muted-foreground" />- <h3 className="text-base font-medium text-foreground">- {t('home.recentTasks' as any)}- </h3>+ {/* 标题栏 */}+ <div className="flex items-center justify-between mb-4">+ <div className="flex items-center gap-2">+ <History className="w-5 h-5 text-muted-foreground" />+ <h3 className="text-base font-medium text-foreground">+ {t("home.recentTasks" as any)}+ </h3>+ </div>+ <button+ onClick={handleViewAll}+ className="flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors cursor-pointer"+ >+ {t("home.viewAll" as any)}+ <ArrowRight className="w-4 h-4" />+ </button></div>- <button- onClick={handleViewAll}- className="flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors cursor-pointer"- >- {t('home.viewAll' as any)}- <ArrowRight className="w-4 h-4" />- </button>- </div>- {/* 任务卡片列表 */}- <div className="grid grid-cols-2 md:grid-cols-4 gap-4">- {isLoading- ? Array.from({ length: limit }).map((_, index) => (- <TaskCardSkeleton key={index} />- ))- : tasks.map((task) => (- <TaskCard- key={task.id}- id={task.id}- title={task.title || t('task.newChat' as any)}- status={task.status}- createdAt={task.createdAt}- updatedAt={task.updatedAt}- onDelete={handleDelete}- />- ))}- </div>+ {/* 任务卡片列表 */}+ <TaskHistoryList+ tasks={tasks}+ isLoading={isLoading}+ skeletonCount={limit}+ onRefresh={() => loadTasks()}+ className="grid-cols-2 md:grid-cols-4"+ /></div></section>- )+ );}-export default TaskPreview-+export default TaskPreview;diff --git a/project/web/src/components/ui/alert-dialog.tsx b/project/web/src/components/ui/alert-dialog.tsxindex 57760f2e..7c46341a 100644--- a/project/web/src/components/ui/alert-dialog.tsx+++ b/project/web/src/components/ui/alert-dialog.tsx@@ -65,7 +65,7 @@ const AlertDialogFooter = ({}: React.HTMLAttributes<HTMLDivElement>) => (<divclassName={cn(- "flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",+ "flex flex-col-reverse sm:flex-row sm:justify-end gap-2",className)}{...props}diff --git a/project/web/src/components/ui/dialog.tsx b/project/web/src/components/ui/dialog.tsxindex 79be5896..267bcc59 100644--- a/project/web/src/components/ui/dialog.tsx+++ b/project/web/src/components/ui/dialog.tsx@@ -96,7 +96,7 @@ const DialogFooter = ({}: React.HTMLAttributes<HTMLDivElement>) => (<divclassName={cn(- "flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",+ "flex flex-col-reverse sm:flex-row sm:justify-end gap-2",className)}{...props}diff --git a/project/web/src/middleware.ts b/project/web/src/middleware.tsindex 1cf1d409..0062d41c 100644--- a/project/web/src/middleware.ts+++ b/project/web/src/middleware.ts@@ -27,7 +27,6 @@ export function middleware(req: NextRequest) {'/sitemap-3.xml','/sitemap-4.xml','/sitemap',- '/chat','/healthz',"/js/xhs_sign_init.js","/js/xhs_web_sign.js",diff --git a/project/web/src/store/user.ts b/project/web/src/store/user.tsindex 6610d978..51508000 100644--- a/project/web/src/store/user.ts+++ b/project/web/src/store/user.ts@@ -56,6 +56,8 @@ export interface IUserStore {creditsBalance: number// Credits 余额加载状态creditsLoading: boolean+ // 侧边栏收起状态+ sidebarCollapsed: boolean}const state: IUserStore = {@@ -67,6 +69,7 @@ const state: IUserStore = {currentDatePickerType: PublishDatePickerType.DATE,creditsBalance: 0,creditsLoading: false,+ sidebarCollapsed: false,}const getState = (): IUserStore => {@@ -138,6 +141,11 @@ export const useUserStore = createPersistStore(set({ creditsBalance: balance })},+ // 设置侧边栏收起状态+ setSidebarCollapsed(collapsed: boolean) {+ set({ sidebarCollapsed: collapsed })+ },+// 清除登录状态clearLoginStatus: () => {set({ ...getState() });