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.

✨ feat(tasks): create scheduled tasks from the Scheduled tasks tab (#21165)

Rdmclin2c96688842d95
diff --git a/apps/server/src/services/task/armScheduleOnCreate.test.ts b/apps/server/src/services/task/armScheduleOnCreate.test.ts
new file mode 100644
index 00000000000..018d1b8e3a2
--- /dev/null
+++ b/apps/server/src/services/task/armScheduleOnCreate.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it } from 'vitest';
+
+import { armScheduleOnCreate } from './armScheduleOnCreate';
+
+const now = new Date('2026-10-18T09:00:00.000Z');
+
+describe('armScheduleOnCreate', () => {
+ it('creates a schedule-mode task as scheduled with its window opened', () => {
+ expect(
+ armScheduleOnCreate({ automationMode: 'schedule', schedulePattern: '0 9 * * *' }, now),
+ ).toEqual({
+ context: { scheduler: { scheduleStartedAt: '2026-10-18T09:00:00.000Z' } },
+ status: 'scheduled',
+ });
+ });
+
+ it('keeps the other context pockets', () => {
+ const origin = { topicId: 'tpc_1' } as any;
+
+ expect(
+ armScheduleOnCreate(
+ {
+ automationMode: 'schedule',
+ context: { origin, scheduler: { consecutiveFailures: 0 } },
+ schedulePattern: '0 9 * * *',
+ },
+ now,
+ ).context,
+ ).toEqual({
+ origin,
+ scheduler: { consecutiveFailures: 0, scheduleStartedAt: '2026-10-18T09:00:00.000Z' },
+ });
+ });
+
+ it('does not arm a schedule-mode task without a cron pattern', () => {
+ expect(armScheduleOnCreate({ automationMode: 'schedule' }, now)).toEqual({});
+ expect(armScheduleOnCreate({ automationMode: 'schedule', schedulePattern: '' }, now)).toEqual(
+ {},
+ );
+ });
+
+ it('leaves non-schedule tasks untouched', () => {
+ expect(
+ armScheduleOnCreate(
+ { automationMode: 'heartbeat', context: { scheduler: { consecutiveFailures: 1 } } },
+ now,
+ ),
+ ).toEqual({});
+ expect(armScheduleOnCreate({}, now)).toEqual({});
+ });
+});
diff --git a/apps/server/src/services/task/armScheduleOnCreate.ts b/apps/server/src/services/task/armScheduleOnCreate.ts
new file mode 100644
index 00000000000..89c39b86957
--- /dev/null
+++ b/apps/server/src/services/task/armScheduleOnCreate.ts
@@ -0,0 +1,33 @@
+import type { TaskContext, TaskStatus } from '@lobechat/types';
+
+/**
+ * Arms a task created directly in schedule mode, matching what starting a
+ * schedule through `updateStatus(…, 'scheduled')` does.
+ *
+ * The dispatcher fires any non-terminal schedule-mode task, so a task created
+ * with `automationMode: 'schedule'` is live from its first insert. Creating it
+ * as `scheduled` keeps the UI's run/pause controls truthful, and stamping
+ * `context.scheduler.scheduleStartedAt` opens the window `maxExecutions`
+ * counts against and keeps the dispatcher from replaying an occurrence from
+ * before the task existed.
+ */
+export const armScheduleOnCreate = (
+ input: {
+ automationMode?: 'heartbeat' | 'schedule';
+ context?: TaskContext;
+ schedulePattern?: string;
+ },
+ now: Date = new Date(),
+): { context?: TaskContext; status?: TaskStatus } => {
+ // Without a cron pattern the dispatcher never picks the task up, so it is
+ // not live and must not look armed.
+ if (input.automationMode !== 'schedule' || !input.schedulePattern) return {};
+
+ return {
+ context: {
+ ...input.context,
+ scheduler: { ...input.context?.scheduler, scheduleStartedAt: now.toISOString() },
+ },
+ status: 'scheduled',
+ };
+};
diff --git a/apps/server/src/services/task/index.ts b/apps/server/src/services/task/index.ts
index 665a8225c47..9ad9c5f1af6 100644
--- a/apps/server/src/services/task/index.ts
+++ b/apps/server/src/services/task/index.ts
@@ -1,5 +1,5 @@
import { TASK_ASSIGNEE_PERMISSION_CODES } from '@lobechat/const/rbac';
-import type { TaskContext, TaskDetailData, TaskItem } from '@lobechat/types';
+import type { TaskContext, TaskDetailData, TaskItem, TaskStatus } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import pMap from 'p-map';
@@ -17,6 +17,7 @@ import { type SubtaskGraphPlan, TaskGraphService } from '../taskGraph';
import { type ReviewResult, TaskReviewService } from '../taskReview';
import { TaskRunnerService } from '../taskRunner';
import { writeKeepingArchivedIdle } from './archiveGuard';
+import { armScheduleOnCreate } from './armScheduleOnCreate';
import type { TaskServiceDeps } from './deps';
import { TaskDetailService } from './detail';
import { resolveMissingTaskModelConfig } from './modelSnapshot';
@@ -190,7 +191,10 @@ export class TaskService {
// produce a `Private parent + Public child` combo if the caller insists.
this.assertParentVisibilityCompat(createData.visibility, parentVisibility);
- const task = await this.createTaskWithAssigneeLock(createData);
+ const task = await this.createTaskWithAssigneeLock({
+ ...createData,
+ ...armScheduleOnCreate(createData),
+ });
return task;
}
@@ -638,7 +642,7 @@ export class TaskService {
}
private async createTaskWithAssigneeLock(
- createData: CreateTaskInput & { config?: Record<string, unknown> },
+ createData: CreateTaskInput & { config?: Record<string, unknown>; status?: TaskStatus },
): Promise<TaskItem> {
if (!createData.assigneeUserId || !this.workspaceId) {
await this.assertAssigneeUserAssignable(createData.assigneeUserId);
diff --git a/locales/ar/chat.json b/locales/ar/chat.json
index 1b2ce68e97c..a9e67816648 100644
--- a/locales/ar/chat.json
+++ b/locales/ar/chat.json
@@ -341,6 +341,7 @@
"createTask.instructionPlaceholder": "أضف وصفًا...",
"createTask.member": "المُكلف",
"createTask.submit": "إنشاء مهمة",
+ "createTask.submitScheduled": "إنشاء مهمة مجدولة",
"createTask.titlePlaceholder": "عنوان المهمة",
"createTask.visibility.changeFailed": "فشل في تغيير رؤية المهمة",
"createTask.visibility.helperPrivate": "فقط يمكنك رؤية هذه المهمة.",
diff --git a/locales/bg-BG/chat.json b/locales/bg-BG/chat.json
index 097a63befe8..e466b765d5e 100644
--- a/locales/bg-BG/chat.json
+++ b/locales/bg-BG/chat.json
@@ -341,6 +341,7 @@
"createTask.instructionPlaceholder": "Добавете описание...",
"createTask.member": "Назначен",
"createTask.submit": "Създаване на задача",
+ "createTask.submitScheduled": "Създаване на планирана задача",
"createTask.titlePlaceholder": "Заглавие на задачата",
"createTask.visibility.changeFailed": "Неуспешна промяна на видимостта на задачата",
"createTask.visibility.helperPrivate": "Само вие можете да видите тази задача.",
diff --git a/locales/de-DE/chat.json b/locales/de-DE/chat.json
index f5ab05d8bf9..4fcc97f0dae 100644
--- a/locales/de-DE/chat.json
+++ b/locales/de-DE/chat.json
@@ -341,6 +341,7 @@
"createTask.instructionPlaceholder": "Beschreibung hinzufügen...",
"createTask.member": "Zuständiger",
"createTask.submit": "Aufgabe erstellen",
+ "createTask.submitScheduled": "Geplante Aufgabe erstellen",
"createTask.titlePlaceholder": "Aufgabentitel",
"createTask.visibility.changeFailed": "Sichtbarkeit der Aufgabe konnte nicht geändert werden",
"createTask.visibility.helperPrivate": "Nur Sie können diese Aufgabe sehen.",
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index aff2edae00a..02fa899c18d 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -343,6 +343,7 @@
"createTask.instructionPlaceholder": "Add task instruction...",
"createTask.member": "Assignee",
"createTask.submit": "Create task",
+ "createTask.submitScheduled": "Create scheduled task",
"createTask.titlePlaceholder": "Task title",
"createTask.visibility.changeFailed": "Failed to change task visibility",
"createTask.visibility.helperPrivate": "Only you can see this task.",
diff --git a/locales/es-ES/chat.json b/locales/es-ES/chat.json
index 4936918be8b..ebf0b08c87b 100644
--- a/locales/es-ES/chat.json
+++ b/locales/es-ES/chat.json
@@ -341,6 +341,7 @@
"createTask.instructionPlaceholder": "Añadir descripción...",
"createTask.member": "Asignado",
"createTask.submit": "Crear tarea",
+ "createTask.submitScheduled": "Crear tarea programada",
"createTask.titlePlaceholder": "Título de la tarea",
"createTask.visibility.changeFailed": "Error al cambiar la visibilidad de la tarea",
"createTask.visibility.helperPrivate": "Solo tú puedes ver esta tarea.",
diff --git a/locales/fa-IR/chat.json b/locales/fa-IR/chat.json
index c933d019082..13f9d267af5 100644
--- a/locales/fa-IR/chat.json
+++ b/locales/fa-IR/chat.json
@@ -341,6 +341,7 @@
"createTask.instructionPlaceholder": "افزودن توضیحات...",
"createTask.member": "مسئول",
"createTask.submit": "ایجاد وظیفه",
+ "createTask.submitScheduled": "ایجاد وظیفه زمان‌بندی‌شده",
"createTask.titlePlaceholder": "عنوان وظیفه",
"createTask.visibility.changeFailed": "تغییر قابلیت مشاهده وظیفه ناموفق بود",
"createTask.visibility.helperPrivate": "فقط شما می‌توانید این وظیفه را ببینید.",
diff --git a/locales/fr-FR/chat.json b/locales/fr-FR/chat.json
index acd7a0f25db..00c11700dd4 100644
--- a/locales/fr-FR/chat.json
+++ b/locales/fr-FR/chat.json
@@ -341,6 +341,7 @@
"createTask.instructionPlaceholder": "Ajouter une description...",
"createTask.member": "Attribué",
"createTask.submit": "Créer la tâche",
+ "createTask.submitScheduled": "Créer une tâche planifiée",
"createTask.titlePlaceholder": "Titre de la tâche",
"createTask.visibility.changeFailed": "Échec du changement de visibilité de la tâche",
"createTask.visibility.helperPrivate": "Vous seul pouvez voir cette tâche.",
diff --git a/locales/it-IT/chat.json b/locales/it-IT/chat.json
index e94d7137bc2..0083f99471e 100644
--- a/locales/it-IT/chat.json
+++ b/locales/it-IT/chat.json
@@ -341,6 +341,7 @@
"createTask.instructionPlaceholder": "Aggiungi una descrizione...",
"createTask.member": "Assegnatario",
"createTask.submit": "Crea attività",
+ "createTask.submitScheduled": "Crea attività programmata",
"createTask.titlePlaceholder": "Titolo dell’attività",
"createTask.visibility.changeFailed": "Impossibile modificare la visibilità del compito",
"createTask.visibility.helperPrivate": "Solo tu puoi vedere questo compito.",
diff --git a/locales/ja-JP/chat.json b/locales/ja-JP/chat.json
index 0fb24ba379f..926b8844822 100644
--- a/locales/ja-JP/chat.json
+++ b/locales/ja-JP/chat.json
@@ -341,6 +341,7 @@
"createTask.instructionPlaceholder": "説明を追加...",
"createTask.member": "担当者",
"createTask.submit": "タスクを作成",
+ "createTask.submitScheduled": "スケジュールされたタスクを作成",
"createTask.titlePlaceholder": "タスク名",
"createTask.visibility.changeFailed": "タスクの可視性の変更に失敗しました",
"createTask.visibility.helperPrivate": "このタスクはあなただけが見ることができます。",
diff --git a/locales/ko-KR/chat.json b/locales/ko-KR/chat.json
index f66e813357b..dd9e57debd1 100644
--- a/locales/ko-KR/chat.json
+++ b/locales/ko-KR/chat.json
@@ -341,6 +341,7 @@
"createTask.instructionPlaceholder": "설명 추가...",
"createTask.member": "담당자",
"createTask.submit": "작업 생성",
+ "createTask.submitScheduled": "예약된 작업 생성",
"createTask.titlePlaceholder": "작업 제목",
"createTask.visibility.changeFailed": "작업 가시성 변경 실패",
"createTask.visibility.helperPrivate": "이 작업은 오직 당신만 볼 수 있습니다.",
diff --git a/locales/nl-NL/chat.json b/locales/nl-NL/chat.json
index bfe3b355faa..58c95974833 100644
--- a/locales/nl-NL/chat.json
+++ b/locales/nl-NL/chat.json
@@ -341,6 +341,7 @@
"createTask.instructionPlaceholder": "Beschrijving toevoegen...",
"createTask.member": "Toewijzing",
"createTask.submit": "Taak aanmaken",
+ "createTask.submitScheduled": "Geplande taak maken",
"createTask.titlePlaceholder": "Taaktitel",
"createTask.visibility.changeFailed": "Het wijzigen van de zichtbaarheid van de taak is mislukt",
"createTask.visibility.helperPrivate": "Alleen jij kunt deze taak zien.",
diff --git a/locales/pl-PL/chat.json b/locales/pl-PL/chat.json
index 1af94f6f760..c99f7bce273 100644
--- a/locales/pl-PL/chat.json
+++ b/locales/pl-PL/chat.json
@@ -341,6 +341,7 @@
"createTask.instructionPlaceholder": "Dodaj opis...",
"createTask.member": "Przypisany",
"createTask.submit": "Utwórz zadanie",
+ "createTask.submitScheduled": "Utwórz zaplanowane zadanie",
"createTask.titlePlaceholder": "Tytuł zadania",
"createTask.visibility.changeFailed": "Nie udało się zmienić widoczności zadania",
"createTask.visibility.helperPrivate": "Tylko Ty możesz zobaczyć to zadanie.",
diff --git a/locales/pt-BR/chat.json b/locales/pt-BR/chat.json
index a0a5028b994..0566019a164 100644
--- a/locales/pt-BR/chat.json
+++ b/locales/pt-BR/chat.json
@@ -341,6 +341,7 @@
"createTask.instructionPlaceholder": "Adicionar descrição...",
"createTask.member": "Responsável",
"createTask.submit": "Criar tarefa",
+ "createTask.submitScheduled": "Criar tarefa agendada",
"createTask.titlePlaceholder": "Título da tarefa",
"createTask.visibility.changeFailed": "Falha ao alterar a visibilidade da tarefa",
"createTask.visibility.helperPrivate": "Somente você pode ver esta tarefa.",
diff --git a/locales/ru-RU/chat.json b/locales/ru-RU/chat.json
index 5dd1bb50ab3..bd3c574318d 100644
--- a/locales/ru-RU/chat.json
+++ b/locales/ru-RU/chat.json
@@ -341,6 +341,7 @@
"createTask.instructionPlaceholder": "Добавить описание...",
"createTask.member": "Исполнитель",
"createTask.submit": "Создать задачу",
+ "createTask.submitScheduled": "Создать запланированную задачу",
"createTask.titlePlaceholder": "Название задачи",
"createTask.visibility.changeFailed": "Не удалось изменить видимость задачи",
"createTask.visibility.helperPrivate": "Только вы можете видеть эту задачу.",
diff --git a/locales/tr-TR/chat.json b/locales/tr-TR/chat.json
index 28a643d16c5..724cc105ff8 100644
--- a/locales/tr-TR/chat.json
+++ b/locales/tr-TR/chat.json
@@ -341,6 +341,7 @@
"createTask.instructionPlaceholder": "Açıklama ekle...",
"createTask.member": "Atanan",
"createTask.submit": "Görevi oluştur",
+ "createTask.submitScheduled": "Zamanlanmış görevi oluştur",
"createTask.titlePlaceholder": "Görev başlığı",
"createTask.visibility.changeFailed": "Görev görünürlüğü değiştirilemedi",
"createTask.visibility.helperPrivate": "Bu görevi yalnızca siz görebilirsiniz.",
diff --git a/locales/vi-VN/chat.json b/locales/vi-VN/chat.json
index ae2b998b68d..085d532aba7 100644
--- a/locales/vi-VN/chat.json
+++ b/locales/vi-VN/chat.json
@@ -341,6 +341,7 @@
"createTask.instructionPlaceholder": "Thêm mô tả...",
"createTask.member": "Người được giao",
"createTask.submit": "Tạo nhiệm vụ",
+ "createTask.submitScheduled": "Tạo tác vụ đã lên lịch",
"createTask.titlePlaceholder": "Tiêu đề nhiệm vụ",
"createTask.visibility.changeFailed": "Không thể thay đổi quyền hiển thị của nhiệm vụ",
"createTask.visibility.helperPrivate": "Chỉ bạn có thể xem nhiệm vụ này.",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index baf6d8fe0d7..c866e8945e4 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -343,6 +343,7 @@
"createTask.instructionPlaceholder": "添加描述…",
"createTask.member": "负责人",
"createTask.submit": "创建任务",
+ "createTask.submitScheduled": "创建定时任务",
"createTask.titlePlaceholder": "任务标题",
"createTask.visibility.changeFailed": "切换任务可见性失败",
"createTask.visibility.helperPrivate": "仅自己可见此任务。",
diff --git a/locales/zh-TW/chat.json b/locales/zh-TW/chat.json
index 25046bca87b..1eb1d95fa7b 100644
--- a/locales/zh-TW/chat.json
+++ b/locales/zh-TW/chat.json
@@ -341,6 +341,7 @@
"createTask.instructionPlaceholder": "新增描述...",
"createTask.member": "指派人",
"createTask.submit": "建立任務",
+ "createTask.submitScheduled": "建立排程任務",
"createTask.titlePlaceholder": "任務標題",
"createTask.visibility.changeFailed": "無法更改任務可見性",
"createTask.visibility.helperPrivate": "只有您可以看到此任務。",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index a854f7e8ca4..45b01be024c 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -2151,6 +2151,7 @@ export default {
'createTask.expandToInline': 'Dock to page',
'createTask.instructionPlaceholder': 'Add task instruction...',
'createTask.submit': 'Create task',
+ 'createTask.submitScheduled': 'Create scheduled task',
'createTask.titlePlaceholder': 'Task title',
'createTask.visibility.changeFailed': 'Failed to change task visibility',
'createTask.visibility.helperPrivate': 'Only you can see this task.',
diff --git a/packages/types/src/task/index.ts b/packages/types/src/task/index.ts
index 2bc0890ce77..6ef20330b48 100644
--- a/packages/types/src/task/index.ts
+++ b/packages/types/src/task/index.ts
@@ -246,6 +246,9 @@ export interface TaskSchedulerContext {
consecutiveFailures?: number;
// ISO timestamp when the latest tick was scheduled. Informational only.
scheduledAt?: string;
+ // ISO timestamp opening the current schedule window: `maxExecutions` counts
+ // schedule runs since it, and the dispatcher never fires an earlier occurrence.
+ scheduleStartedAt?: string;
// QStash messageId (or LocalScheduler scheduleId) for the next tick. Used to
// cancel when the user wants an interval change to take effect immediately.
tickMessageId?: string;
diff --git a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
index d6b0ce2a591..4ac7620d9b2 100644
--- a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
+++ b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
@@ -1,5 +1,6 @@
import {
ActionIcon,
+ Button,
Flexbox,
Pagination,
TabsIndicator,
@@ -284,6 +285,10 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, projectId }) => {
const collectionTasks = collectionSWR.data?.data ?? [];
const collectionTasksTotal = collectionSWR.data?.total ?? 0;
const isCollectionListInit = collectionSWR.data !== undefined;
+ // An empty Scheduled tab offers creation from its empty state; the header
+ // button would only duplicate it.
+ const showScheduledEmptyCreate =
+ isScheduledCollection && canCreateTask && isCollectionListInit && collectionTasksTotal === 0;
const scheduledViewOptions = useMemo(
() => getScheduledTaskViewOptions(viewOptions),
[viewOptions],
@@ -340,6 +345,21 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, projectId }) => {
});
}, [agentId, canCreateTask, createActionBehavior.mode, navigate, projectId, updateSystemStatus]);
+ const handleCreateScheduledTask = useCallback(() => {
+ if (!canCreateTask) return;
+ createTaskModal({
+ agentId,
+ lockAssignee: !!agentId,
+ projectId,
+ schedule: true,
+ // The scheduled tab has no inline entry to dock into.
+ showInlineToggle: false,
+ onCreated: (task) => {
+ navigate(taskDetailPath(task.identifier, agentId ? task.agentId : undefined, task.name));
+ },
+ });
+ }, [agentId, canCreateTask, navigate, projectId]);
+
const handleShowHiddenCompleted = useCallback(() => {
setViewOptions((prev) => ({ ...prev, hideCompleted: false }));
}, [setViewOptions]);
@@ -424,6 +444,15 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, projectId }) => {
onClick={handleCreateTask}
/>
)}
+ {isScheduledCollection && !showScheduledEmptyCreate && (
+ <ActionIcon
+ disabled={!canCreateTask}
+ icon={Plus}
+ size={DESKTOP_HEADER_ICON_SMALL_SIZE}
+ title={canCreateTask ? t('createTask.submitScheduled') : reason}
+ onClick={handleCreateScheduledTask}
+ />
+ )}
{!isScheduledCollection && headerVisibility.showViewOptions && (
<TasksGroupConfig
options={viewOptions}
@@ -475,6 +504,13 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, projectId }) => {
items={collectionTasks}
options={isMineCollection ? myTaskViewOptions : scheduledViewOptions}
routeScope={routeScope}
+ emptyAction={
+ showScheduledEmptyCreate ? (
+ <Button icon={Plus} onClick={handleCreateScheduledTask}>
+ {t('createTask.submitScheduled')}
+ </Button>
+ ) : undefined
+ }
emptyDescription={
isMineCollection
? t(
diff --git a/src/features/AgentTasks/AgentTaskList/TaskList.tsx b/src/features/AgentTasks/AgentTaskList/TaskList.tsx
index 5f987ccef2f..11082ce9a6c 100644
--- a/src/features/AgentTasks/AgentTaskList/TaskList.tsx
+++ b/src/features/AgentTasks/AgentTaskList/TaskList.tsx
@@ -48,6 +48,8 @@ interface TaskListProps {
* so it never disagrees with the empty signal.
*/
data?: unknown;
+ /** Call to action under the empty state, e.g. creating the collection's first task. */
+ emptyAction?: ReactNode;
emptyDescription?: string;
/** Thrown error from the list SWR — surfaced as a failure state, not a skeleton. */
error?: unknown;
@@ -268,6 +270,7 @@ const TaskList = memo<TaskListProps>((props) => {
const emptyState = (
<Center height={'80vh'} width={'100%'}>
<Empty
+ action={props.emptyAction}
description={props.emptyDescription ?? t('taskList.empty')}
icon={ClipboardCheckIcon}
/>
diff --git a/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx b/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx
index 77fd4bf07b4..af4305ee9ba 100644
--- a/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx
+++ b/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx
@@ -41,6 +41,12 @@ import { UnassignedAssigneeIcon } from '../features/UnassignedAssigneeIcon';
import { useAgentDisplayMeta } from '../shared/useAgentDisplayMeta';
import { useAgentVisibility } from '../shared/useAgentVisibility';
import { useUserDisplayMeta } from '../shared/useUserDisplayMeta';
+import ScheduleChip from './ScheduleChip';
+import {
+ createDefaultScheduleDraft,
+ type ScheduleDraft,
+ toScheduledCreateParams,
+} from './scheduleDraft';
import { useTitleEnterToInstruction } from './useTitleEnterToInstruction';
export interface CreateTaskContentProps {
@@ -54,6 +60,11 @@ export interface CreateTaskContentProps {
lockAssignee?: boolean;
onCreated?: (task: { agentId?: string; identifier: string; name?: string }) => void;
projectId?: string;
+ /**
+ * Creates a scheduled task: the form gains a schedule chip and the task is
+ * created with that schedule already on. Used by the Scheduled tasks tab.
+ */
+ schedule?: boolean;
/**
* Whether to show the "minimize to inline entry" button. Only the list view has an
* inline entry target, so contexts like the Kanban board pass `false` to hide it.
@@ -68,6 +79,7 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
lockAssignee,
onCreated,
projectId,
+ schedule: isScheduled = false,
showInlineToggle = true,
}) => {
const { t } = useTranslation('chat');
@@ -92,6 +104,7 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
// and going private stays one click away. In personal mode the field is
// irrelevant and the chip is hidden anyway.
const [visibility, setVisibility] = useState<'private' | 'public'>('public');
+ const [scheduleDraft, setScheduleDraft] = useState<ScheduleDraft>(createDefaultScheduleDraft);
const assigneeVisibility = useAgentVisibility(assigneeAgentId);
const isPrivateAgent = assigneeVisibility === 'private';
@@ -160,15 +173,17 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
const editorJson = editor?.getDocument?.('json') as unknown;
+ // Only present when the user pinned a run location / directory —
+ // otherwise the task inherits the assignee agent entirely.
+ const config = execution ? { execution: toTaskExecutionConfigPatch(execution) } : undefined;
+
// `createTask` keeps its rejecting contract; surface the failure here so a
// failed create isn't silent and the modal stays open with its content.
try {
const result = await createTask({
assigneeAgentId,
assigneeUserId,
- // Only present when the user pinned a run location / directory —
- // otherwise the task inherits the assignee agent entirely.
- ...(execution ? { config: { execution: toTaskExecutionConfigPatch(execution) } } : {}),
+ ...(isScheduled ? toScheduledCreateParams(scheduleDraft, config) : { config }),
editorData: editorJson,
instruction: instruction || title.trim(),
name: title.trim() || undefined,
@@ -198,9 +213,11 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
execution,
createTask,
editor,
+ isScheduled,
onCreated,
priority,
projectId,
+ scheduleDraft,
t,
title,
visibility,
@@ -279,6 +296,14 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
}}
>
<Flexbox horizontal gap={2} wrap={'wrap'}>
+ {isScheduled && (
+ <ScheduleChip
+ disabled={!canCreateTask}
+ value={scheduleDraft}
+ onChange={setScheduleDraft}
+ />
+ )}
+
<TaskPriorityTag priority={priority} onChange={setPriority}>
<Block
clickable
@@ -425,7 +450,7 @@ const CreateTaskContent = memo<CreateTaskContentProps>(
type={'primary'}
onClick={handleSubmit}
>
- {t('createTask.submit')}
+ {t(isScheduled ? 'createTask.submitScheduled' : 'createTask.submit')}
</Button>
</Flexbox>
</Flexbox>
diff --git a/src/features/AgentTasks/CreateTaskModal/ScheduleChip.tsx b/src/features/AgentTasks/CreateTaskModal/ScheduleChip.tsx
new file mode 100644
index 00000000000..62caaade27d
--- /dev/null
+++ b/src/features/AgentTasks/CreateTaskModal/ScheduleChip.tsx
@@ -0,0 +1,80 @@
+'use client';
+
+import { Block, createStaticStyles, cssVar, Flexbox, Icon, Popover, Text } from '@lobehub/ui';
+import { ClockIcon } from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import {
+ formatScheduleDescription,
+ formatTimezoneName,
+} from '../AgentTaskDetail/scheduler/helpers';
+import SchedulerForm from '../AgentTaskDetail/scheduler/SchedulerForm';
+import type { ScheduleDraft } from './scheduleDraft';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ popover: css`
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 12px;
+ background: ${cssVar.colorBgContainer};
+ `,
+}));
+
+interface ScheduleChipProps {
+ disabled?: boolean;
+ onChange: (draft: ScheduleDraft) => void;
+ value: ScheduleDraft;
+}
+
+/**
+ * Create-form chip for a scheduled task: shows the drafted schedule and edits
+ * it with the same form the task detail uses, before the task exists.
+ */
+const ScheduleChip = memo<ScheduleChipProps>(({ disabled, onChange, value }) => {
+ const { t, i18n } = useTranslation('chat');
+
+ const summary = useMemo(() => formatScheduleDescription(value.pattern, t), [value.pattern, t]);
+ const timezoneName = useMemo(
+ () => formatTimezoneName(value.timezone, i18n.language),
+ [value.timezone, i18n.language],
+ );
+
+ return (
+ <Popover
+ className={styles.popover}
+ disabled={disabled}
+ placement="topLeft"
+ trigger="click"
+ content={
+ <Flexbox gap={12} style={{ padding: 4, width: 400 }}>
+ <Text weight={500}>{t('taskSchedule.scheduler')}</Text>
+ <SchedulerForm
+ maxExecutions={value.maxExecutions}
+ pattern={value.pattern}
+ timezone={value.timezone}
+ onChange={onChange}
+ />
+ </Flexbox>
+ }
+ >
+ <Block
+ clickable
+ horizontal
+ align="center"
+ gap={6}
+ height={24}
+ paddingBlock={3}
+ paddingInline={8}
+ title={`${summary} · ${timezoneName}`}
+ variant={'borderless'}
+ >
+ <Icon color={cssVar.colorTextDescription} icon={ClockIcon} size={14} />
+ <Text fontSize={12}>{summary}</Text>
+ </Block>
+ </Popover>
+ );
+});
+
+ScheduleChip.displayName = 'ScheduleChip';
+
+export default ScheduleChip;
diff --git a/src/features/AgentTasks/CreateTaskModal/scheduleDraft.test.ts b/src/features/AgentTasks/CreateTaskModal/scheduleDraft.test.ts
new file mode 100644
index 00000000000..0d2786c0dad
--- /dev/null
+++ b/src/features/AgentTasks/CreateTaskModal/scheduleDraft.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from 'vitest';
+
+import { createDefaultScheduleDraft, toScheduledCreateParams } from './scheduleDraft';
+
+describe('createDefaultScheduleDraft', () => {
+ it('defaults to a continuous daily 09:00 schedule', () => {
+ const draft = createDefaultScheduleDraft();
+
+ expect(draft.pattern).toBe('0 9 * * *');
+ expect(draft.maxExecutions).toBeNull();
+ expect(draft.timezone).toBeTruthy();
+ });
+});
+
+describe('toScheduledCreateParams', () => {
+ it('creates the task in schedule mode with the drafted cron and timezone', () => {
+ expect(
+ toScheduledCreateParams({
+ maxExecutions: null,
+ pattern: '30 8 * * 1,2,3',
+ timezone: 'Asia/Shanghai',
+ }),
+ ).toEqual({
+ automationMode: 'schedule',
+ config: undefined,
+ schedulePattern: '30 8 * * 1,2,3',
+ scheduleTimezone: 'Asia/Shanghai',
+ });
+ });
+
+ it('keeps other config and adds a run limit under config.schedule', () => {
+ const execution = { deviceId: 'dev_1' };
+
+ expect(
+ toScheduledCreateParams(
+ { maxExecutions: 5, pattern: '0 9 * * *', timezone: 'UTC' },
+ { execution },
+ ).config,
+ ).toEqual({ execution, schedule: { maxExecutions: 5 } });
+ });
+
+ it('leaves config untouched for a continuous schedule', () => {
+ const config = { execution: { deviceId: 'dev_1' } };
+
+ expect(
+ toScheduledCreateParams(
+ { maxExecutions: null, pattern: '0 9 * * *', timezone: 'UTC' },
+ config,
+ ).config,
+ ).toBe(config);
+ });
+});
diff --git a/src/features/AgentTasks/CreateTaskModal/scheduleDraft.ts b/src/features/AgentTasks/CreateTaskModal/scheduleDraft.ts
new file mode 100644
index 00000000000..1b187b9c594
--- /dev/null
+++ b/src/features/AgentTasks/CreateTaskModal/scheduleDraft.ts
@@ -0,0 +1,50 @@
+import type { TaskAutomationMode } from '@lobechat/types';
+
+/** The schedule a scheduled task is created with, before it exists to be updated. */
+export interface ScheduleDraft {
+ /** `null` = continuous, matching `tasks.config.schedule.maxExecutions`. */
+ maxExecutions: number | null;
+ pattern: string;
+ timezone: string;
+}
+
+// Same defaults the detail page writes when automation is first switched on.
+const DEFAULT_SCHEDULE_PATTERN = '0 9 * * *';
+
+const resolveLocalTimezone = (): string => {
+ try {
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
+ } catch {
+ return 'UTC';
+ }
+};
+
+export const createDefaultScheduleDraft = (): ScheduleDraft => ({
+ maxExecutions: null,
+ pattern: DEFAULT_SCHEDULE_PATTERN,
+ timezone: resolveLocalTimezone(),
+});
+
+/**
+ * The `task.create` fields that make the new task a live schedule; the server
+ * creates a schedule-mode task already `scheduled`. `maxExecutions` lives in
+ * the `config.schedule` pocket and is merged over any other config the form
+ * sends.
+ */
+export const toScheduledCreateParams = (
+ draft: ScheduleDraft,
+ config?: Record<string, unknown>,
+): {
+ automationMode: TaskAutomationMode;
+ config?: Record<string, unknown>;
+ schedulePattern: string;
+ scheduleTimezone: string;
+} => ({
+ automationMode: 'schedule',
+ config:
+ draft.maxExecutions === null
+ ? config
+ : { ...config, schedule: { maxExecutions: draft.maxExecutions } },
+ schedulePattern: draft.pattern,
+ scheduleTimezone: draft.timezone,
+});