Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

💄 style(task): polish schedule, artifacts, and task list UI (#14248)

Arvin Xu2654c4d31e3d
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 7b1c1bd5530..8b4eefb368f 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -474,7 +474,10 @@
"taskDetail.activities.fallback.topic": "started a topic",
"taskDetail.activitiesEmpty": "No activity yet",
"taskDetail.addSubtask": "Add sub-task",
+ "taskDetail.artifactSize": "{{value}} chars",
+ "taskDetail.artifacts": "Artifacts",
"taskDetail.blockedBy": "Blocked by {{id}}",
+ "taskDetail.cancelSchedule": "Cancel schedule",
"taskDetail.comment.cancel": "Cancel",
"taskDetail.comment.delete": "Delete",
"taskDetail.comment.deleteConfirm.content": "This comment will be permanently removed.",
@@ -489,7 +492,6 @@
"taskDetail.instruction": "Instruction",
"taskDetail.instructionPlaceholder": "Click to edit task instructions...",
"taskDetail.latestActivity.brief": "Brief: {{title}}",
- "taskDetail.latestActivity.briefOnly": "Brief",
"taskDetail.latestActivity.briefWithAction": "{{title}} - {{action}}",
"taskDetail.latestActivity.briefWithType": "Brief ({{type}}): {{title}}",
"taskDetail.latestActivity.briefWithTypeOnly": "Brief ({{type}})",
@@ -498,6 +500,7 @@
"taskDetail.latestActivity.untitledTopic": "Untitled topic",
"taskDetail.modelConfig": "Model Override",
"taskDetail.navigation": "Navigation",
+ "taskDetail.nextRunCountdown": "Next run in {{countdown}}",
"taskDetail.pauseTask": "Pause task",
"taskDetail.priority.high": "High",
"taskDetail.priority.low": "Low",
@@ -515,6 +518,7 @@
"taskDetail.status.failed": "Failed",
"taskDetail.status.paused": "Pending review",
"taskDetail.status.running": "In progress",
+ "taskDetail.status.scheduled": "Scheduled",
"taskDetail.stopTask": "Stop task",
"taskDetail.subIssueOf": "Sub-issue of",
"taskDetail.subtaskInstructionPlaceholder": "Describe the sub-task...",
@@ -569,23 +573,33 @@
"taskList.view.board": "Board",
"taskList.view.list": "List",
"taskList.viewAll": "View all",
+ "taskSchedule.advancedSettings": "Advanced settings",
"taskSchedule.clear": "Clear",
"taskSchedule.continuous": "Continuous",
"taskSchedule.enable": "Enable automation",
"taskSchedule.every": "Every",
"taskSchedule.frequency": "Frequency",
+ "taskSchedule.heading": "Automation",
"taskSchedule.hours": "Hours",
- "taskSchedule.interval": "Recurring",
- "taskSchedule.intervalTab": "Recurring",
+ "taskSchedule.intervalLabel": "Run interval",
+ "taskSchedule.intervalSuffix": "each time",
+ "taskSchedule.intervalTab": "Heartbeat",
"taskSchedule.maxExecutions": "Max runs",
+ "taskSchedule.maxExecutionsPlaceholder": "Unlimited",
"taskSchedule.minutes": "Minutes",
+ "taskSchedule.nextRun": "Next run",
+ "taskSchedule.nextRun.format": "MMM D HH:mm",
"taskSchedule.scheduleType.daily": "Daily",
"taskSchedule.scheduleType.hourly": "Hourly",
"taskSchedule.scheduleType.weekly": "Weekly",
"taskSchedule.scheduler": "Scheduler",
- "taskSchedule.schedulerNotReady": "Scheduler is coming soon. Use Recurring for now.",
- "taskSchedule.schedulerTab": "Scheduler",
- "taskSchedule.seconds": "Seconds",
+ "taskSchedule.schedulerTab": "Scheduled",
+ "taskSchedule.summary.daily": "Daily at {{time}}",
+ "taskSchedule.summary.disabled": "Automation is off",
+ "taskSchedule.summary.everyNHours": "Every {{count}} hours{{minute}}",
+ "taskSchedule.summary.heartbeat": "Runs every {{interval}}",
+ "taskSchedule.summary.hourly": "Every hour{{minute}}",
+ "taskSchedule.summary.weekly": "Every {{days}} at {{time}}",
"taskSchedule.tag.add": "Set schedule",
"taskSchedule.tag.every": "Every {{interval}}",
"taskSchedule.tag.heartbeat": "Heartbeat · {{every}}",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 0e86381596e..fc537202236 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -474,7 +474,10 @@
"taskDetail.activities.fallback.topic": "发起了主题",
"taskDetail.activitiesEmpty": "暂无活动记录",
"taskDetail.addSubtask": "添加子任务",
+ "taskDetail.artifactSize": "{{value}} 字符",
+ "taskDetail.artifacts": "产物",
"taskDetail.blockedBy": "被 {{id}} 阻塞",
+ "taskDetail.cancelSchedule": "取消定时",
"taskDetail.comment.cancel": "取消",
"taskDetail.comment.delete": "删除",
"taskDetail.comment.deleteConfirm.content": "此评论将被永久删除。",
@@ -489,7 +492,6 @@
"taskDetail.instruction": "任务说明",
"taskDetail.instructionPlaceholder": "点击编辑任务说明…",
"taskDetail.latestActivity.brief": "简要:{{title}}",
- "taskDetail.latestActivity.briefOnly": "简要",
"taskDetail.latestActivity.briefWithAction": "{{title}} - {{action}}",
"taskDetail.latestActivity.briefWithType": "简要({{type}}):{{title}}",
"taskDetail.latestActivity.briefWithTypeOnly": "简要({{type}})",
@@ -498,6 +500,7 @@
"taskDetail.latestActivity.untitledTopic": "未命名主题",
"taskDetail.modelConfig": "模型覆盖",
"taskDetail.navigation": "导航",
+ "taskDetail.nextRunCountdown": "{{countdown}} 后执行",
"taskDetail.pauseTask": "暂停任务",
"taskDetail.priority.high": "高",
"taskDetail.priority.low": "低",
@@ -515,6 +518,7 @@
"taskDetail.status.failed": "失败",
"taskDetail.status.paused": "待审阅",
"taskDetail.status.running": "进行中",
+ "taskDetail.status.scheduled": "已排期",
"taskDetail.stopTask": "停止任务",
"taskDetail.subIssueOf": "隶属于",
"taskDetail.subtaskInstructionPlaceholder": "描述这个子任务…",
@@ -569,23 +573,33 @@
"taskList.view.board": "看板",
"taskList.view.list": "列表",
"taskList.viewAll": "查看全部",
+ "taskSchedule.advancedSettings": "高级设置",
"taskSchedule.clear": "清除",
- "taskSchedule.continuous": "持续执行",
+ "taskSchedule.continuous": "持续运行",
"taskSchedule.enable": "启用自动化",
"taskSchedule.every": "每",
- "taskSchedule.frequency": "执行频率",
+ "taskSchedule.frequency": "运行频率",
+ "taskSchedule.heading": "自动化",
"taskSchedule.hours": "小时",
- "taskSchedule.interval": "循环任务",
- "taskSchedule.intervalTab": "循环任务",
- "taskSchedule.maxExecutions": "最大次数",
+ "taskSchedule.intervalLabel": "运行间隔",
+ "taskSchedule.intervalSuffix": "运行一次",
+ "taskSchedule.intervalTab": "心跳模式",
+ "taskSchedule.maxExecutions": "运行次数限制",
+ "taskSchedule.maxExecutionsPlaceholder": "无限制",
"taskSchedule.minutes": "分钟",
+ "taskSchedule.nextRun": "下次运行",
+ "taskSchedule.nextRun.format": "M月D日 HH:mm",
"taskSchedule.scheduleType.daily": "每日",
"taskSchedule.scheduleType.hourly": "每小时",
"taskSchedule.scheduleType.weekly": "每周",
"taskSchedule.scheduler": "定时任务",
- "taskSchedule.schedulerNotReady": "定时任务即将上线。暂时请使用“循环任务”。",
"taskSchedule.schedulerTab": "定时任务",
- "taskSchedule.seconds": "秒",
+ "taskSchedule.summary.daily": "每天 {{time}} 运行",
+ "taskSchedule.summary.disabled": "自动化未启用",
+ "taskSchedule.summary.everyNHours": "每 {{count}} 小时{{minute}}",
+ "taskSchedule.summary.heartbeat": "每 {{interval}} 运行一次",
+ "taskSchedule.summary.hourly": "每小时{{minute}}",
+ "taskSchedule.summary.weekly": "每周 {{days}} {{time}} 运行",
"taskSchedule.tag.add": "设置计划",
"taskSchedule.tag.every": "每 {{interval}}",
"taskSchedule.tag.heartbeat": "心跳 · {{every}}",
diff --git a/src/features/AgentTasks/AgentTaskDetail/PageDrawer/index.tsx b/src/features/AgentTasks/AgentTaskDetail/PageDrawer/index.tsx
new file mode 100644
index 00000000000..d7c3edc43b5
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskDetail/PageDrawer/index.tsx
@@ -0,0 +1,50 @@
+'use client';
+
+import { Drawer } from '@lobehub/ui';
+import { cssVar } from 'antd-style';
+import { memo } from 'react';
+
+import PageExplorer from '@/features/PageExplorer';
+import { useTaskStore } from '@/store/task';
+import { taskDetailSelectors } from '@/store/task/selectors';
+
+const PageDrawer = memo(() => {
+ const pageId = useTaskStore(taskDetailSelectors.activePageDrawerPageId);
+ const closePageDrawer = useTaskStore((s) => s.closePageDrawer);
+
+ const open = !!pageId;
+
+ return (
+ <Drawer
+ destroyOnHidden
+ containerMaxWidth={'auto'}
+ mask={false}
+ open={open}
+ placement={'right'}
+ push={false}
+ width={720}
+ styles={{
+ body: { padding: 0 },
+ bodyContent: { height: '100%' },
+ header: { display: 'none' },
+ wrapper: {
+ border: `1px solid ${cssVar.colorBorderSecondary}`,
+ borderRadius: 12,
+ bottom: 8,
+ boxShadow: '0 6px 24px 0 rgba(0, 0, 0, 0.08), 0 2px 6px 0 rgba(0, 0, 0, 0.04)',
+ height: 'auto',
+ overflow: 'hidden',
+ right: 8,
+ top: 8,
+ },
+ }}
+ onClose={closePageDrawer}
+ >
+ {open && pageId && <PageExplorer pageId={pageId} />}
+ </Drawer>
+ );
+});
+
+PageDrawer.displayName = 'PageDrawer';
+
+export default PageDrawer;
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskArtifacts.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskArtifacts.tsx
index a9ab0d1ca53..b2bc743d9a8 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskArtifacts.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskArtifacts.tsx
@@ -1,72 +1,74 @@
import type { TaskDetailWorkspaceNode } from '@lobechat/types';
import { Block, Flexbox, Icon, Tag, Text } from '@lobehub/ui';
-import { ConfigProvider, Tree } from 'antd';
-import type { DataNode } from 'antd/es/tree';
import { cssVar } from 'antd-style';
-import { ChevronDown, FileText, FolderClosed, Package } from 'lucide-react';
+import { Package } from 'lucide-react';
import { memo, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import FileIcon from '@/components/FileIcon';
import { useTaskStore } from '@/store/task';
import { taskDetailSelectors } from '@/store/task/selectors';
-import { styles } from '../shared/style';
+import AccordionArrowIcon from '../shared/AccordionArrowIcon';
-const formatSize = (size?: number | null): string | undefined => {
- if (size == null) return undefined;
- if (size < 1000) return `${size} chars`;
- return `${(size / 1000).toFixed(1)}k chars`;
-};
+const formatSizeValue = (size: number): string =>
+ size < 1000 ? String(size) : `${(size / 1000).toFixed(1)}k`;
-const ArtifactTitle = memo<{ node: TaskDetailWorkspaceNode }>(({ node }) => {
- const isFolder = (node.children?.length ?? 0) > 0;
- const sizeLabel = formatSize(node.size);
+const flattenWorkspace = (nodes: TaskDetailWorkspaceNode[]): TaskDetailWorkspaceNode[] =>
+ nodes.flatMap((node) => [
+ node,
+ ...(node.children?.length ? flattenWorkspace(node.children) : []),
+ ]);
+
+const ArtifactCard = memo<{ node: TaskDetailWorkspaceNode }>(({ node }) => {
+ const { t } = useTranslation('chat');
+ const openPageDrawer = useTaskStore((s) => s.openPageDrawer);
+ const title = node.title || 'Untitled';
+ const sizeLabel =
+ node.size == null
+ ? undefined
+ : t('taskDetail.artifactSize', { value: formatSizeValue(node.size) });
+ const fileName = title.includes('.') ? title : `${title}.md`;
return (
- <Flexbox
+ <Block
+ clickable
horizontal
align="center"
- gap={8}
- style={{ lineHeight: 1, minWidth: 0, overflow: 'hidden', width: '100%' }}
+ gap={12}
+ paddingBlock={12}
+ paddingInline={12}
+ variant="outlined"
+ onClick={() => openPageDrawer(node.documentId)}
>
- <Icon
- color={cssVar.colorTextDescription}
- icon={isFolder ? FolderClosed : FileText}
- size={14}
- style={{ flex: 'none' }}
- />
- <Text ellipsis fontSize={13} style={{ flex: 1, minWidth: 0 }}>
- {node.title || 'Untitled'}
- </Text>
- {sizeLabel && (
- <Text style={{ color: cssVar.colorTextQuaternary, flex: 'none', fontSize: 12 }}>
- {sizeLabel}
- </Text>
- )}
- {node.sourceTaskIdentifier && (
- <Tag size="small" style={{ flexShrink: 0 }}>
- {node.sourceTaskIdentifier}
- </Tag>
- )}
- </Flexbox>
+ <FileIcon fileName={fileName} size={32} />
+ <Flexbox flex={1} gap={2} style={{ minWidth: 0, overflow: 'hidden' }}>
+ <Text ellipsis>{title}</Text>
+ <Flexbox horizontal align="center" gap={6}>
+ {sizeLabel && (
+ <Text fontSize={12} type="secondary">
+ {sizeLabel}
+ </Text>
+ )}
+ {node.sourceTaskIdentifier && (
+ <Tag size="small" style={{ flexShrink: 0 }}>
+ {node.sourceTaskIdentifier}
+ </Tag>
+ )}
+ </Flexbox>
+ </Flexbox>
+ </Block>
);
});
-const toTreeData = (nodes: TaskDetailWorkspaceNode[]): DataNode[] =>
- nodes.map((node) => ({
- children: node.children?.length ? toTreeData(node.children) : undefined,
- key: node.documentId,
- title: <ArtifactTitle node={node} />,
- }));
-
const TaskArtifacts = memo(() => {
const { t } = useTranslation('chat');
const workspace = useTaskStore(taskDetailSelectors.activeTaskWorkspace);
const [isExpanded, setIsExpanded] = useState(true);
- const treeData = useMemo(() => toTreeData(workspace), [workspace]);
+ const items = useMemo(() => flattenWorkspace(workspace), [workspace]);
- if (workspace.length === 0) return null;
+ if (items.length === 0) return null;
return (
<Flexbox gap={8}>
@@ -86,30 +88,16 @@ const TaskArtifacts = memo(() => {
<Text color={cssVar.colorTextSecondary} fontSize={13} weight={500}>
{t('taskDetail.artifacts')}
</Text>
- <Tag size="small">{workspace.length}</Tag>
- <Icon
- color={cssVar.colorTextDescription}
- icon={ChevronDown}
- size={14}
- style={{
- transform: isExpanded ? 'rotate(0deg)' : 'rotate(-90deg)',
- transition: 'transform 200ms',
- }}
- />
+ <Tag size="small">{items.length}</Tag>
+ <AccordionArrowIcon isOpen={isExpanded} style={{ color: cssVar.colorTextDescription }} />
</Block>
</Flexbox>
{isExpanded && (
- <ConfigProvider theme={{ components: { Tree: { titleHeight: 32 } } }}>
- <Tree
- blockNode
- defaultExpandAll
- showLine
- className={styles.subtaskTree}
- selectable={false}
- switcherIcon={<Icon icon={ChevronDown} size={14} />}
- treeData={treeData}
- />
- </ConfigProvider>
+ <Flexbox gap={8} paddingInline={12}>
+ {items.map((node) => (
+ <ArtifactCard key={node.documentId} node={node} />
+ ))}
+ </Flexbox>
)}
</Flexbox>
);
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx
index 4bbe743e43c..a0ff76eed66 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx
@@ -11,6 +11,7 @@ import { useTaskStore } from '@/store/task';
import { taskDetailSelectors } from '@/store/task/selectors';
import Breadcrumb from '../shared/Breadcrumb';
+import PageDrawer from './PageDrawer';
import TaskActivities from './TaskActivities';
import TaskArtifacts from './TaskArtifacts';
import TaskDetailAssignee from './TaskDetailAssignee';
@@ -104,6 +105,7 @@ const TaskDetailPage = memo<TaskDetailPageProps>(({ agentId, taskId }) => {
</WideScreenContainer>
</Flexbox>
<TopicChatDrawer />
+ <PageDrawer />
</Flexbox>
);
});
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailRunPauseAction.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailRunPauseAction.tsx
index 1c4f989805d..f5a4d1ee39f 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailRunPauseAction.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailRunPauseAction.tsx
@@ -1,6 +1,6 @@
-import { Button } from '@lobehub/ui';
-import { PlayIcon, RotateCcwIcon } from 'lucide-react';
-import { memo, useCallback, useState } from 'react';
+import { Button, Flexbox, Text } from '@lobehub/ui';
+import { CalendarOffIcon, PlayIcon, RotateCcwIcon } from 'lucide-react';
+import { memo, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import StopLoadingIcon from '@/components/StopLoading';
@@ -9,20 +9,40 @@ import { builtinAgentSelectors } from '@/store/agent/selectors';
import { useTaskStore } from '@/store/task';
import { taskDetailSelectors } from '@/store/task/selectors';
+import { nextHeartbeatFiring, nextScheduleFiring } from './scheduler/helpers';
+
+const padTime = (n: number) => String(n).padStart(2, '0');
+
+const formatCountdown = (msRemaining: number): string => {
+ const totalSeconds = Math.max(0, Math.floor(msRemaining / 1000));
+ const hours = Math.floor(totalSeconds / 3600);
+ const minutes = Math.floor((totalSeconds % 3600) / 60);
+ const seconds = totalSeconds % 60;
+ if (hours > 0) return `${padTime(hours)}:${padTime(minutes)}:${padTime(seconds)}`;
+ return `${padTime(minutes)}:${padTime(seconds)}`;
+};
+
const TaskDetailRunPauseAction = memo(() => {
const { t } = useTranslation('chat');
const taskId = useTaskStore(taskDetailSelectors.activeTaskId);
const canRun = useTaskStore(taskDetailSelectors.canRunActiveTask);
const canPause = useTaskStore(taskDetailSelectors.canPauseActiveTask);
const status = useTaskStore(taskDetailSelectors.activeTaskStatus);
+ const detail = useTaskStore(taskDetailSelectors.activeTaskDetail);
+ const automationMode = useTaskStore(taskDetailSelectors.activeTaskAutomationMode);
+ const interval = useTaskStore(taskDetailSelectors.activeTaskPeriodicInterval);
+ const schedulePattern = useTaskStore(taskDetailSelectors.activeTaskSchedulePattern);
+ const scheduleTimezone = useTaskStore(taskDetailSelectors.activeTaskScheduleTimezone);
const assigneeAgentId = useTaskStore(taskDetailSelectors.activeTaskAgentId);
const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
const isRerun = status === 'completed';
const runTask = useTaskStore((s) => s.runTask);
const updateTask = useTaskStore((s) => s.updateTask);
const updateTaskStatus = useTaskStore((s) => s.updateTaskStatus);
+ const setAutomationMode = useTaskStore((s) => s.setAutomationMode);
const [isStarting, setIsStarting] = useState(false);
+ const [isCancellingSchedule, setIsCancellingSchedule] = useState(false);
const handleRunOrPause = useCallback(async () => {
if (!taskId) return;
@@ -51,6 +71,67 @@ const TaskDetailRunPauseAction = memo(() => {
updateTaskStatus,
]);
+ const handleCancelSchedule = useCallback(async () => {
+ if (!taskId) return;
+ setIsCancellingSchedule(true);
+ try {
+ await setAutomationMode(taskId, null);
+ if (status === 'scheduled') {
+ await updateTaskStatus(taskId, 'backlog');
+ }
+ } finally {
+ setIsCancellingSchedule(false);
+ }
+ }, [taskId, setAutomationMode, updateTaskStatus, status]);
+
+ const isScheduled = status === 'scheduled';
+
+ const [nowMs, setNowMs] = useState(() => Date.now());
+ useEffect(() => {
+ if (!isScheduled) return;
+ const id = setInterval(() => setNowMs(Date.now()), 1000);
+ return () => clearInterval(id);
+ }, [isScheduled]);
+
+ const countdownText = useMemo(() => {
+ if (!isScheduled) return null;
+ let next = null;
+ if (automationMode === 'heartbeat') {
+ next = nextHeartbeatFiring(detail?.heartbeat?.lastAt, interval);
+ } else if (automationMode === 'schedule' && schedulePattern) {
+ next = nextScheduleFiring(schedulePattern, scheduleTimezone);
+ }
+ if (!next) return null;
+ return formatCountdown(next.toDate().getTime() - nowMs);
+ }, [
+ isScheduled,
+ automationMode,
+ detail?.heartbeat?.lastAt,
+ interval,
+ schedulePattern,
+ scheduleTimezone,
+ nowMs,
+ ]);
+
+ if (isScheduled) {
+ return (
+ <Flexbox horizontal align={'center'} gap={12}>
+ <Button
+ icon={CalendarOffIcon}
+ loading={isCancellingSchedule}
+ onClick={handleCancelSchedule}
+ >
+ {t('taskDetail.cancelSchedule')}
+ </Button>
+ {countdownText && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('taskDetail.nextRunCountdown', { countdown: countdownText })}
+ </Text>
+ )}
+ </Flexbox>
+ );
+ }
+
if (!canRun && !canPause && !isStarting) return null;
if (isStarting) {
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskScheduleConfig.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskScheduleConfig.tsx
index 58d36df864b..dfbb1b5b004 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskScheduleConfig.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskScheduleConfig.tsx
@@ -1,8 +1,9 @@
import type { TaskAutomationMode } from '@lobechat/types';
import {
ActionIcon,
- Button,
+ Avatar,
Flexbox,
+ Icon,
InputNumber,
Popover,
Segmented,
@@ -10,7 +11,9 @@ import {
Text,
} from '@lobehub/ui';
import { Switch } from 'antd';
-import { TimerIcon } from 'lucide-react';
+import { createStaticStyles, cssVar } from 'antd-style';
+import dayjs from 'dayjs';
+import { CalendarDays, Clock, RefreshCw, TimerIcon, Zap } from 'lucide-react';
import type { ReactNode } from 'react';
import { memo, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -18,9 +21,36 @@ import { useTranslation } from 'react-i18next';
import { useTaskStore } from '@/store/task';
import { taskDetailSelectors } from '@/store/task/selectors';
+import {
+ formatIntervalLabel,
+ formatScheduleDescription,
+ formatTimezoneName,
+ nextHeartbeatFiring,
+ nextScheduleFiring,
+} from './scheduler/helpers';
import SchedulerForm, { type SchedulerFormChange } from './scheduler/SchedulerForm';
-type IntervalUnit = 'hours' | 'minutes' | 'seconds';
+type IntervalUnit = 'hours' | 'minutes';
+
+const MIN_MINUTES = 10;
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ fieldLabel: css`
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+ `,
+ popover: css`
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 12px;
+ background: ${cssVar.colorBgContainer};
+ `,
+ preview: css`
+ padding-block: 12px;
+ padding-inline: 14px;
+ border-radius: 12px;
+ background: ${cssVar.colorFillQuaternary};
+ `,
+}));
interface IntervalTabProps {
currentInterval: number;
@@ -33,12 +63,13 @@ const IntervalTab = memo<IntervalTabProps>(({ currentInterval, taskId }) => {
const derived = useMemo(() => {
if (!currentInterval || currentInterval === 0)
- return { displayValue: undefined, unit: 'minutes' as IntervalUnit };
+ return { displayValue: MIN_MINUTES, unit: 'minutes' as IntervalUnit };
if (currentInterval >= 3600 && currentInterval % 3600 === 0)
return { displayValue: currentInterval / 3600, unit: 'hours' as IntervalUnit };
- if (currentInterval >= 60 && currentInterval % 60 === 0)
- return { displayValue: currentInterval / 60, unit: 'minutes' as IntervalUnit };
- return { displayValue: currentInterval, unit: 'seconds' as IntervalUnit };
+ return {
+ displayValue: Math.max(MIN_MINUTES, Math.round(currentInterval / 60)),
+ unit: 'minutes' as IntervalUnit,
+ };
}, [currentInterval]);
const [localUnit, setLocalUnit] = useState<IntervalUnit>(derived.unit);
@@ -51,17 +82,7 @@ const IntervalTab = memo<IntervalTabProps>(({ currentInterval, taskId }) => {
const toSeconds = (val: number | null, u: IntervalUnit): number | null => {
if (!val || val <= 0) return null;
- switch (u) {
- case 'hours': {
- return val * 3600;
- }
- case 'minutes': {
- return val * 60;
- }
- default: {
- return val;
- }
- }
+ return u === 'hours' ? val * 3600 : val * 60;
};
const handleValueChange = useCallback(
@@ -87,44 +108,40 @@ const IntervalTab = memo<IntervalTabProps>(({ currentInterval, taskId }) => {
(u: IntervalUnit) => {
setLocalUnit(u);
if (!taskId || !localValue) return;
- const seconds = toSeconds(localValue, u);
+ const clamped = u === 'minutes' ? Math.max(MIN_MINUTES, localValue) : localValue;
+ if (clamped !== localValue) setLocalValue(clamped);
+ const seconds = toSeconds(clamped, u);
updatePeriodicInterval(taskId, seconds);
},
[taskId, localValue, updatePeriodicInterval],
);
- const handleClear = useCallback(() => {
- setLocalValue(undefined);
- if (taskId) updatePeriodicInterval(taskId, null);
- }, [taskId, updatePeriodicInterval]);
-
return (
- <>
- <Flexbox horizontal align="center" gap={16} justify={'space-between'}>
- <Text weight={500}>{t('taskSchedule.every')}</Text>
- <Flexbox horizontal align="center" gap={8}>
- <InputNumber
- min={1}
- placeholder="10"
- style={{ width: 100 }}
- value={localValue}
- onChange={handleValueChange}
- />
- <Select
- style={{ width: 110 }}
- value={localUnit}
- variant="outlined"
- options={[
- { label: t('taskSchedule.seconds'), value: 'seconds' },
- { label: t('taskSchedule.minutes'), value: 'minutes' },
- { label: t('taskSchedule.hours'), value: 'hours' },
- ]}
- onChange={handleUnitChange}
- />
- </Flexbox>
+ <Flexbox gap={6}>
+ <Text className={styles.fieldLabel}>{t('taskSchedule.intervalLabel')}</Text>
+ <Flexbox horizontal align="center" gap={8}>
+ <Text type="secondary">{t('taskSchedule.every')}</Text>
+ <InputNumber
+ min={localUnit === 'minutes' ? MIN_MINUTES : 1}
+ placeholder={localUnit === 'minutes' ? String(MIN_MINUTES) : '1'}
+ style={{ width: 100 }}
+ value={localValue}
+ variant="filled"
+ onChange={handleValueChange}
+ />
+ <Select
+ style={{ flex: 1 }}
+ value={localUnit}
+ variant="filled"
+ options={[
+ { label: t('taskSchedule.minutes'), value: 'minutes' },
+ { label: t('taskSchedule.hours'), value: 'hours' },
+ ]}
+ onChange={handleUnitChange}
+ />
+ <Text type="secondary">{t('taskSchedule.intervalSuffix')}</Text>
</Flexbox>
- {currentInterval > 0 && <Button onClick={handleClear}>{t('taskSchedule.clear')}</Button>}
- </>
+ </Flexbox>
);
});
@@ -167,21 +184,76 @@ const TaskScheduleConfig = memo(function TaskScheduleConfig({
currentInterval,
taskId,
}: TaskScheduleConfigProps) {
- const { t } = useTranslation('chat');
+ const { t, i18n } = useTranslation('chat');
const activeTaskId = useTaskStore(taskDetailSelectors.activeTaskId);
const activeTaskInterval = useTaskStore(taskDetailSelectors.activeTaskPeriodicInterval);
const automationMode = useTaskStore(taskDetailSelectors.activeTaskAutomationMode);
const setAutomationMode = useTaskStore((s) => s.setAutomationMode);
+ const detail = useTaskStore(taskDetailSelectors.activeTaskDetail);
+ const schedulePattern = useTaskStore(taskDetailSelectors.activeTaskSchedulePattern);
+ const scheduleTimezone = useTaskStore(taskDetailSelectors.activeTaskScheduleTimezone);
+
const finalTaskId = taskId ?? activeTaskId;
const finalCurrentInterval = currentInterval ?? activeTaskInterval;
const enabled = !!automationMode;
+ const summary = useMemo<{ primary: string; secondary?: string } | null>(() => {
+ if (automationMode === 'heartbeat' && finalCurrentInterval > 0) {
+ return {
+ primary: t('taskSchedule.summary.heartbeat', {
+ interval: formatIntervalLabel(finalCurrentInterval, t),
+ }),
+ };
+ }
+ if (automationMode === 'schedule' && schedulePattern) {
+ return {
+ primary: formatScheduleDescription(schedulePattern, t),
+ secondary: scheduleTimezone
+ ? formatTimezoneName(scheduleTimezone, i18n.language)
+ : undefined,
+ };
+ }
+ return null;
+ }, [automationMode, finalCurrentInterval, schedulePattern, scheduleTimezone, t, i18n.language]);
+
+ const [nowTick, setNowTick] = useState(0);
+ useEffect(() => {
+ if (!enabled) return;
+ const id = setInterval(() => setNowTick((n) => n + 1), 60_000);
+ return () => clearInterval(id);
+ }, [enabled]);
+
+ const nextRun = useMemo(() => {
+ if (!enabled) return null;
+ if (automationMode === 'heartbeat') {
+ return nextHeartbeatFiring(detail?.heartbeat?.lastAt, finalCurrentInterval);
+ }
+ if (automationMode === 'schedule' && schedulePattern) {
+ return nextScheduleFiring(schedulePattern, scheduleTimezone);
+ }
+ return null;
+ }, [
+ automationMode,
+ detail?.heartbeat?.lastAt,
+ enabled,
+ finalCurrentInterval,
+ schedulePattern,
+ scheduleTimezone,
+ nowTick,
+ ]);
+
+ const nextRunText = useMemo(() => {
+ if (!nextRun) return null;
+ return dayjs(nextRun.toDate()).format(t('taskSchedule.nextRun.format'));
+ }, [nextRun, t]);
+
const handleEnableChange = useCallback(
(checked: boolean) => {
if (!finalTaskId) return;
- // When enabling, default to heartbeat (the more common mode)
- setAutomationMode(finalTaskId, checked ? 'heartbeat' : null);
+ // Schedule (cron) is the more common, predictable choice; users who want
+ // a fixed interval can switch to the heartbeat tab from there.
+ setAutomationMode(finalTaskId, checked ? 'schedule' : null);
},
[finalTaskId, setAutomationMode],
);
@@ -195,19 +267,62 @@ const TaskScheduleConfig = memo(function TaskScheduleConfig({
);
const content = (
- <Flexbox gap={16} style={{ padding: 8, width: 420 }} onClick={(e) => e.stopPropagation()}>
- <Flexbox horizontal align="center" gap={8}>
- <Text weight={500}>{t('taskSchedule.enable')}</Text>
+ <Flexbox gap={16} style={{ padding: 4, width: 440 }} onClick={(e) => e.stopPropagation()}>
+ <Flexbox horizontal align="center" gap={12}>
+ <Avatar
+ avatar={<Icon color={cssVar.colorSuccess} icon={Zap} size={20} />}
+ background={cssVar.colorSuccessBg}
+ shape="square"
+ size={40}
+ />
+ <Flexbox flex={1} gap={2}>
+ <Text weight={500}>{t('taskSchedule.heading')}</Text>
+ <Text style={{ color: cssVar.colorTextSecondary, fontSize: 12 }}>
+ {summary?.primary ?? t('taskSchedule.summary.disabled')}
+ </Text>
+ {summary?.secondary && (
+ <Text style={{ color: cssVar.colorTextDescription, fontSize: 11 }}>
+ {summary.secondary}
+ </Text>
+ )}
+ </Flexbox>
<Switch checked={enabled} onChange={handleEnableChange} />
</Flexbox>
+
+ {enabled && nextRunText && (
+ <Flexbox horizontal align="center" className={styles.preview} gap={10}>
+ <Icon color={cssVar.colorTextDescription} icon={Clock} size={16} />
+ <Text style={{ color: cssVar.colorTextSecondary }}>{t('taskSchedule.nextRun')}</Text>
+ <Text style={{ flex: 1, textAlign: 'right' }} weight={500}>
+ {nextRunText}
+ </Text>
+ </Flexbox>
+ )}
+
{enabled && (
<>
<Segmented
block
value={automationMode ?? 'heartbeat'}
options={[
- { label: t('taskSchedule.schedulerTab'), value: 'schedule' },
- { label: t('taskSchedule.intervalTab'), value: 'heartbeat' },
+ {
+ label: (
+ <Flexbox horizontal align="center" gap={6} justify="center">
+ <Icon icon={CalendarDays} size={14} />
+ <span>{t('taskSchedule.schedulerTab')}</span>
+ </Flexbox>
+ ),
+ value: 'schedule',
+ },
+ {
+ label: (
+ <Flexbox horizontal align="center" gap={6} justify="center">
+ <Icon icon={RefreshCw} size={14} />
+ <span>{t('taskSchedule.intervalTab')}</span>
+ </Flexbox>
+ ),
+ value: 'heartbeat',
+ },
]}
onChange={handleModeChange}
/>
@@ -221,7 +336,7 @@ const TaskScheduleConfig = memo(function TaskScheduleConfig({
);
return (
- <Popover content={content} placement="bottomRight" trigger="click">
+ <Popover className={styles.popover} content={content} placement="bottomRight" trigger="click">
{children ? (
<div onClick={(e) => e.stopPropagation()}>{children}</div>
) : (
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx
index f68cb3564ff..dcf72dff153 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx
@@ -19,6 +19,7 @@ import TaskStatusTag from '../features/TaskStatusTag';
import TaskSubtaskProgressTag from '../features/TaskSubtaskProgressTag';
import TaskTriggerTag from '../features/TaskTriggerTag';
import { useTaskItemContextMenu } from '../features/useTaskItemContextMenu';
+import AccordionArrowIcon from '../shared/AccordionArrowIcon';
import { styles } from '../shared/style';
type TaskStatus = 'backlog' | 'canceled' | 'completed' | 'failed' | 'paused' | 'running';
@@ -197,14 +198,9 @@ const TaskSubtasks = memo(() => {
<Text color={cssVar.colorTextSecondary} fontSize={13} weight={500}>
{t('taskDetail.subtasks')}
</Text>
- <Icon
- color={cssVar.colorTextDescription}
- icon={ChevronDown}
- size={14}
- style={{
- transform: isExpanded ? 'rotate(0deg)' : 'rotate(-90deg)',
- transition: 'transform 200ms',
- }}
+ <AccordionArrowIcon
+ isOpen={isExpanded}
+ style={{ color: cssVar.colorTextDescription }}
/>
</Block>
<TaskSubtaskProgressTag
diff --git a/src/features/AgentTasks/AgentTaskDetail/scheduler/SchedulerForm.tsx b/src/features/AgentTasks/AgentTaskDetail/scheduler/SchedulerForm.tsx
index 0157f3b9dd4..7e17b347fcf 100644
--- a/src/features/AgentTasks/AgentTaskDetail/scheduler/SchedulerForm.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/scheduler/SchedulerForm.tsx
@@ -1,7 +1,17 @@
-import { Checkbox, Flexbox, InputNumber, Select, Text } from '@lobehub/ui';
+import {
+ Accordion,
+ AccordionItem,
+ Checkbox,
+ Flexbox,
+ Icon,
+ InputNumber,
+ Select,
+ Text,
+} from '@lobehub/ui';
import { TimePicker } from 'antd';
-import { createStaticStyles, cx } from 'antd-style';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
import dayjs, { type Dayjs } from 'dayjs';
+import { Globe, Hash, SlidersHorizontal } from 'lucide-react';
import { memo, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -15,9 +25,8 @@ import {
} from './CronConfig';
const styles = createStaticStyles(({ css, cssVar }) => ({
- label: css`
- flex-shrink: 0;
- width: 80px;
+ fieldLabel: css`
+ font-size: 12px;
color: ${cssVar.colorTextSecondary};
`,
weekdayButton: css`
@@ -29,31 +38,28 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
width: 36px;
height: 32px;
- border: 1px solid ${cssVar.colorBorder};
border-radius: 6px;
font-size: 12px;
font-weight: 500;
color: ${cssVar.colorTextSecondary};
- background: transparent;
+ background: ${cssVar.colorFillTertiary};
transition: all 0.15s ease;
&:hover {
- border-color: ${cssVar.colorPrimary};
- color: ${cssVar.colorPrimary};
+ color: ${cssVar.colorText};
+ background: ${cssVar.colorFillSecondary};
}
`,
weekdayButtonActive: css`
- border-color: ${cssVar.colorPrimary};
- color: ${cssVar.colorTextLightSolid};
- background: ${cssVar.colorPrimary};
+ color: ${cssVar.colorPrimary};
+ background: ${cssVar.colorPrimaryBg};
&:hover {
- border-color: ${cssVar.colorPrimaryHover};
- color: ${cssVar.colorTextLightSolid};
- background: ${cssVar.colorPrimaryHover};
+ color: ${cssVar.colorPrimary};
+ background: ${cssVar.colorPrimaryBgHover};
}
`,
}));
@@ -189,66 +195,69 @@ const SchedulerForm = memo<SchedulerFormProps>(({ maxExecutions, onChange, patte
const isUnlimited = maxExec === null || maxExec === undefined;
- return (
- <Flexbox gap={14} paddingBlock={4}>
- <Flexbox horizontal align="center" gap={12} justify="space-between">
- <Text className={styles.label}>{t('taskSchedule.frequency')}</Text>
- <Select
- style={{ width: 200 }}
- value={scheduleType}
- variant="outlined"
- options={SCHEDULE_TYPE_OPTIONS.map((opt) => ({
- label: t(opt.label as any),
- value: opt.value,
- }))}
- onChange={handleScheduleTypeChange}
- />
- </Flexbox>
+ const showTimeRow = scheduleType !== 'hourly';
- {scheduleType !== 'hourly' && (
- <Flexbox horizontal align="center" gap={12} justify="space-between">
- <Text className={styles.label}>{t('taskSchedule.time')}</Text>
- <TimePicker
- format="HH:mm"
- minuteStep={15}
- style={{ width: 200 }}
- value={triggerTime}
- onChange={handleTimeChange}
+ return (
+ <Flexbox gap={16}>
+ <Flexbox horizontal gap={12}>
+ <Flexbox flex={1} gap={6}>
+ <Text className={styles.fieldLabel}>{t('taskSchedule.frequency')}</Text>
+ <Select
+ value={scheduleType}
+ variant="filled"
+ options={SCHEDULE_TYPE_OPTIONS.map((opt) => ({
+ label: t(opt.label as any),
+ value: opt.value,
+ }))}
+ onChange={handleScheduleTypeChange}
/>
</Flexbox>
- )}
-
- {scheduleType === 'hourly' && (
- <Flexbox horizontal align="center" gap={12} justify="space-between">
- <Text className={styles.label}>{t('taskSchedule.every')}</Text>
- <Flexbox horizontal align="center" gap={8}>
- <InputNumber
- max={24}
- min={1}
- style={{ width: 70 }}
- value={hourlyInterval}
- onChange={handleHourlyIntervalChange}
- />
- <Text type="secondary">{t('taskSchedule.hours')}</Text>
- <Select
- style={{ width: 80 }}
- value={triggerTime.minute()}
- variant="outlined"
- options={[
- { label: ':00', value: 0 },
- { label: ':15', value: 15 },
- { label: ':30', value: 30 },
- { label: ':45', value: 45 },
- ]}
- onChange={handleHourlyMinuteChange}
+ {showTimeRow && (
+ <Flexbox flex={1} gap={6}>
+ <Text className={styles.fieldLabel}>{t('taskSchedule.time')}</Text>
+ <TimePicker
+ format="HH:mm"
+ minuteStep={15}
+ style={{ width: '100%' }}
+ value={triggerTime}
+ variant="filled"
+ onChange={handleTimeChange}
/>
</Flexbox>
- </Flexbox>
- )}
+ )}
+ {scheduleType === 'hourly' && (
+ <Flexbox flex={1} gap={6}>
+ <Text className={styles.fieldLabel}>{t('taskSchedule.every')}</Text>
+ <Flexbox horizontal align="center" gap={6}>
+ <InputNumber
+ max={24}
+ min={1}
+ style={{ flex: 1 }}
+ value={hourlyInterval}
+ variant="filled"
+ onChange={handleHourlyIntervalChange}
+ />
+ <Text type="secondary">{t('taskSchedule.hours')}</Text>
+ <Select
+ style={{ width: 80 }}
+ value={triggerTime.minute()}
+ variant="filled"
+ options={[
+ { label: ':00', value: 0 },
+ { label: ':15', value: 15 },
+ { label: ':30', value: 30 },
+ { label: ':45', value: 45 },
+ ]}
+ onChange={handleHourlyMinuteChange}
+ />
+ </Flexbox>
+ </Flexbox>
+ )}
+ </Flexbox>
{scheduleType === 'weekly' && (
- <Flexbox horizontal align="center" gap={12} justify="space-between">
- <Text className={styles.label}>{t('taskSchedule.weekday')}</Text>
+ <Flexbox gap={6}>
+ <Text className={styles.fieldLabel}>{t('taskSchedule.weekday')}</Text>
<Flexbox horizontal gap={6}>
{WEEKDAYS.map(({ key, label }) => (
<div
@@ -266,35 +275,59 @@ const SchedulerForm = memo<SchedulerFormProps>(({ maxExecutions, onChange, patte
</Flexbox>
)}
- <Flexbox horizontal align="center" gap={12} justify="space-between">
- <Text className={styles.label}>{t('taskSchedule.timezone')}</Text>
- <Select
- showSearch
- options={TIMEZONE_OPTIONS}
- popupMatchSelectWidth={false}
- style={{ width: 280 }}
- value={tz}
- variant="outlined"
- onChange={handleTimezoneChange}
- />
- </Flexbox>
-
- <Flexbox horizontal align="center" gap={12} justify="space-between">
- <Text className={styles.label}>{t('taskSchedule.maxExecutions')}</Text>
- <Flexbox horizontal align="center" gap={10}>
- <InputNumber
- disabled={isUnlimited}
- min={1}
- placeholder="100"
- style={{ width: 90 }}
- value={maxExec ?? undefined}
- onChange={handleMaxExecChange}
- />
- <Checkbox checked={isUnlimited} onChange={handleContinuousChange}>
- {t('taskSchedule.continuous')}
- </Checkbox>
- </Flexbox>
- </Flexbox>
+ <Accordion gap={0}>
+ <AccordionItem
+ itemKey="advanced"
+ paddingBlock={6}
+ paddingInline={0}
+ title={
+ <Flexbox horizontal align="center" gap={8}>
+ <Icon color={cssVar.colorTextDescription} icon={SlidersHorizontal} size={14} />
+ <Text style={{ color: cssVar.colorTextSecondary }}>
+ {t('taskSchedule.advancedSettings')}
+ </Text>
+ </Flexbox>
+ }
+ >
+ <Flexbox gap={14} paddingBlock={'8px 4px'}>
+ <Flexbox gap={6}>
+ <Flexbox horizontal align="center" gap={6}>
+ <Icon color={cssVar.colorTextDescription} icon={Globe} size={14} />
+ <Text className={styles.fieldLabel}>{t('taskSchedule.timezone')}</Text>
+ </Flexbox>
+ <Select
+ showSearch
+ options={TIMEZONE_OPTIONS}
+ popupMatchSelectWidth={false}
+ value={tz}
+ variant="filled"
+ onChange={handleTimezoneChange}
+ />
+ </Flexbox>
+
+ <Flexbox gap={6}>
+ <Flexbox horizontal align="center" gap={6}>
+ <Icon color={cssVar.colorTextDescription} icon={Hash} size={14} />
+ <Text className={styles.fieldLabel}>{t('taskSchedule.maxExecutions')}</Text>
+ </Flexbox>
+ <Flexbox horizontal align="center" gap={12}>
+ <InputNumber
+ disabled={isUnlimited}
+ min={1}
+ placeholder={t('taskSchedule.maxExecutionsPlaceholder')}
+ style={{ flex: 1 }}
+ value={maxExec ?? undefined}
+ variant="filled"
+ onChange={handleMaxExecChange}
+ />
+ <Checkbox checked={isUnlimited} onChange={handleContinuousChange}>
+ {t('taskSchedule.continuous')}
+ </Checkbox>
+ </Flexbox>
+ </Flexbox>
+ </Flexbox>
+ </AccordionItem>
+ </Accordion>
</Flexbox>
);
});
diff --git a/src/features/AgentTasks/AgentTaskDetail/scheduler/helpers.ts b/src/features/AgentTasks/AgentTaskDetail/scheduler/helpers.ts
new file mode 100644
index 00000000000..ac0555d2f32
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskDetail/scheduler/helpers.ts
@@ -0,0 +1,163 @@
+import dayjs, { type Dayjs } from 'dayjs';
+import timezone from 'dayjs/plugin/timezone';
+import utc from 'dayjs/plugin/utc';
+import type { TFunction } from 'i18next';
+
+import { parseCronPattern, type ScheduleType, WEEKDAYS } from './CronConfig';
+
+dayjs.extend(utc);
+dayjs.extend(timezone);
+
+const padTime = (n: number) => String(n).padStart(2, '0');
+
+const formatHHmm = (hour: number, minute: number) => `${padTime(hour)}:${padTime(minute)}`;
+
+/**
+ * Pretty interval like "10 min" / "2 hr" / "30 sec".
+ * Reuses the same `taskSchedule.unit.*` plural keys as TaskTriggerTag.
+ */
+export const formatIntervalLabel = (seconds: number, t: TFunction<'chat'>): string => {
+ if (seconds <= 0) return '';
+ if (seconds % 3600 === 0) return t('taskSchedule.unit.hour', { count: seconds / 3600 });
+ if (seconds % 60 === 0) return t('taskSchedule.unit.minute', { count: seconds / 60 });
+ return t('taskSchedule.unit.second', { count: seconds });
+};
+
+/**
+ * Localized timezone display name (e.g. "中国标准时间", "Pacific Daylight Time").
+ * Falls back to the IANA id when the runtime can't resolve a long name.
+ */
+export const formatTimezoneName = (tz: string, locale: string): string => {
+ try {
+ const parts = new Intl.DateTimeFormat(locale, {
+ timeZone: tz,
+ timeZoneName: 'long',
+ }).formatToParts(new Date());
+ return parts.find((p) => p.type === 'timeZoneName')?.value ?? tz;
+ } catch {
+ return tz;
+ }
+};
+
+/**
+ * Human description of a cron pattern like "每天 09:00" or "Every 2 hours :30".
+ */
+export const formatScheduleDescription = (pattern: string, t: TFunction<'chat'>): string => {
+ const parsed = parseCronPattern(pattern);
+ switch (parsed.scheduleType) {
+ case 'hourly': {
+ const interval = parsed.hourlyInterval ?? 1;
+ const minute = `:${padTime(parsed.triggerMinute)}`;
+ return interval === 1
+ ? t('taskSchedule.summary.hourly', { minute })
+ : t('taskSchedule.summary.everyNHours', { count: interval, minute });
+ }
+ case 'daily': {
+ return t('taskSchedule.summary.daily', {
+ time: formatHHmm(parsed.triggerHour, parsed.triggerMinute),
+ });
+ }
+ case 'weekly': {
+ const days = parsed.weekdays ?? [];
+ const allDays = days.length === 7;
+ if (allDays) {
+ return t('taskSchedule.summary.daily', {
+ time: formatHHmm(parsed.triggerHour, parsed.triggerMinute),
+ });
+ }
+ const labels = [...days]
+ .sort((a, b) => a - b)
+ .map((d) => t(WEEKDAYS.find((w) => w.key === d)!.label as any))
+ .join('/');
+ return t('taskSchedule.summary.weekly', {
+ days: labels,
+ time: formatHHmm(parsed.triggerHour, parsed.triggerMinute),
+ });
+ }
+ }
+};
+
+/**
+ * Compute the next firing time for a parsed cron schedule, in the given timezone.
+ * Returns a Dayjs in `tz` so callers can format relative to user locale.
+ */
+const computeNextScheduleFiring = (
+ scheduleType: ScheduleType,
+ triggerHour: number,
+ triggerMinute: number,
+ hourlyInterval: number | undefined,
+ weekdays: number[] | undefined,
+ tz: string,
+): Dayjs => {
+ const now = dayjs().tz(tz);
+
+ switch (scheduleType) {
+ case 'hourly': {
+ const interval = hourlyInterval && hourlyInterval > 0 ? hourlyInterval : 1;
+ let candidate = now.minute(triggerMinute).second(0).millisecond(0);
+ if (!candidate.isAfter(now)) candidate = candidate.add(1, 'hour');
+ while (candidate.hour() % interval !== 0) {
+ candidate = candidate.add(1, 'hour');
+ }
+ return candidate;
+ }
+ case 'daily': {
+ let candidate = now.hour(triggerHour).minute(triggerMinute).second(0).millisecond(0);
+ if (!candidate.isAfter(now)) candidate = candidate.add(1, 'day');
+ return candidate;
+ }
+ case 'weekly': {
+ const days = weekdays && weekdays.length > 0 ? weekdays : [0, 1, 2, 3, 4, 5, 6];
+ for (let offset = 0; offset < 8; offset += 1) {
+ const candidate = now
+ .add(offset, 'day')
+ .hour(triggerHour)
+ .minute(triggerMinute)
+ .second(0)
+ .millisecond(0);
+ if (days.includes(candidate.day()) && candidate.isAfter(now)) return candidate;
+ }
+ return now.add(1, 'week');
+ }
+ }
+};
+
+/**
+ * Next firing time for a cron pattern in IANA timezone. Returns null if pattern is
+ * unparseable.
+ */
+export const nextScheduleFiring = (pattern: string, tz: string | null): Dayjs | null => {
+ const parsed = parseCronPattern(pattern);
+ const safeTz = tz || dayjs.tz.guess();
+ try {
+ return computeNextScheduleFiring(
+ parsed.scheduleType,
+ parsed.triggerHour,
+ parsed.triggerMinute,
+ parsed.hourlyInterval,
+ parsed.weekdays,
+ safeTz,
+ );
+ } catch {
+ return null;
+ }
+};
+
+/**
+ * Next heartbeat firing time strictly after now. Catches up by interval steps
+ * when `lastAt` is stale (e.g. task was paused for hours).
+ */
+export const nextHeartbeatFiring = (
+ lastAt: string | null | undefined,
+ intervalSeconds: number,
+): Dayjs | null => {
+ if (!intervalSeconds || intervalSeconds <= 0) return null;
+ const now = dayjs();
+ if (!lastAt) return now.add(intervalSeconds, 'second');
+ const base = dayjs(lastAt);
+ const next = base.add(intervalSeconds, 'second');
+ if (next.isAfter(now)) return next;
+ const intervalMs = intervalSeconds * 1000;
+ const steps = Math.floor(now.diff(base) / intervalMs) + 1;
+ return base.add(steps * intervalSeconds, 'second');
+};
diff --git a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
index 2701f5154f1..562e3447d1c 100644
--- a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
+++ b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
@@ -55,7 +55,7 @@ const AgentTasksPage = memo(() => {
left={<Breadcrumb />}
right={
<Flexbox horizontal align={'center'} gap={4}>
- {inlineCollapsed && (
+ {(inlineCollapsed || viewMode === 'kanban') && (
<ActionIcon icon={Plus} size={DESKTOP_HEADER_ICON_SIZE} onClick={handleCreateTask} />
)}
<TasksGroupConfig options={viewOptions} setOptions={setViewOptions} />
diff --git a/src/features/AgentTasks/AgentTaskList/listViewOptions.ts b/src/features/AgentTasks/AgentTaskList/listViewOptions.ts
index 6e436b49481..575464b32f5 100644
--- a/src/features/AgentTasks/AgentTaskList/listViewOptions.ts
+++ b/src/features/AgentTasks/AgentTaskList/listViewOptions.ts
@@ -89,11 +89,11 @@ const PRIORITY_RANK_MAP: Record<number, number> = {
};
const STATUS_GROUP_RANK_MAP: Record<NonNullable<TaskGroupMeta['status']>, number> = {
- backlog: 0,
- running: 1,
- paused: 2,
- completed: 3,
- failed: 4,
+ paused: 0,
+ failed: 1,
+ running: 2,
+ backlog: 3,
+ completed: 4,
canceled: 5,
};
@@ -104,6 +104,7 @@ const TASK_STATUS_TO_GROUP_MAP: Record<string, NonNullable<TaskGroupMeta['status
failed: 'failed',
paused: 'paused',
running: 'running',
+ scheduled: 'running',
};
const getPriorityValue = (task: TaskListItem) => task.priority ?? 0;
diff --git a/src/features/AgentTasks/features/AgentTaskItem.tsx b/src/features/AgentTasks/features/AgentTaskItem.tsx
index dfd4438d0f4..02f18b7edbc 100644
--- a/src/features/AgentTasks/features/AgentTaskItem.tsx
+++ b/src/features/AgentTasks/features/AgentTaskItem.tsx
@@ -1,3 +1,4 @@
+import type { TaskStatus } from '@lobechat/types';
import { Block, ContextMenuTrigger, Flexbox, Text } from '@lobehub/ui';
import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
@@ -22,22 +23,22 @@ interface TaskItemProps {
variant?: 'compact' | 'default';
}
-const TASK_STATUS_SET = new Set([
+const TASK_STATUS_SET = new Set<TaskStatus>([
'backlog',
'canceled',
'completed',
'failed',
'paused',
'running',
+ 'scheduled',
]);
-type TaskStatus = 'backlog' | 'canceled' | 'completed' | 'failed' | 'paused' | 'running';
-
const toTaskStatus = (status: string): TaskStatus =>
- TASK_STATUS_SET.has(status) ? (status as TaskStatus) : 'backlog';
+ TASK_STATUS_SET.has(status as TaskStatus) ? (status as TaskStatus) : 'backlog';
const AgentTaskItem = memo<TaskItemProps>(({ task, variant = 'default' }) => {
const { t } = useTranslation('discover');
+ const { t: tChat } = useTranslation('chat');
const useFetchTaskDetail = useTaskStore((s) => s.useFetchTaskDetail);
useFetchTaskDetail(task.identifier);
@@ -64,6 +65,23 @@ const AgentTaskItem = memo<TaskItemProps>(({ task, variant = 'default' }) => {
[navigate],
);
+ const scheduledBadge =
+ status === 'scheduled' ? (
+ <Block
+ horizontal
+ align={'center'}
+ flex={'none'}
+ height={20}
+ paddingInline={8}
+ style={{ borderRadius: 24 }}
+ variant={'outlined'}
+ >
+ <Text fontSize={12} type={'secondary'}>
+ {tChat('taskDetail.status.scheduled', { defaultValue: 'Scheduled' })}
+ </Text>
+ </Block>
+ ) : null;
+
const titleRow = (
<Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
<TaskPriorityTag priority={task.priority} taskIdentifier={task.identifier} />
@@ -82,6 +100,7 @@ const AgentTaskItem = memo<TaskItemProps>(({ task, variant = 'default' }) => {
{task.identifier}
</Text>
)}
+ {scheduledBadge}
<TaskSubtaskProgressTag
currentIdentifier={task.identifier}
subtasks={taskDetail?.subtasks}
@@ -139,6 +158,7 @@ const AgentTaskItem = memo<TaskItemProps>(({ task, variant = 'default' }) => {
<Text ellipsis style={{ minWidth: 0 }} weight={500}>
{hasName ? task.name : task.identifier}
</Text>
+ {scheduledBadge}
<TaskSubtaskProgressTag
currentIdentifier={task.identifier}
subtasks={taskDetail?.subtasks}
diff --git a/src/features/AgentTasks/features/TaskLatestActivity.tsx b/src/features/AgentTasks/features/TaskLatestActivity.tsx
index a784f7cf5c1..1e8a5495255 100644
--- a/src/features/AgentTasks/features/TaskLatestActivity.tsx
+++ b/src/features/AgentTasks/features/TaskLatestActivity.tsx
@@ -21,7 +21,7 @@ const getActivityText = (activity: TaskDetailActivity | undefined, t: TFunction<
if (!briefTitle) {
return activity.briefType
? t('taskDetail.latestActivity.briefWithTypeOnly', { type: activity.briefType })
- : t('taskDetail.latestActivity.briefOnly');
+ : undefined;
}
if (activity.resolvedAction) {
diff --git a/src/features/AgentTasks/features/TaskStatusIcon.tsx b/src/features/AgentTasks/features/TaskStatusIcon.tsx
index 8e9db4565d2..ae5cac5d376 100644
--- a/src/features/AgentTasks/features/TaskStatusIcon.tsx
+++ b/src/features/AgentTasks/features/TaskStatusIcon.tsx
@@ -27,7 +27,7 @@ const STATUS_META: Record<TaskStatus, StatusMeta> = {
failed: { color: cssVar.colorError, icon: CircleX },
paused: { color: cssVar.colorInfo, icon: HandIcon },
running: { color: cssVar.colorWarning, icon: CircleDot },
- scheduled: { color: cssVar.colorTextDescription, icon: Clock },
+ scheduled: { color: cssVar.colorWarning, icon: Clock },
};
interface TaskStatusIconProps {
diff --git a/src/features/AgentTasks/features/TaskStatusTag.tsx b/src/features/AgentTasks/features/TaskStatusTag.tsx
index ddf95d47876..6b05684b3b1 100644
--- a/src/features/AgentTasks/features/TaskStatusTag.tsx
+++ b/src/features/AgentTasks/features/TaskStatusTag.tsx
@@ -66,7 +66,7 @@ export const STATUS_META: Record<TaskStatus, StatusMeta> = {
labelKey: 'status.running',
},
scheduled: {
- color: cssVar.colorTextDescription,
+ color: cssVar.colorWarning,
icon: Clock,
label: 'Scheduled',
labelKey: 'status.scheduled',
diff --git a/src/features/AgentTasks/features/TaskTriggerTag.tsx b/src/features/AgentTasks/features/TaskTriggerTag.tsx
index aa39ebda7c5..f273ed7430d 100644
--- a/src/features/AgentTasks/features/TaskTriggerTag.tsx
+++ b/src/features/AgentTasks/features/TaskTriggerTag.tsx
@@ -1,16 +1,14 @@
import { Block, Flexbox, Icon, Text, Tooltip } from '@lobehub/ui';
import { cssVar } from 'antd-style';
-import type { TFunction } from 'i18next';
import { ClockIcon } from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-const formatInterval = (seconds: number, t: TFunction<'chat'>) => {
- if (seconds < 60) return t('taskSchedule.unit.second', { count: seconds });
- if (seconds % 3600 === 0) return t('taskSchedule.unit.hour', { count: seconds / 3600 });
- if (seconds % 60 === 0) return t('taskSchedule.unit.minute', { count: seconds / 60 });
- return t('taskSchedule.unit.second', { count: seconds });
-};
+import {
+ formatIntervalLabel,
+ formatScheduleDescription,
+ formatTimezoneName,
+} from '@/features/AgentTasks/AgentTaskDetail/scheduler/helpers';
interface TaskTriggerTagProps {
heartbeatInterval?: number | null;
@@ -21,40 +19,60 @@ interface TaskTriggerTagProps {
const TaskTriggerTag = memo<TaskTriggerTagProps>(
({ heartbeatInterval, mode = 'tag', schedulePattern, scheduleTimezone }) => {
- const { t } = useTranslation('chat');
- const data = useMemo(() => {
+ const { t, i18n } = useTranslation('chat');
+ const data = useMemo<
+ | {
+ primary: string;
+ secondary?: string;
+ tooltip: string;
+ }
+ | undefined
+ >(() => {
if (schedulePattern) {
- const timezone = scheduleTimezone ? ` (${scheduleTimezone})` : '';
+ const primary = formatScheduleDescription(schedulePattern, t);
+ const tzName = scheduleTimezone
+ ? formatTimezoneName(scheduleTimezone, i18n.language)
+ : undefined;
return {
- tooltip: t('taskSchedule.tag.schedule', {
- schedule: schedulePattern,
- timezone,
- }),
- text: `${schedulePattern} ${timezone}`,
+ primary,
+ secondary: tzName,
+ tooltip: tzName ? `${primary} · ${tzName}` : primary,
};
}
if (heartbeatInterval && heartbeatInterval > 0) {
const every = t('taskSchedule.tag.every', {
- interval: formatInterval(heartbeatInterval, t),
+ interval: formatIntervalLabel(heartbeatInterval, t),
});
return {
+ primary: every,
tooltip: t('taskSchedule.tag.heartbeat', { every }),
- text: every,
};
}
return undefined;
- }, [heartbeatInterval, schedulePattern, scheduleTimezone, t]);
+ }, [heartbeatInterval, schedulePattern, scheduleTimezone, t, i18n.language]);
if (mode === 'inline') {
return (
<Tooltip title={data?.tooltip}>
- <Flexbox horizontal align="center" gap={10}>
- <Icon color={cssVar.colorTextDescription} icon={ClockIcon} size={16} />
- <Text type={data ? undefined : 'secondary'} weight={data ? 500 : undefined}>
- {data?.text ?? t('taskSchedule.tag.add')}
- </Text>
+ <Flexbox horizontal align="flex-start" gap={10}>
+ <Icon
+ color={cssVar.colorTextDescription}
+ icon={ClockIcon}
+ size={16}
+ style={{ marginTop: 2 }}
+ />
+ <Flexbox gap={2}>
+ <Text type={data ? undefined : 'secondary'} weight={data ? 500 : undefined}>
+ {data?.primary ?? t('taskSchedule.tag.add')}
+ </Text>
+ {data?.secondary && (
+ <Text style={{ color: cssVar.colorTextDescription, fontSize: 11 }}>
+ {data.secondary}
+ </Text>
+ )}
+ </Flexbox>
</Flexbox>
</Tooltip>
);
@@ -62,6 +80,8 @@ const TaskTriggerTag = memo<TaskTriggerTagProps>(
if (!data) return null;
+ // Pill height (24px) only fits one line — drop the timezone here; the
+ // tooltip surfaces it on hover.
return (
<Tooltip title={data.tooltip}>
<Block
@@ -75,7 +95,7 @@ const TaskTriggerTag = memo<TaskTriggerTagProps>(
>
<Icon color={cssVar.colorTextDescription} icon={ClockIcon} size={16} />
<Text fontSize={12} type={'secondary'}>
- {data.text}
+ {data.primary}
</Text>
</Block>
</Tooltip>
diff --git a/src/features/AgentTasks/shared/AccordionArrowIcon.tsx b/src/features/AgentTasks/shared/AccordionArrowIcon.tsx
new file mode 100644
index 00000000000..611361f4c91
--- /dev/null
+++ b/src/features/AgentTasks/shared/AccordionArrowIcon.tsx
@@ -0,0 +1,31 @@
+import { memo, type SVGProps } from 'react';
+
+interface AccordionArrowIconProps extends Omit<SVGProps<SVGSVGElement>, 'fill'> {
+ isOpen?: boolean;
+ size?: number | string;
+}
+
+const AccordionArrowIcon = memo<AccordionArrowIconProps>(
+ ({ isOpen = false, size = 18, style, ...rest }) => (
+ <svg
+ fill="currentColor"
+ fillRule="evenodd"
+ height={size}
+ viewBox="0 0 16 16"
+ width={size}
+ xmlns="http://www.w3.org/2000/svg"
+ style={{
+ flex: 'none',
+ lineHeight: 1,
+ transform: isOpen ? 'rotate(90deg)' : undefined,
+ transition: 'transform 200ms',
+ ...style,
+ }}
+ {...rest}
+ >
+ <path d="M7.002 10.624a.5.5 0 01-.752-.432V5.808a.5.5 0 01.752-.432l3.758 2.192a.5.5 0 010 .864l-3.758 2.192z" />
+ </svg>
+ ),
+);
+
+export default AccordionArrowIcon;
diff --git a/src/features/DailyBrief/BriefCard.tsx b/src/features/DailyBrief/BriefCard.tsx
index bbee41288a5..ae371ce689a 100644
--- a/src/features/DailyBrief/BriefCard.tsx
+++ b/src/features/DailyBrief/BriefCard.tsx
@@ -1,8 +1,9 @@
import { DEFAULT_AVATAR, INBOX_SESSION_ID } from '@lobechat/const';
-import { Avatar, Block, Flexbox, Text } from '@lobehub/ui';
+import { ActionIcon, Avatar, Block, Flexbox, Icon, Text } from '@lobehub/ui';
import { Divider } from 'antd';
import { cssVar } from 'antd-style';
-import { memo } from 'react';
+import { Check, ChevronDownIcon, ChevronUpIcon } from 'lucide-react';
+import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
@@ -53,6 +54,10 @@ interface BriefCardProps {
const BriefCard = memo<BriefCardProps>(
({ brief, enableNavigation = true, onAfterResolve, onAfterAddComment }) => {
const navigate = useNavigate();
+ const { t } = useTranslation('home');
+ const isResolved = Boolean(brief.resolvedAction);
+ const [expanded, setExpanded] = useState(false);
+ const showFull = !isResolved || expanded;
const canNavigate = enableNavigation && Boolean(brief.taskId);
@@ -79,19 +84,42 @@ const BriefCard = memo<BriefCardProps>(
</Text>
<Time date={brief.createdAt} />
</Flexbox>
- {brief.agents.length > 0 && <AgentAvatars agents={brief.agents} />}
+ <Flexbox horizontal align={'center'} gap={8}>
+ {isResolved && !expanded && (
+ <Flexbox horizontal align={'center'} gap={4}>
+ <Icon color={cssVar.colorTextQuaternary} icon={Check} size={14} />
+ <Text className={styles.resolvedTag}>{t('brief.resolved')}</Text>
+ </Flexbox>
+ )}
+ {brief.agents.length > 0 && <AgentAvatars agents={brief.agents} />}
+ {isResolved && (
+ <ActionIcon
+ icon={expanded ? ChevronUpIcon : ChevronDownIcon}
+ size={'small'}
+ title={expanded ? t('brief.collapse') : t('brief.expandAll')}
+ onClick={(event) => {
+ event.stopPropagation();
+ setExpanded((v) => !v);
+ }}
+ />
+ )}
+ </Flexbox>
</Flexbox>
- <Divider dashed style={{ marginBlock: 0 }} />
- <BriefCardSummary summary={brief.summary} />
- <BriefCardActions
- actions={brief.actions}
- briefId={brief.id}
- briefType={brief.type}
- resolvedAction={brief.resolvedAction}
- taskId={brief.taskId}
- onAfterAddComment={onAfterAddComment}
- onAfterResolve={onAfterResolve}
- />
+ {showFull && (
+ <>
+ <Divider dashed style={{ marginBlock: 0 }} />
+ <BriefCardSummary summary={brief.summary} />
+ <BriefCardActions
+ actions={brief.actions}
+ briefId={brief.id}
+ briefType={brief.type}
+ resolvedAction={brief.resolvedAction}
+ taskId={brief.taskId}
+ onAfterAddComment={onAfterAddComment}
+ onAfterResolve={onAfterResolve}
+ />
+ </>
+ )}
</Block>
);
},
diff --git a/src/features/DailyBrief/BriefCardActions.tsx b/src/features/DailyBrief/BriefCardActions.tsx
index d3531a7e6e3..9a6547cde76 100644
--- a/src/features/DailyBrief/BriefCardActions.tsx
+++ b/src/features/DailyBrief/BriefCardActions.tsx
@@ -2,7 +2,7 @@ import { type BriefAction, DEFAULT_BRIEF_ACTIONS } from '@lobechat/types';
import { Button, Flexbox, Icon, Text, Tooltip } from '@lobehub/ui';
import { cssVar } from 'antd-style';
import { Check, SquarePen } from 'lucide-react';
-import { memo, useCallback, useEffect, useState } from 'react';
+import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { shallow } from 'zustand/shallow';
@@ -46,18 +46,11 @@ const BriefCardActions = memo<BriefCardActionsProps>(
const { t } = useTranslation('home');
const [commentMode, setCommentMode] = useState<CommentMode | null>(null);
const [loadingKey, setLoadingKey] = useState<string | null>(null);
- const [feedbackSent, setFeedbackSent] = useState(false);
- const { addComment, resolveBrief } = useBriefStore(
- (s) => ({ addComment: s.addComment, resolveBrief: s.resolveBrief }),
+ const { resolveBrief, submitFeedback } = useBriefStore(
+ (s) => ({ resolveBrief: s.resolveBrief, submitFeedback: s.submitFeedback }),
shallow,
);
- useEffect(() => {
- if (!feedbackSent) return;
- const timer = setTimeout(() => setFeedbackSent(false), 1500);
- return () => clearTimeout(timer);
- }, [feedbackSent]);
-
const isResult = briefType === 'result';
const actions: BriefAction[] = isResult
@@ -99,21 +92,29 @@ const BriefCardActions = memo<BriefCardActionsProps>(
} finally {
setLoadingKey(null);
}
- } else {
- if (taskId) {
- await addComment(briefId, taskId, text);
- await onAfterAddComment?.();
- }
- setFeedbackSent(true);
+ } else if (taskId) {
+ // Free-form feedback must resolve the brief (so the heartbeat
+ // re-arm gate stops blocking on this urgent brief) AND re-run
+ // the task so the agent picks up `resolvedComment` next turn.
+ await submitFeedback(briefId, taskId, text);
+ await onAfterAddComment?.();
+ await onAfterResolve?.();
}
setCommentMode(null);
},
- [addComment, briefId, commentMode, resolveBrief, taskId, onAfterResolve, onAfterAddComment],
+ [
+ briefId,
+ commentMode,
+ resolveBrief,
+ submitFeedback,
+ taskId,
+ onAfterResolve,
+ onAfterAddComment,
+ ],
);
if (resolvedAction) return <SuccessTag label={t('brief.resolved')} />;
- if (feedbackSent) return <SuccessTag label={t('brief.feedbackSent')} />;
if (commentMode) {
return <CommentInput onCancel={() => setCommentMode(null)} onSubmit={handleCommentSubmit} />;
}
diff --git a/src/features/DailyBrief/BriefCardSummary.tsx b/src/features/DailyBrief/BriefCardSummary.tsx
index d7f7595b3cd..a29f6c6e31c 100644
--- a/src/features/DailyBrief/BriefCardSummary.tsx
+++ b/src/features/DailyBrief/BriefCardSummary.tsx
@@ -6,7 +6,7 @@ import { useTranslation } from 'react-i18next';
import { styles } from './style';
-export const COLLAPSED_MAX_HEIGHT = 240;
+export const COLLAPSED_MAX_HEIGHT = 180;
interface BriefCardSummaryProps {
summary: string;
diff --git a/src/hooks/useFetchChatTopics.ts b/src/hooks/useFetchChatTopics.ts
index 73cef05fcf9..6da7919ae16 100644
--- a/src/hooks/useFetchChatTopics.ts
+++ b/src/hooks/useFetchChatTopics.ts
@@ -1,9 +1,9 @@
+import { MAIN_SIDEBAR_EXCLUDE_TRIGGERS } from '@/const/topic';
import { useFetchTopics } from '@/hooks/useFetchTopics';
import { useUserStore } from '@/store/user';
import { preferenceSelectors } from '@/store/user/selectors';
const EXCLUDE_STATUSES_COMPLETED = ['completed'];
-const EXCLUDE_TRIGGERS = ['cron', 'eval'];
/**
* Canonical topic fetch for chat sidebars (agent + group). Reads every
@@ -21,6 +21,6 @@ export const useFetchChatTopics = () => {
return useFetchTopics({
excludeStatuses: includeCompleted ? undefined : EXCLUDE_STATUSES_COMPLETED,
- excludeTriggers: EXCLUDE_TRIGGERS,
+ excludeTriggers: MAIN_SIDEBAR_EXCLUDE_TRIGGERS,
});
};
diff --git a/src/hooks/useGatewayReconnect.ts b/src/hooks/useGatewayReconnect.ts
index 69c0cb49fd2..e028189f3dd 100644
--- a/src/hooks/useGatewayReconnect.ts
+++ b/src/hooks/useGatewayReconnect.ts
@@ -1,6 +1,7 @@
import useSWR from 'swr';
import { useChatStore } from '@/store/chat';
+import { useServerConfigStore } from '@/store/serverConfig';
interface RunningOperation {
assistantMessageId: string;
@@ -16,6 +17,10 @@ interface RunningOperation {
* (main agent) and the task-detail activity (task drawer) live in different
* stores, so this hook stays source-agnostic.
*
+ * Reconnect only depends on whether the server has a Gateway URL configured;
+ * the user's lab toggle controls *new* requests, not resuming an op that's
+ * already running on the Gateway.
+ *
* SWR key is the operationId, so the same operation deduplicates and only
* one reconnect attempt fires per op.
*/
@@ -23,10 +28,10 @@ export const useGatewayReconnect = (
topicId: string | null | undefined,
runningOperation: RunningOperation | null | undefined,
) => {
- const isGatewayModeEnabled = useChatStore((s) => s.isGatewayModeEnabled);
+ const agentGatewayUrl = useServerConfigStore((s) => s.serverConfig.agentGatewayUrl);
useSWR(
- runningOperation && topicId && isGatewayModeEnabled()
+ runningOperation && topicId && agentGatewayUrl
? ['reconnectGateway', runningOperation.operationId]
: null,
async () => {
diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.ts
index 85cabd60bed..67e97e28625 100644
--- a/src/locales/default/chat.ts
+++ b/src/locales/default/chat.ts
@@ -507,23 +507,33 @@ export default {
'task.status.fetchingDetails': 'Fetching details...',
'task.status.initializing': 'Initializing task...',
'task.subtask': 'Subtask',
+ 'taskSchedule.advancedSettings': 'Advanced settings',
'taskSchedule.clear': 'Clear',
'taskSchedule.continuous': 'Continuous',
'taskSchedule.enable': 'Enable automation',
'taskSchedule.every': 'Every',
'taskSchedule.frequency': 'Frequency',
+ 'taskSchedule.heading': 'Automation',
'taskSchedule.hours': 'Hours',
- 'taskSchedule.interval': 'Recurring',
- 'taskSchedule.intervalTab': 'Recurring',
+ 'taskSchedule.intervalLabel': 'Run interval',
+ 'taskSchedule.intervalSuffix': 'each time',
+ 'taskSchedule.intervalTab': 'Heartbeat',
'taskSchedule.maxExecutions': 'Max runs',
+ 'taskSchedule.maxExecutionsPlaceholder': 'Unlimited',
'taskSchedule.minutes': 'Minutes',
+ 'taskSchedule.nextRun': 'Next run',
+ 'taskSchedule.nextRun.format': 'MMM D HH:mm',
'taskSchedule.scheduleType.daily': 'Daily',
'taskSchedule.scheduleType.hourly': 'Hourly',
'taskSchedule.scheduleType.weekly': 'Weekly',
'taskSchedule.scheduler': 'Scheduler',
- 'taskSchedule.schedulerNotReady': 'Scheduler is coming soon. Use Recurring for now.',
- 'taskSchedule.schedulerTab': 'Scheduler',
- 'taskSchedule.seconds': 'Seconds',
+ 'taskSchedule.schedulerTab': 'Scheduled',
+ 'taskSchedule.summary.daily': 'Daily at {{time}}',
+ 'taskSchedule.summary.disabled': 'Automation is off',
+ 'taskSchedule.summary.everyNHours': 'Every {{count}} hours{{minute}}',
+ 'taskSchedule.summary.heartbeat': 'Runs every {{interval}}',
+ 'taskSchedule.summary.hourly': 'Every hour{{minute}}',
+ 'taskSchedule.summary.weekly': 'Every {{days}} at {{time}}',
'taskSchedule.tag.add': 'Set schedule',
'taskSchedule.tag.every': 'Every {{interval}}',
'taskSchedule.tag.heartbeat': 'Heartbeat · {{every}}',
@@ -548,6 +558,7 @@ export default {
'taskDetail.activities': 'Activities',
'taskDetail.activitiesEmpty': 'No activity yet',
'taskDetail.artifacts': 'Artifacts',
+ 'taskDetail.artifactSize': '{{value}} chars',
'taskDetail.activities.agentTag': 'Agent',
'taskDetail.activities.fallback.brief': 'posted a brief',
'taskDetail.activities.fallback.comment': 'left a comment',
@@ -571,13 +582,14 @@ export default {
'taskDetail.saveModelConfig': 'Save',
'taskDetail.instructionPlaceholder': 'Click to edit task instructions...',
'taskDetail.latestActivity.brief': 'Brief: {{title}}',
- 'taskDetail.latestActivity.briefOnly': 'Brief',
'taskDetail.latestActivity.briefWithAction': '{{title}} - {{action}}',
'taskDetail.latestActivity.briefWithType': 'Brief ({{type}}): {{title}}',
'taskDetail.latestActivity.briefWithTypeOnly': 'Brief ({{type}})',
'taskDetail.latestActivity.topic': 'Topic: {{title}}',
'taskDetail.latestActivity.topicWithSeq': 'Topic #{{seq}}: {{title}}',
'taskDetail.latestActivity.untitledTopic': 'Untitled topic',
+ 'taskDetail.cancelSchedule': 'Cancel schedule',
+ 'taskDetail.nextRunCountdown': 'Next run in {{countdown}}',
'taskDetail.pauseTask': 'Pause task',
'taskDetail.rerunTask': 'Re-run task',
'taskDetail.runTask': 'Run',
diff --git a/src/services/__tests__/brief.test.ts b/src/services/__tests__/brief.test.ts
index ccbe5fd7b00..3a77f67ab65 100644
--- a/src/services/__tests__/brief.test.ts
+++ b/src/services/__tests__/brief.test.ts
@@ -4,7 +4,6 @@ import { briefService } from '../brief';
const mockQuery = vi.fn();
const mockBriefMutate = vi.fn();
-const mockTaskMutate = vi.fn();
vi.mock('@/libs/trpc/client', () => ({
lambdaClient: {
@@ -13,9 +12,6 @@ vi.mock('@/libs/trpc/client', () => ({
markRead: { mutate: (...args: any[]) => mockBriefMutate(...args) },
resolve: { mutate: (...args: any[]) => mockBriefMutate(...args) },
},
- task: {
- addComment: { mutate: (...args: any[]) => mockTaskMutate(...args) },
- },
},
}));
@@ -67,30 +63,4 @@ describe('BriefService', () => {
expect(mockBriefMutate).toHaveBeenCalledWith({ id: 'brief-1' });
});
});
-
- describe('addComment', () => {
- it('should call task.addComment with correct params', async () => {
- mockTaskMutate.mockResolvedValueOnce({ data: {}, success: true });
-
- await briefService.addComment('task-1', 'my feedback', 'brief-1');
-
- expect(mockTaskMutate).toHaveBeenCalledWith({
- briefId: 'brief-1',
- content: 'my feedback',
- id: 'task-1',
- });
- });
-
- it('should call task.addComment without briefId when not provided', async () => {
- mockTaskMutate.mockResolvedValueOnce({ data: {}, success: true });
-
- await briefService.addComment('task-1', 'feedback text');
-
- expect(mockTaskMutate).toHaveBeenCalledWith({
- briefId: undefined,
- content: 'feedback text',
- id: 'task-1',
- });
- });
- });
});
diff --git a/src/services/brief.ts b/src/services/brief.ts
index 039d86f67e5..f3a5a75aadc 100644
--- a/src/services/brief.ts
+++ b/src/services/brief.ts
@@ -1,10 +1,6 @@
import { lambdaClient } from '@/libs/trpc/client';
class BriefService {
- addComment = async (taskId: string, content: string, briefId?: string) => {
- return lambdaClient.task.addComment.mutate({ briefId, content, id: taskId });
- };
-
listUnresolved = async () => {
return lambdaClient.brief.listUnresolved.query();
};
diff --git a/src/store/brief/slices/list/action.ts b/src/store/brief/slices/list/action.ts
index 994f96730c2..453fdfc147d 100644
--- a/src/store/brief/slices/list/action.ts
+++ b/src/store/brief/slices/list/action.ts
@@ -3,6 +3,7 @@ import { type SWRResponse } from 'swr';
import { useClientDataSWRWithSync } from '@/libs/swr';
import { briefService } from '@/services/brief';
+import { taskService } from '@/services/task';
import { type BriefStore } from '@/store/brief/store';
import { type BriefItem } from '@/store/brief/types';
import { type StoreSetter } from '@/store/types';
@@ -27,10 +28,6 @@ export class BriefListActionImpl {
this.#get = get;
}
- addComment = async (briefId: string, taskId: string, content: string) => {
- await briefService.addComment(taskId, content, briefId);
- };
-
internal_updateBrief = (id: string, data: Partial<BriefItem>) => {
const briefs = this.#get().briefs;
const index = briefs.findIndex((b) => b.id === id);
@@ -54,6 +51,23 @@ export class BriefListActionImpl {
});
};
+ // Free-form feedback from the brief card: resolve the brief with the
+ // user's text (so the heartbeat re-arm gate in TaskLifecycle no longer
+ // sees an unresolved urgent brief), then re-run the task so the agent
+ // picks up `resolvedComment` in its next prompt. Without this, the brief
+ // stays unresolved and the task is parked forever in `human-waiting`.
+ submitFeedback = async (briefId: string, taskId: string, content: string) => {
+ await this.resolveBrief(briefId, 'feedback', content);
+ try {
+ await taskService.run(taskId);
+ } catch (error) {
+ // CONFLICT means a run is already in flight (e.g. the user resolved
+ // multiple briefs at once) — the in-flight run will read the freshly
+ // resolved comment, so the resolve still does its job.
+ console.warn('[BriefStore] submitFeedback: task.run failed', error);
+ }
+ };
+
useFetchBriefs = (isLogin: boolean | undefined): SWRResponse<BriefItem[]> => {
return useClientDataSWRWithSync<BriefItem[]>(
isLogin === true ? [FETCH_BRIEFS_KEY, isLogin] : null,
diff --git a/src/store/chat/slices/aiChat/actions/gateway.ts b/src/store/chat/slices/aiChat/actions/gateway.ts
index 6f892a13b9c..f26d7779194 100644
--- a/src/store/chat/slices/aiChat/actions/gateway.ts
+++ b/src/store/chat/slices/aiChat/actions/gateway.ts
@@ -344,10 +344,9 @@ export class GatewayActionImpl {
}): Promise<void> => {
const { assistantMessageId, operationId, topicId, scope, threadId } = params;
- if (!this.isGatewayModeEnabled()) return;
-
const agentGatewayUrl =
- window.global_serverConfigStore!.getState().serverConfig.agentGatewayUrl!;
+ window.global_serverConfigStore?.getState()?.serverConfig?.agentGatewayUrl;
+ if (!agentGatewayUrl) return;
// Get a fresh JWT token (original expired after 5 min)
const { token } = await aiAgentService.refreshGatewayToken(topicId);
diff --git a/src/store/task/selectors/detailSelectors.ts b/src/store/task/selectors/detailSelectors.ts
index a4ba083ae92..a706fe33353 100644
--- a/src/store/task/selectors/detailSelectors.ts
+++ b/src/store/task/selectors/detailSelectors.ts
@@ -85,7 +85,10 @@ const taskSaveStatus = (s: TaskStoreState) => s.taskSaveStatus;
const activeTopicDrawerTopicId = (s: TaskStoreState) => s.activeTopicDrawerTopicId;
+const activePageDrawerPageId = (s: TaskStoreState) => s.activePageDrawerPageId;
+
export const taskDetailSelectors = {
+ activePageDrawerPageId,
activeTaskAgentId,
activeTaskAutomationMode,
activeTaskCheckpoint,
diff --git a/src/store/task/slices/config/action.test.ts b/src/store/task/slices/config/action.test.ts
index 0316a977241..6b6a041a293 100644
--- a/src/store/task/slices/config/action.test.ts
+++ b/src/store/task/slices/config/action.test.ts
@@ -134,17 +134,50 @@ describe('TaskConfigSliceAction', () => {
});
describe('setAutomationMode', () => {
- it('should optimistically update and call update with automationMode', async () => {
+ it('should seed default heartbeat interval when first enabling', async () => {
const { mutate } = await import('@/libs/swr');
vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);
await useTaskStore.getState().setAutomationMode('T-1', 'heartbeat');
expect(useTaskStore.getState().taskDetailMap['T-1'].automationMode).toBe('heartbeat');
- expect(taskService.update).toHaveBeenCalledWith('T-1', { automationMode: 'heartbeat' });
+ expect(taskService.update).toHaveBeenCalledWith('T-1', {
+ automationMode: 'heartbeat',
+ heartbeatInterval: 600,
+ });
expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-1']);
});
+ it('should preserve existing heartbeat interval when re-entering heartbeat mode', async () => {
+ vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);
+
+ useTaskStore.setState({
+ taskDetailMap: {
+ 'T-1': {
+ ...useTaskStore.getState().taskDetailMap['T-1'],
+ heartbeat: { interval: 1800 },
+ },
+ },
+ });
+
+ await useTaskStore.getState().setAutomationMode('T-1', 'heartbeat');
+
+ expect(taskService.update).toHaveBeenCalledWith('T-1', { automationMode: 'heartbeat' });
+ });
+
+ it('should seed default cron pattern + local timezone when entering schedule mode', async () => {
+ vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);
+
+ await useTaskStore.getState().setAutomationMode('T-1', 'schedule');
+
+ const localTz = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
+ expect(taskService.update).toHaveBeenCalledWith('T-1', {
+ automationMode: 'schedule',
+ schedulePattern: '0 9 * * *',
+ scheduleTimezone: localTz,
+ });
+ });
+
it('should accept null to disable automation', async () => {
vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);
diff --git a/src/store/task/slices/config/action.ts b/src/store/task/slices/config/action.ts
index 9d0a65d7320..d251cc75f34 100644
--- a/src/store/task/slices/config/action.ts
+++ b/src/store/task/slices/config/action.ts
@@ -5,6 +5,19 @@ import type { StoreSetter } from '@/store/types';
import type { TaskStore } from '../../store';
+// Default values applied when a task is switched into a mode for the first time
+// — keeps the popover summary, the cron runtime and the persisted record in
+// sync rather than leaving the task in a "mode enabled but unconfigured" state.
+const DEFAULT_HEARTBEAT_INTERVAL_SECONDS = 600;
+const DEFAULT_SCHEDULE_PATTERN = '0 9 * * *';
+const resolveDefaultTimezone = (): string => {
+ try {
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
+ } catch {
+ return 'UTC';
+ }
+};
+
type Setter = StoreSetter<TaskStore>;
export const createTaskConfigSlice = (set: Setter, get: () => TaskStore, _api?: unknown) =>
@@ -116,8 +129,21 @@ export class TaskConfigSliceActionImpl {
}
};
- // Switch between automation modes; null = disable automation.
+ // Switch between automation modes; null = disable automation. When entering a
+ // mode that has never been configured, also persist the mode's defaults so the
+ // popover summary, cron runtime and DB row stay aligned.
setAutomationMode = async (id: string, mode: TaskAutomationMode | null): Promise<void> => {
+ const detail = this.#get().taskDetailMap[id];
+
+ const update: Parameters<typeof taskService.update>[1] = { automationMode: mode };
+ if (mode === 'heartbeat' && !detail?.heartbeat?.interval) {
+ update.heartbeatInterval = DEFAULT_HEARTBEAT_INTERVAL_SECONDS;
+ }
+ if (mode === 'schedule') {
+ if (!detail?.schedule?.pattern) update.schedulePattern = DEFAULT_SCHEDULE_PATTERN;
+ if (!detail?.schedule?.timezone) update.scheduleTimezone = resolveDefaultTimezone();
+ }
+
// Optimistic update so the Segmented reflects the new tab immediately
this.#get().internal_dispatchTaskDetail({
id,
@@ -126,7 +152,7 @@ export class TaskConfigSliceActionImpl {
});
try {
- await taskService.update(id, { automationMode: mode });
+ await taskService.update(id, update);
await this.#get().internal_refreshTaskDetail(id);
} catch (error) {
console.error('[TaskStore] Failed to update automation mode:', error);
diff --git a/src/store/task/slices/detail/action.ts b/src/store/task/slices/detail/action.ts
index 40efbe1594d..cc8fadbef84 100644
--- a/src/store/task/slices/detail/action.ts
+++ b/src/store/task/slices/detail/action.ts
@@ -192,7 +192,11 @@ export class TaskDetailSliceActionImpl {
setActiveTaskId = (taskId?: string): void => {
if (this.#get().activeTaskId === taskId) return;
this.#set(
- { activeTaskId: taskId, activeTopicDrawerTopicId: undefined },
+ {
+ activePageDrawerPageId: undefined,
+ activeTaskId: taskId,
+ activeTopicDrawerTopicId: undefined,
+ },
false,
'setActiveTaskId',
);
@@ -208,6 +212,22 @@ export class TaskDetailSliceActionImpl {
this.#set({ activeTopicDrawerTopicId: undefined }, false, 'closeTopicDrawer');
};
+ openPageDrawer = (pageId: string): void => {
+ if (this.#get().activePageDrawerPageId === pageId) return;
+ // Page and topic drawers share right-side floating real estate; close the
+ // other one so they don't stack.
+ this.#set(
+ { activePageDrawerPageId: pageId, activeTopicDrawerTopicId: undefined },
+ false,
+ 'openPageDrawer',
+ );
+ };
+
+ closePageDrawer = (): void => {
+ if (!this.#get().activePageDrawerPageId) return;
+ this.#set({ activePageDrawerPageId: undefined }, false, 'closePageDrawer');
+ };
+
unpinDocument = async (taskId: string, documentId: string): Promise<void> => {
await taskService.unpinDocument(taskId, documentId);
await this.internal_refreshTaskDetail(taskId);
diff --git a/src/store/task/slices/detail/initialState.ts b/src/store/task/slices/detail/initialState.ts
index 34d9009963c..445ce25b2b5 100644
--- a/src/store/task/slices/detail/initialState.ts
+++ b/src/store/task/slices/detail/initialState.ts
@@ -1,6 +1,7 @@
import type { TaskDetailData } from '@lobechat/types';
export interface TaskDetailSliceState {
+ activePageDrawerPageId?: string;
activeTaskId?: string;
activeTopicDrawerTopicId?: string;
isCreatingTask: boolean;
diff --git a/src/store/task/slices/list/action.ts b/src/store/task/slices/list/action.ts
index 13044a84323..c75cbb3ebc3 100644
--- a/src/store/task/slices/list/action.ts
+++ b/src/store/task/slices/list/action.ts
@@ -19,10 +19,12 @@ export const ALL_AGENTS_LIST_KEY = '__all__';
// 'scheduled' shares the 'running' column — both represent "automation in
// progress" from the user's perspective (one is mid-tick, the other is
// waiting for the next tick).
+// `needsInput` is intentionally first: in the list view it surfaces the
+// actionable items at the top of the page.
const DEFAULT_KANBAN_GROUPS = [
+ { key: 'needsInput', statuses: ['paused', 'failed'] },
{ key: 'backlog', statuses: ['backlog'] },
{ key: 'running', statuses: ['running', 'scheduled'] },
- { key: 'needsInput', statuses: ['paused', 'failed'] },
{ key: 'done', statuses: ['completed'] },
{ key: 'canceled', statuses: ['canceled'] },
];