🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(task): pick an exact minute for scheduled tasks (#22406)
Rdmclin22b4319e705e9
diff --git a/apps/server/src/router-hono/workflows/task/handlers/__tests__/scheduleDispatch.test.ts b/apps/server/src/router-hono/workflows/task/handlers/__tests__/scheduleDispatch.test.tsindex 686cd059b93..a741594fe83 100644--- a/apps/server/src/router-hono/workflows/task/handlers/__tests__/scheduleDispatch.test.ts+++ b/apps/server/src/router-hono/workflows/task/handlers/__tests__/scheduleDispatch.test.ts@@ -167,9 +167,103 @@ describe('scheduleDispatch', () => {});});+ describe('occurrences between ticks', () => {+ const armed = { scheduleStartedAt: '2026-09-21T08:55:00.000Z' };+ const preciseTask = (context: unknown, schedulePattern = '17 9 * * *') => ({+ ...dailyNineTask(context),+ schedulePattern,+ });++ beforeEach(() => {+ mocks.appEnv.enableQueueAgentRuntime = true;+ vi.stubEnv('APP_URL', 'https://example.com');+ mocks.swapDispatchedScheduleOccurrence.mockResolvedValue(true);+ mocks.publishJSON.mockResolvedValue({ messageId: 'm1' });+ });++ afterEach(() => {+ mocks.appEnv.enableQueueAgentRuntime = false;+ vi.unstubAllEnvs();+ });++ it('reserves the occurrence and delays its delivery to the exact minute', async () => {+ mocks.getScheduledTasks.mockResolvedValue([preciseTask({ scheduler: armed })]);++ expect(await dispatch(false)).toMatchObject({ dispatched: 1, due: 1 });+ expect(mocks.swapDispatchedScheduleOccurrence).toHaveBeenCalledWith(+ {},+ 'task-1',+ null,+ '2026-09-21T09:17:00.000Z',+ );+ expect(mocks.publishJSON).toHaveBeenCalledWith({+ body: { occurrence: '2026-09-21T09:17:00.000Z', taskId: 'task-1', userId: 'user-1' },+ notBefore: Date.UTC(2026, 8, 21, 9, 17) / 1000,+ url: 'https://example.com/api/workflows/task/schedule-execute',+ });+ });++ it('does not publish again on the tick after the reservation', async () => {+ vi.setSystemTime(new Date('2026-09-21T09:20:00.000Z'));+ mocks.getScheduledTasks.mockResolvedValue([+ preciseTask({+ scheduler: { ...armed, lastDispatchedOccurrenceAt: '2026-09-21T09:17:00.000Z' },+ }),+ ]);++ expect(await dispatch(false)).toMatchObject({ due: 0 });+ expect(mocks.publishJSON).not.toHaveBeenCalled();+ });++ it('fires an earlier time the schedule moved to, past the old reservation', async () => {+ vi.setSystemTime(new Date('2026-09-21T09:20:00.000Z'));+ mocks.getScheduledTasks.mockResolvedValue([+ preciseTask(+ { scheduler: { ...armed, lastDispatchedOccurrenceAt: '2026-09-21T09:17:00.000Z' } },+ '15 9 * * *',+ ),+ ]);++ expect(await dispatch(false)).toMatchObject({ dispatched: 1, due: 1 });+ expect(mocks.swapDispatchedScheduleOccurrence).toHaveBeenCalledWith(+ {},+ 'task-1',+ '2026-09-21T09:17:00.000Z',+ '2026-09-21T09:15:00.000Z',+ );+ });++ it('leaves an occurrence on the next tick to that tick', async () => {+ mocks.getScheduledTasks.mockResolvedValue([preciseTask({ scheduler: armed }, '20 9 * * *')]);++ expect(await dispatch(false)).toMatchObject({ due: 0 });+ expect(mocks.publishJSON).not.toHaveBeenCalled();+ });++ it('keeps a due occurrence undelayed', async () => {+ mocks.getScheduledTasks.mockResolvedValue([dailyNineTask({ scheduler: armed })]);++ await dispatch(false);++ expect(mocks.publishJSON).toHaveBeenCalledWith({+ body: { taskId: 'task-1', userId: 'user-1' },+ url: 'https://example.com/api/workflows/task/schedule-execute',+ });+ });+ });+describe('inline dispatch', () => {const armed = { scheduleStartedAt: '2026-09-21T08:55:00.000Z' };+ it('waits for the tick after an occurrence, since nothing can delay delivery', async () => {+ mocks.getScheduledTasks.mockResolvedValue([+ { ...dailyNineTask({ scheduler: armed }), schedulePattern: '17 9 * * *' },+ ]);++ expect(await dispatch(false)).toMatchObject({ due: 0 });+ expect(mocks.swapDispatchedScheduleOccurrence).not.toHaveBeenCalled();+ });+it('keeps the reservation when the tick succeeds', async () => {mocks.getScheduledTasks.mockResolvedValue([dailyNineTask({ scheduler: armed })]);mocks.swapDispatchedScheduleOccurrence.mockResolvedValue(true);diff --git a/apps/server/src/router-hono/workflows/task/handlers/scheduleDispatch.ts b/apps/server/src/router-hono/workflows/task/handlers/scheduleDispatch.tsindex ede863a9dc0..c7fb95da780 100644--- a/apps/server/src/router-hono/workflows/task/handlers/scheduleDispatch.ts+++ b/apps/server/src/router-hono/workflows/task/handlers/scheduleDispatch.ts@@ -1,4 +1,8 @@-import { findDueOccurrence } from '@lobechat/utils/cronEval';+import {+ findDueOccurrence,+ findUpcomingOccurrence,+ isCronOccurrence,+} from '@lobechat/utils/cronEval';import debug from 'debug';import type { Context } from 'hono';@@ -18,6 +22,8 @@ export interface ScheduleDispatchPayload {}interface DueTask {+ /** Set when the occurrence is still ahead: deliver it at that exact minute. */+ deliverAtOccurrence?: boolean;/** The cron occurrence (ISO) this dispatch fires. */occurrence: string;pattern: string;@@ -36,8 +42,10 @@ interface DueTask {** 1. Loads all schedule-mode tasks in dispatchable status (`scheduled`/`backlog`).* 2. Filters by cron pattern + timezone + last-run dedup (`findDueOccurrence`).- * 3. Reserves each due occurrence on the task row, then fans out one QStash- * message per reserved task to `/schedule-execute`.+ * In queue mode, an occurrence before the next tick is taken too+ * (`findUpcomingOccurrence`), so a time between ticks still fires on the minute.+ * 3. Reserves each occurrence on the task row, then fans out one QStash message+ * per reserved task to `/schedule-execute`, delayed for one still ahead.** No per-user authentication: this is a global sweep. Signature verification is* handled by the `qstashAuth` middleware on the route.@@ -66,16 +74,30 @@ export async function scheduleDispatch(c: Context) {// spans several ticks, so an occurrence whose delivery is still queued// is covered by the reservation made when it was dispatched.const previousOccurrence = scheduler?.lastDispatchedOccurrenceAt ?? null;- const coveredUntil = latest(task.lastHeartbeatAt, previousOccurrence);- const occurrence = findDueOccurrence({+ // A reservation can sit ahead of `now`. If the pattern has since changed it+ // no longer stands for a run of this schedule, so it must not swallow an+ // earlier occurrence of the new pattern.+ const reservationCurrent =+ !!previousOccurrence &&+ isCronOccurrence(task.schedulePattern, task.scheduleTimezone, new Date(previousOccurrence));+ const scan = {armedAt: scheduleStartedAt ? new Date(scheduleStartedAt) : null,cronPattern: task.schedulePattern,currentTime: now,- lastExecutedAt: coveredUntil,+ lastExecutedAt: latest(+ task.lastHeartbeatAt,+ reservationCurrent ? previousOccurrence : null,+ ),timezone: task.scheduleTimezone,- });+ };+ const dueOccurrence = findDueOccurrence(scan);+ // Only QStash can hold a message until the minute; inline mode fires on the next tick.+ const upcoming =+ !dueOccurrence && appEnv.enableQueueAgentRuntime ? findUpcomingOccurrence(scan) : null;+ const occurrence = dueOccurrence ?? upcoming;if (!occurrence) continue;due.push({+ deliverAtOccurrence: !!upcoming,occurrence: occurrence.toISOString(),pattern: task.schedulePattern,previousOccurrence,@@ -207,10 +229,15 @@ const fanout = async (db: ServerDB, due: DueTask[]): Promise<number> => {const results = await Promise.allSettled(due.map((d) =>- qstashClient.publishJSON({- body: { taskId: d.taskId, userId: d.userId },- url,- }),+ qstashClient.publishJSON(+ d.deliverAtOccurrence+ ? {+ body: { occurrence: d.occurrence, taskId: d.taskId, userId: d.userId },+ notBefore: Math.floor(new Date(d.occurrence).getTime() / 1000),+ url,+ }+ : { body: { taskId: d.taskId, userId: d.userId }, url },+ ),),);diff --git a/apps/server/src/router-hono/workflows/task/handlers/scheduleExecute.ts b/apps/server/src/router-hono/workflows/task/handlers/scheduleExecute.tsindex 7ea01f17983..40fd10cdaae 100644--- a/apps/server/src/router-hono/workflows/task/handlers/scheduleExecute.ts+++ b/apps/server/src/router-hono/workflows/task/handlers/scheduleExecute.ts@@ -6,6 +6,8 @@ import { runScheduleTick } from '@/server/services/taskRunner/scheduleTick';const log = debug('lobe-server:workflows:task:schedule-execute');export interface ScheduleExecutePayload {+ /** Present on a delayed delivery: the occurrence (ISO) it was reserved for. */+ occurrence?: string;taskId: string;userId: string;}@@ -18,13 +20,13 @@ export interface ScheduleExecutePayload {export async function scheduleExecute(c: Context) {try {const body = (await c.req.json()) as ScheduleExecutePayload;- const { taskId, userId } = body;+ const { occurrence, taskId, userId } = body;if (!taskId || !userId) {return c.json({ error: 'Missing required fields: taskId, userId' }, 400);}log('Received: taskId=%s userId=%s', taskId, userId);- const outcome = await runScheduleTick(taskId, userId);+ const outcome = await runScheduleTick(taskId, userId, { occurrence });return c.json({ success: true, ...outcome });} catch (error) {console.error('[task/schedule-execute] Error:', error);diff --git a/apps/server/src/routers/lambda/task/lifecycle.ts b/apps/server/src/routers/lambda/task/lifecycle.tsindex a8cc406beaf..b03148d23af 100644--- a/apps/server/src/routers/lambda/task/lifecycle.ts+++ b/apps/server/src/routers/lambda/task/lifecycle.ts@@ -13,6 +13,7 @@ import {taskOriginInputSchema,} from '@/server/services/task/originValidation';import {+ assertPreciseScheduleAllowed,assertResultingScheduleValid,schedulePatternSchema,scheduleTimezoneSchema,@@ -137,6 +138,11 @@ export const lifecycleRouter = router({});}assertResultingScheduleValid(null, createInput);+ await assertPreciseScheduleAllowed(+ { userId: ctx.userId, workspaceId: ctx.workspaceId },+ null,+ createInput.schedulePattern,+ );const labelModel = new TaskLabelModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);if (labelIds?.length) {// Reject unknown / group / conflicting labels before anything is written.diff --git a/apps/server/src/services/task/patchValidation.ts b/apps/server/src/services/task/patchValidation.tsindex 018b434518f..f319706de7e 100644--- a/apps/server/src/services/task/patchValidation.ts+++ b/apps/server/src/services/task/patchValidation.ts@@ -11,7 +11,7 @@ import type { TaskService } from '@/server/services/task';import { assertArchivedTaskStaysIdle } from './archiveGuard';import { assertTaskOriginPatchAllowed } from './originValidation';-import { assertResultingScheduleValid } from './scheduleValidation';+import { assertPreciseScheduleAllowed, assertResultingScheduleValid } from './scheduleValidation';import { findTaskOrThrow, resolveTaskOrThrow } from './utils';/**@@ -187,6 +187,11 @@ export async function resolveTaskPatchInvariants<Data extends TaskPatchFields>(const resolved = await resolveTaskOrThrow(ctx.taskModel, id);assertResultingScheduleValid(resolved, data);+ await assertPreciseScheduleAllowed(+ { userId: ctx.userId, workspaceId: ctx.workspaceId },+ resolved.schedulePattern,+ data.schedulePattern,+ );assertArchivedTaskStaysIdle(resolved, data);// `context` replaces the whole column, origin included: a changed origin// must point at the caller's own conversation like it must at create time.diff --git a/apps/server/src/services/task/scheduleValidation.test.ts b/apps/server/src/services/task/scheduleValidation.test.tsnew file mode 100644index 00000000000..5a1c61428e7--- /dev/null+++ b/apps/server/src/services/task/scheduleValidation.test.ts@@ -0,0 +1,50 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { assertPreciseScheduleAllowed } from './scheduleValidation';++const { checkPreciseScheduleAccess } = vi.hoisted(() => ({+ checkPreciseScheduleAccess: vi.fn(),+}));++vi.mock('@/business/server/task/preciseSchedule', () => ({ checkPreciseScheduleAccess }));++const actor = { userId: 'user-1', workspaceId: 'ws-1' };++describe('assertPreciseScheduleAllowed', () => {+ beforeEach(() => {+ checkPreciseScheduleAccess.mockReset();+ checkPreciseScheduleAccess.mockResolvedValue({ allowed: false, message: 'upgrade to pick' });+ });++ it('refuses a new exact minute with the deployment message', async () => {+ await expect(assertPreciseScheduleAllowed(actor, null, '17 9 * * *')).rejects.toMatchObject({+ code: 'PRECONDITION_FAILED',+ message: 'upgrade to pick',+ });+ expect(checkPreciseScheduleAccess).toHaveBeenCalledWith(actor);+ });++ it('refuses changing to a different exact minute', async () => {+ await expect(+ assertPreciseScheduleAllowed(actor, '17 9 * * *', '18 9 * * *'),+ ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });+ });++ it('passes when access is allowed', async () => {+ checkPreciseScheduleAccess.mockResolvedValue({ allowed: true });++ await expect(assertPreciseScheduleAllowed(actor, null, '17 9 * * *')).resolves.toBeUndefined();+ });++ it.each([+ ['a standard minute', '30 9 * * *', null],+ ['an interval', '*/15 * * * *', null],+ ['a cleared pattern', null, '17 9 * * *'],+ ['an untouched pattern', undefined, '17 9 * * *'],+ ['the stored minute on another hour or weekday', '17 10 * * 1', '17 9 * * *'],+ ])('does not check the plan for %s', async (_name, next, stored) => {+ await expect(assertPreciseScheduleAllowed(actor, stored, next)).resolves.toBeUndefined();+ expect(checkPreciseScheduleAccess).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/task/scheduleValidation.ts b/apps/server/src/services/task/scheduleValidation.tsindex e815f44fded..656c0cd7661 100644--- a/apps/server/src/services/task/scheduleValidation.ts+++ b/apps/server/src/services/task/scheduleValidation.ts@@ -1,4 +1,6 @@import {+ hasSameScheduleMinute,+ isPreciseSchedulePattern,isValidTimezone,validateCronPattern,validateScheduleUpdate,@@ -6,6 +8,8 @@ import {import { TRPCError } from '@trpc/server';import { z } from 'zod';+import { checkPreciseScheduleAccess } from '@/business/server/task/preciseSchedule';+/*** Write-time schedule validation, shared by every boundary that can create or* patch a task: the tRPC router the in-app surfaces call and the REST routes@@ -55,3 +59,22 @@ export function assertResultingScheduleValid(throw new TRPCError({ code: 'BAD_REQUEST', message: `Invalid schedule: ${result.error}` });}}++/**+ * Enforce a deployment's plan rule for custom exact times at every write+ * boundary. Only picking a new exact minute is checked: a schedule that already+ * has one keeps running and stays editable after a downgrade.+ */+export async function assertPreciseScheduleAllowed(+ actor: { userId: string; workspaceId?: string | null },+ storedPattern: string | null | undefined,+ nextPattern: string | null | undefined,+) {+ if (!nextPattern || !isPreciseSchedulePattern(nextPattern)) return;+ if (storedPattern && hasSameScheduleMinute(storedPattern, nextPattern)) return;++ const access = await checkPreciseScheduleAccess(actor);+ if (!access.allowed) {+ throw new TRPCError({ code: 'PRECONDITION_FAILED', message: access.message });+ }+}diff --git a/apps/server/src/services/taskRunner/scheduleTick.test.ts b/apps/server/src/services/taskRunner/scheduleTick.test.tsindex 6e16ea4821c..98b6d624864 100644--- a/apps/server/src/services/taskRunner/scheduleTick.test.ts+++ b/apps/server/src/services/taskRunner/scheduleTick.test.ts@@ -213,4 +213,22 @@ describe('runScheduleTick', () => {});expect(mockRunner.runTask).not.toHaveBeenCalled();});++ describe('delayed delivery', () => {+ const task = {+ automationMode: 'schedule',+ schedulePattern: '15 9 * * *',+ scheduleTimezone: 'UTC',+ status: 'scheduled',+ };++ it('skips an occurrence the schedule no longer includes', async () => {+ mockSelectTask.mockResolvedValue([task]);++ await expect(+ runScheduleTick(taskId, userId, { occurrence: '2026-09-21T09:17:00.000Z' }),+ ).resolves.toEqual({ ran: false, reason: 'schedule-changed' });+ expect(mockRunner.runTask).not.toHaveBeenCalled();+ });+ });});diff --git a/apps/server/src/services/taskRunner/scheduleTick.ts b/apps/server/src/services/taskRunner/scheduleTick.tsindex 6dc4ecedf81..a0db430932f 100644--- a/apps/server/src/services/taskRunner/scheduleTick.ts+++ b/apps/server/src/services/taskRunner/scheduleTick.ts@@ -1,3 +1,4 @@+import { isCronOccurrence } from '@lobechat/utils/cronEval';import { TRPCError } from '@trpc/server';import debug from 'debug';import { and, eq } from 'drizzle-orm';@@ -28,6 +29,7 @@ export type ScheduleTickSkipReason =| 'no-pattern'| 'not-found'| 'paused'+ | 'schedule-changed'| 'terminal';/**@@ -40,6 +42,7 @@ export type ScheduleTickSkipReason =export async function runScheduleTick(taskId: string,userId: string,+ options: { occurrence?: string } = {},): Promise<ScheduleTickOutcome> {const db = await getServerDB();@@ -72,6 +75,15 @@ export async function runScheduleTick(log('skip task=%s reason=no-pattern', taskId);return { ran: false, reason: 'no-pattern' };}+ // A delayed delivery was reserved before it fires; the user may have moved the+ // schedule since, and the new time is dispatched on its own.+ if (+ options.occurrence &&+ !isCronOccurrence(task.schedulePattern, task.scheduleTimezone, new Date(options.occurrence))+ ) {+ log('skip task=%s reason=schedule-changed (occurrence=%s)', taskId, options.occurrence);+ return { ran: false, reason: 'schedule-changed' };+ }if (isTerminal(task.status)) {log('skip task=%s reason=terminal (status=%s)', taskId, task.status);return { ran: false, reason: 'terminal' };diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex d30fb8d54a2..f0364b03c46 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -2888,6 +2888,8 @@"taskSchedule.advancedSettings": "Advanced settings","taskSchedule.clear": "Clear","taskSchedule.continuous": "Continuous",+ "taskSchedule.customMinute": "Custom",+ "taskSchedule.customMinute.badge": "Pro","taskSchedule.enable": "Enable automation","taskSchedule.every": "Every","taskSchedule.frequency": "Frequency",@@ -2910,9 +2912,11 @@"taskSchedule.summary.daily": "Daily at {{time}}","taskSchedule.summary.disabled": "Automation is off","taskSchedule.summary.everyNHours": "Every {{count}} hours",+ "taskSchedule.summary.everyNHoursAtMinute": "Every {{count}} hours at :{{minute}}","taskSchedule.summary.everyNHoursHalfPast": "Every {{count}} hours at half past","taskSchedule.summary.heartbeat": "Runs every {{interval}}","taskSchedule.summary.hourly": "Every hour",+ "taskSchedule.summary.hourlyAtMinute": "Every hour at :{{minute}}","taskSchedule.summary.hourlyHalfPast": "Every hour at half past","taskSchedule.summary.weekly": "Every {{days}} at {{time}}","taskSchedule.tag.add": "Set schedule",diff --git a/locales/en-US/subscription.json b/locales/en-US/subscription.jsonindex cd77268878b..e63a356e0f7 100644--- a/locales/en-US/subscription.json+++ b/locales/en-US/subscription.json@@ -685,6 +685,8 @@"plansModal.modelAccess.title": "Unlock all models","plansModal.persistentSandbox.desc": "Files your agent writes in the cloud sandbox are discarded when the session ends. Upgrade to keep a persistent working directory that survives sessions and is shared across your topics.","plansModal.persistentSandbox.title": "Keep your sandbox files",+ "plansModal.preciseSchedule.desc": "Run scheduled tasks at any exact minute, not only on the hour or half hour. Upgrade to a paid plan to pick your own time.",+ "plansModal.preciseSchedule.title": "Schedule tasks at an exact time","plansModal.ultraModelAccess.desc": "Ultra models are the most capable and most expensive ones, available on Pro and above. Upgrade to use them.","plansModal.ultraModelAccess.title": "Ultra models need Pro or above","qa.desc": "If your question is not answered, check <1>Product Documentation</1> for more FAQs, or contact us.",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 7d24b3a89d8..e21a1ce2c82 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -2888,6 +2888,8 @@"taskSchedule.advancedSettings": "高级设置","taskSchedule.clear": "清除","taskSchedule.continuous": "持续运行",+ "taskSchedule.customMinute": "自定义",+ "taskSchedule.customMinute.badge": "Pro","taskSchedule.enable": "启用自动化","taskSchedule.every": "每","taskSchedule.frequency": "运行频率",@@ -2910,9 +2912,11 @@"taskSchedule.summary.daily": "每天 {{time}} 运行","taskSchedule.summary.disabled": "自动化未启用","taskSchedule.summary.everyNHours": "每 {{count}} 小时",+ "taskSchedule.summary.everyNHoursAtMinute": "每 {{count}} 小时的 {{minute}} 分","taskSchedule.summary.everyNHoursHalfPast": "每 {{count}} 小时的 30 分","taskSchedule.summary.heartbeat": "每 {{interval}} 运行一次","taskSchedule.summary.hourly": "每小时",+ "taskSchedule.summary.hourlyAtMinute": "每小时的 {{minute}} 分","taskSchedule.summary.hourlyHalfPast": "每小时的 30 分","taskSchedule.summary.weekly": "每周 {{days}} {{time}} 运行","taskSchedule.tag.add": "设置计划",diff --git a/locales/zh-CN/subscription.json b/locales/zh-CN/subscription.jsonindex c8fdd18dc86..efd361c4e7a 100644--- a/locales/zh-CN/subscription.json+++ b/locales/zh-CN/subscription.json@@ -685,6 +685,8 @@"plansModal.modelAccess.title": "解锁全部模型","plansModal.persistentSandbox.desc": "云端沙箱里写下的文件会在会话结束后丢弃。升级后可获得持久化工作目录,跨会话保留、并在各个话题间共享。","plansModal.persistentSandbox.title": "保留沙箱中的文件",+ "plansModal.preciseSchedule.desc": "定时任务可以设置到具体的每一分钟,不再限于整点和半点。升级到付费套餐后即可自定义时间。",+ "plansModal.preciseSchedule.title": "让任务在精确时间运行","plansModal.ultraModelAccess.desc": "Ultra 模型能力最强、成本最高,Pro 及以上套餐可用。升级后即可使用。","plansModal.ultraModelAccess.title": "Ultra 模型需要 Pro 及以上套餐","qa.desc": "如果你的问题未被解答,请查看<1>产品文档</1>获取更多常见问题,或联系我们。",diff --git a/packages/business-server/src/task/preciseSchedule.ts b/packages/business-server/src/task/preciseSchedule.tsnew file mode 100644index 00000000000..0ee461f6d49--- /dev/null+++ b/packages/business-server/src/task/preciseSchedule.ts@@ -0,0 +1,15 @@+export interface CheckPreciseScheduleAccessParams {+ userId: string;+ workspaceId?: string | null;+}++export type CheckPreciseScheduleAccessResult =+ { allowed: false; message: string } | { allowed: true };++/**+ * Decides whether a task schedule may pin a custom exact minute. The default+ * always allows it; a deployment with plan rules overrides it.+ */+export const checkPreciseScheduleAccess = async (+ _params: CheckPreciseScheduleAccessParams,+): Promise<CheckPreciseScheduleAccessResult> => ({ allowed: true });diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex c82694883c1..ccb46160d56 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -2014,6 +2014,8 @@ export default {'taskSchedule.advancedSettings': 'Advanced settings','taskSchedule.clear': 'Clear','taskSchedule.continuous': 'Continuous',+ 'taskSchedule.customMinute': 'Custom',+ 'taskSchedule.customMinute.badge': 'Pro','taskSchedule.enable': 'Enable automation','taskSchedule.every': 'Every','taskSchedule.frequency': 'Frequency',@@ -2036,9 +2038,11 @@ export default {'taskSchedule.summary.daily': 'Daily at {{time}}','taskSchedule.summary.disabled': 'Automation is off','taskSchedule.summary.everyNHours': 'Every {{count}} hours',+ 'taskSchedule.summary.everyNHoursAtMinute': 'Every {{count}} hours at :{{minute}}','taskSchedule.summary.everyNHoursHalfPast': 'Every {{count}} hours at half past','taskSchedule.summary.heartbeat': 'Runs every {{interval}}','taskSchedule.summary.hourly': 'Every hour',+ 'taskSchedule.summary.hourlyAtMinute': 'Every hour at :{{minute}}','taskSchedule.summary.hourlyHalfPast': 'Every hour at half past','taskSchedule.summary.weekly': 'Every {{days}} at {{time}}','taskSchedule.tag.add': 'Set schedule',diff --git a/packages/locales/src/default/subscription.ts b/packages/locales/src/default/subscription.tsindex 03f015ce441..23979299cd2 100644--- a/packages/locales/src/default/subscription.ts+++ b/packages/locales/src/default/subscription.ts@@ -748,6 +748,9 @@ export default {'plansModal.persistentSandbox.desc':'Files your agent writes in the cloud sandbox are discarded when the session ends. Upgrade to keep a persistent working directory that survives sessions and is shared across your topics.','plansModal.persistentSandbox.title': 'Keep your sandbox files',+ 'plansModal.preciseSchedule.desc':+ 'Run scheduled tasks at any exact minute, not only on the hour or half hour. Upgrade to a paid plan to pick your own time.',+ 'plansModal.preciseSchedule.title': 'Schedule tasks at an exact time','plansModal.artifactDeploymentLimit.desc':'Your Artifact hosting capacity has been reached. Upgrade to increase active deployments and per-site size limits.','plansModal.artifactDeploymentLimit.title': 'Increase Artifact hosting capacity',diff --git a/packages/openapi/src/services/task.service.ts b/packages/openapi/src/services/task.service.tsindex 74a4f350377..f15508e48fa 100644--- a/packages/openapi/src/services/task.service.ts+++ b/packages/openapi/src/services/task.service.ts@@ -8,7 +8,10 @@ import { EditLockService } from '@/server/services/editLock';import { TaskService } from '@/server/services/task';import { notifyAssignedBestEffort } from '@/server/services/task/assignmentNotification';import { resolveTaskPatchInvariants } from '@/server/services/task/patchValidation';-import { assertResultingScheduleValid } from '@/server/services/task/scheduleValidation';+import {+ assertPreciseScheduleAllowed,+ assertResultingScheduleValid,+} from '@/server/services/task/scheduleValidation';import { normalizeTaskConfig, resolveTaskOrThrow } from '@/server/services/task/utils';import { TaskRunnerService } from '@/server/services/taskRunner';@@ -93,6 +96,11 @@ export class TaskRestService extends BaseService {// create boundary, so a schedule the dispatcher cannot evaluate is refused// here instead of being stored and silently never firing.assertResultingScheduleValid(null, input);+ await assertPreciseScheduleAllowed(+ { userId: this.userId, workspaceId: this.workspaceId },+ null,+ input.schedulePattern,+ );const task = await this.taskService.createTask({...input,config: await normalizeTaskConfig(this.taskModel, input.config),diff --git a/packages/utils/src/cronEval.test.ts b/packages/utils/src/cronEval.test.tsindex c4b37f29acd..80a76f6724f 100644--- a/packages/utils/src/cronEval.test.ts+++ b/packages/utils/src/cronEval.test.ts@@ -2,7 +2,12 @@ import { describe, expect, it } from 'vitest';import {findDueOccurrence,+ findUpcomingOccurrence,+ hasSameScheduleMinute,+ isCronOccurrence,isExecutionTime,+ isPreciseSchedulePattern,+ snapScheduleToStandardMinute,validateCronPattern,validateScheduleUpdate,} from './cronEval';@@ -480,3 +485,99 @@ describe('validateScheduleUpdate', () => {expect(validateScheduleUpdate(null, { scheduleTimezone: null })).toBeUndefined();});});++describe('findUpcomingOccurrence', () => {+ const at = (currentTime: string, cronPattern: string, extra = {}) =>+ findUpcomingOccurrence({+ cronPattern,+ currentTime: utc(currentTime),+ timezone: 'UTC',+ ...extra,+ });++ it('finds an occurrence before the next tick', () => {+ expect(at('2026-09-21T09:10:00', '17 9 * * *')).toEqual(utc('2026-09-21T09:17:00'));+ });++ it('honors the pattern timezone', () => {+ expect(+ findUpcomingOccurrence({+ cronPattern: '17 9 * * *',+ currentTime: utc('2026-09-21T01:10:00'),+ timezone: SHANGHAI,+ }),+ ).toEqual(utc('2026-09-21T01:17:00'));+ });++ it('leaves the next tick boundary to that tick', () => {+ expect(at('2026-09-21T09:10:00', '20 9 * * *')).toBeNull();+ });++ it('ignores an occurrence after the next tick', () => {+ expect(at('2026-09-21T09:10:00', '25 9 * * *')).toBeNull();+ });++ it('does not take the current minute again', () => {+ expect(at('2026-09-21T09:17:00', '17 9 * * *')).toBeNull();+ });++ it('skips an occurrence already covered', () => {+ expect(+ at('2026-09-21T09:10:00', '17 9 * * *', { lastExecutedAt: utc('2026-09-21T09:17:00') }),+ ).toBeNull();+ });++ it('never fires an invalid pattern', () => {+ expect(at('2026-09-21T09:10:00', 'not a cron')).toBeNull();+ });+});++describe('isCronOccurrence', () => {+ it('matches only instants of the pattern in its timezone', () => {+ expect(isCronOccurrence('17 9 * * *', SHANGHAI, utc('2026-09-21T01:17:00'))).toBe(true);+ expect(isCronOccurrence('17 9 * * *', 'UTC', utc('2026-09-21T01:17:00'))).toBe(false);+ });++ it('treats invalid input as no occurrence', () => {+ expect(isCronOccurrence('nope', 'UTC', utc('2026-09-21T01:17:00'))).toBe(false);+ expect(isCronOccurrence('17 9 * * *', 'UTC', new Date('invalid'))).toBe(false);+ });+});++describe('isPreciseSchedulePattern', () => {+ it.each(['0 9 * * *', '30 9 * * *', '00 9 * * *', '0,30 * * * *', '* * * * *', '*/15 * * * *'])(+ 'does not count %s',+ (pattern) => {+ expect(isPreciseSchedulePattern(pattern)).toBe(false);+ },+ );++ it.each(['17 9 * * *', '0,17 9 * * *', '17-17 9 * * *', '17/60 9 * * *', '59 * * * *'])(+ 'counts %s',+ (pattern) => {+ expect(isPreciseSchedulePattern(pattern)).toBe(true);+ },+ );+});++describe('hasSameScheduleMinute', () => {+ it('compares only the minute field', () => {+ expect(hasSameScheduleMinute('17 9 * * *', ' 17 10 * * 1')).toBe(true);+ expect(hasSameScheduleMinute('17 9 * * *', '18 9 * * *')).toBe(false);+ });+});++describe('snapScheduleToStandardMinute', () => {+ it.each([+ ['17 9 * * 1', '30 9 * * 1'],+ ['14 9 * * *', '0 9 * * *'],+ ['45 9 * * *', '0 9 * * *'],+ ])('moves %s to %s', (pattern, expected) => {+ expect(snapScheduleToStandardMinute(pattern)).toBe(expected);+ });++ it('leaves standard and interval patterns alone', () => {+ expect(snapScheduleToStandardMinute('30 9 * * *')).toBe('30 9 * * *');+ expect(snapScheduleToStandardMinute('*/15 * * * *')).toBe('*/15 * * * *');+ });+});diff --git a/packages/utils/src/cronEval.ts b/packages/utils/src/cronEval.tsindex bcea488695b..1b8aebf9a87 100644--- a/packages/utils/src/cronEval.ts+++ b/packages/utils/src/cronEval.ts@@ -129,6 +129,89 @@ export const findDueOccurrence = (input: IsExecutionTimeInput): Date | null => {return new Date(prev);};+export type FindUpcomingOccurrenceInput = Omit<IsExecutionTimeInput, 'graceMinutes'>;++/**+ * Find the occurrence that falls strictly between this dispatcher tick and the+ * next one, or `null`. Such an occurrence would otherwise fire up to one+ * interval late, so the dispatcher reserves it now and delays its delivery to+ * the exact minute. An occurrence on a tick boundary is left to that tick.+ */+export const findUpcomingOccurrence = (input: FindUpcomingOccurrenceInput): Date | null => {+ const { armedAt, cronPattern, currentTime = new Date(), lastExecutedAt, timezone } = input;++ let expression: ReturnType<typeof parseCron>;+ try {+ expression = parseCron(cronPattern, timezone, currentTime);+ } catch {+ return null;+ }++ const now = currentTime.getTime();+ const intervalMs = SCHEDULE_DISPATCH_INTERVAL_MINUTES * MINUTE_MS;+ const nextTick = (Math.floor(now / intervalMs) + 1) * intervalMs;++ for (+ let candidate = (Math.floor(now / MINUTE_MS) + 1) * MINUTE_MS;+ candidate < nextTick;+ candidate += MINUTE_MS+ ) {+ if (!expression.includesDate(new Date(candidate))) continue;+ if (armedAt && new Date(armedAt).getTime() > candidate) return null;+ if (lastExecutedAt && new Date(lastExecutedAt).getTime() >= candidate) return null;+ return new Date(candidate);+ }++ return null;+};++/** Whether `date` is an occurrence of the pattern. Invalid input is never one. */+export const isCronOccurrence = (+ cronPattern: string,+ timezone: string | null,+ date: Date,+): boolean => {+ if (Number.isNaN(date.getTime())) return false;+ try {+ return parseCron(cronPattern, timezone, date).includesDate(date);+ } catch {+ return false;+ }+};++const STANDARD_SCHEDULE_MINUTES = new Set([0, 30]);++const getCronMinuteField = (cronPattern: string): string => cronPattern.trim().split(/\s+/)[0];++/**+ * Whether a pattern pins a clock minute other than :00 / :30, the custom exact+ * time a deployment may reserve for paid plans. Every-minute and `*\/N` interval+ * patterns repeat rather than pick a time, so they do not count.+ */+export const isPreciseSchedulePattern = (cronPattern: string): boolean => {+ const minute = getCronMinuteField(cronPattern);+ if (!minute || minute === '*' || /^\*\/\d+$/.test(minute)) return false;++ return !minute+ .split(',')+ .every((item) => /^\d+$/.test(item) && STANDARD_SCHEDULE_MINUTES.has(Number(item)));+};++/** Whether two patterns keep the same minute field, so an edit picks no new exact time. */+export const hasSameScheduleMinute = (a: string, b: string): boolean =>+ getCronMinuteField(a) === getCronMinuteField(b);++/** Move a precise pattern to the nearest of :00 / :30 in its hour; others pass through. */+export const snapScheduleToStandardMinute = (cronPattern: string): string => {+ if (!isPreciseSchedulePattern(cronPattern)) return cronPattern;++ const [minute, ...rest] = cronPattern.trim().split(/\s+/);+ const raw = Number.parseInt(minute, 10);+ const snapped = raw >= 15 && raw < 45 ? 30 : 0;++ return [snapped, ...rest].join(' ');+};+/** Whether `findDueOccurrence` finds an occurrence to fire on this tick. */export const isExecutionTime = (input: IsExecutionTimeInput): boolean =>findDueOccurrence(input) !== null;diff --git a/src/business/client/hooks/useBusinessPreciseSchedule.ts b/src/business/client/hooks/useBusinessPreciseSchedule.tsnew file mode 100644index 00000000000..3c04693f2a7--- /dev/null+++ b/src/business/client/hooks/useBusinessPreciseSchedule.ts@@ -0,0 +1,12 @@+export interface BusinessPreciseSchedule {+ /** Whether a task schedule may pick any exact minute, not only :00 / :30. */+ allowed: boolean;+ /** Opens the deployment's upgrade flow from the locked custom-minute option. */+ onUpgrade?: () => void;+}++/**+ * Lets a deployment reserve custom exact schedule times for some plans. The+ * default offers them to everyone.+ */+export const useBusinessPreciseSchedule = (): BusinessPreciseSchedule => ({ allowed: true });diff --git a/src/features/AgentTasks/AgentTaskDetail/scheduler/CronConfig.test.ts b/src/features/AgentTasks/AgentTaskDetail/scheduler/CronConfig.test.tsnew file mode 100644index 00000000000..31be2c282ac--- /dev/null+++ b/src/features/AgentTasks/AgentTaskDetail/scheduler/CronConfig.test.ts@@ -0,0 +1,77 @@+import dayjs from 'dayjs';+import { describe, expect, it } from 'vitest';++import { buildCronPattern, getMinuteChoices, parseCronPattern } from './CronConfig';+import { formatScheduleDescription } from './helpers';++const time = (hour: number, minute: number) => dayjs().hour(hour).minute(minute);++describe('buildCronPattern', () => {+ it('keeps the exact minute for every frequency', () => {+ expect(buildCronPattern('daily', time(9, 17))).toBe('17 9 * * *');+ expect(buildCronPattern('weekly', time(9, 17), undefined, [1, 3])).toBe('17 9 * * 1,3');+ expect(buildCronPattern('hourly', time(0, 45))).toBe('45 * * * *');+ expect(buildCronPattern('hourly', time(0, 15), 2)).toBe('15 */2 * * *');+ });+});++describe('parseCronPattern', () => {+ it('reads the exact minute back', () => {+ expect(parseCronPattern('17 9 * * *')).toMatchObject({+ scheduleType: 'daily',+ triggerHour: 9,+ triggerMinute: 17,+ });+ expect(parseCronPattern('45 */2 * * *')).toMatchObject({+ hourlyInterval: 2,+ triggerMinute: 45,+ });+ });++ it('treats interval and any-minute fields as no fixed minute', () => {+ expect(parseCronPattern('*/15 * * * *').triggerMinute).toBe(0);+ expect(parseCronPattern('* 9 * * *').triggerMinute).toBe(0);+ });+});++describe('getMinuteChoices', () => {+ it('offers every minute with access', () => {+ const choices = getMinuteChoices(true, 0);+ expect(choices).toHaveLength(60);+ expect(choices[59]).toBe(59);+ });++ it('offers the standard minutes without access', () => {+ expect(getMinuteChoices(false, 30)).toEqual([0, 30]);+ });++ it('keeps a stored exact minute visible without access', () => {+ expect(getMinuteChoices(false, 17)).toEqual([0, 17, 30]);+ });+});++describe('formatScheduleDescription', () => {+ const t = ((key: string, options?: Record<string, unknown>) =>+ options ? `${key}:${JSON.stringify(options)}` : key) as never;++ it('names the exact time for daily and weekly schedules', () => {+ expect(formatScheduleDescription('17 9 * * *', t)).toBe(+ 'taskSchedule.summary.daily:{"time":"09:17"}',+ );+ expect(formatScheduleDescription('5 9 * * 1', t)).toContain('"time":"09:05"');+ });++ it('names an exact minute for hourly schedules', () => {+ expect(formatScheduleDescription('5 * * * *', t)).toBe(+ 'taskSchedule.summary.hourlyAtMinute:{"minute":"05"}',+ );+ expect(formatScheduleDescription('45 */2 * * *', t)).toBe(+ 'taskSchedule.summary.everyNHoursAtMinute:{"count":2,"minute":"45"}',+ );+ });++ it('keeps the existing wording for :00 and :30', () => {+ expect(formatScheduleDescription('0 * * * *', t)).toBe('taskSchedule.summary.hourly');+ expect(formatScheduleDescription('30 * * * *', t)).toBe('taskSchedule.summary.hourlyHalfPast');+ });+});diff --git a/src/features/AgentTasks/AgentTaskDetail/scheduler/CronConfig.ts b/src/features/AgentTasks/AgentTaskDetail/scheduler/CronConfig.tsindex c69795e7594..2e7300b04d4 100644--- a/src/features/AgentTasks/AgentTaskDetail/scheduler/CronConfig.ts+++ b/src/features/AgentTasks/AgentTaskDetail/scheduler/CronConfig.ts@@ -76,6 +76,20 @@ export const WEEKDAYS = [{ key: 0, label: 'taskSchedule.weekdays.sun' },] as const;+/** Minutes every plan can pick; any other exact minute is the gated custom time. */+export const STANDARD_MINUTES = [0, 30] as const;++/**+ * The minutes a picker offers. Without custom-time access it stays on the+ * standard ones plus the value already stored, so a schedule set before a+ * downgrade (or by an agent) still reads back as it runs.+ */+export const getMinuteChoices = (canUseCustomMinute: boolean, currentMinute: number): number[] => {+ if (canUseCustomMinute) return Array.from({ length: 60 }, (_, minute) => minute);++ return [...new Set<number>([...STANDARD_MINUTES, currentMinute])].sort((a, b) => a - b);+};+/*** Parse cron pattern (minute hour day month weekday) into editable schedule info.*/@@ -95,7 +109,8 @@ export const parseCronPattern = (const [minute, hour, , , weekday] = parts;const rawMinute = minute === '*' ? 0 : Number.parseInt(minute);- const triggerMinute = rawMinute >= 15 && rawMinute < 45 ? 30 : 0;+ // Interval minutes such as `*/15` pin no clock minute.+ const triggerMinute = Number.isNaN(rawMinute) ? 0 : rawMinute;if (hour.startsWith('*/')) {const interval = Number.parseInt(hour.slice(2));@@ -124,8 +139,7 @@ export const buildCronPattern = (hourlyInterval?: number,weekdays?: number[],): string => {- const rawMinute = triggerTime.minute();- const minute = rawMinute >= 15 && rawMinute < 45 ? 30 : 0;+ const minute = triggerTime.minute();const hour = triggerTime.hour();switch (scheduleType) {diff --git a/src/features/AgentTasks/AgentTaskDetail/scheduler/SchedulerForm.tsx b/src/features/AgentTasks/AgentTaskDetail/scheduler/SchedulerForm.tsxindex 6e47612941e..2ee30875d0c 100644--- a/src/features/AgentTasks/AgentTaskDetail/scheduler/SchedulerForm.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/scheduler/SchedulerForm.tsx@@ -7,6 +7,7 @@ import {Icon,InputNumber,Select,+ Tag,Text,ToggleGroup,} from '@lobehub/ui';@@ -15,8 +16,11 @@ import { Globe, Hash, SlidersHorizontal } from 'lucide-react';import { memo, useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';+import { useBusinessPreciseSchedule } from '@/business/client/hooks/useBusinessPreciseSchedule';+import {buildCronPattern,+ getMinuteChoices,parseCronPattern,SCHEDULE_TYPE_OPTIONS,type ScheduleType,@@ -49,15 +53,12 @@ const styles = createStaticStyles(({ css, cssVar }) => ({const DEFAULT_PATTERN = '0 9 * * *';const DEFAULT_TIMEZONE = 'UTC';-// Cron storage rounds minutes to 0 or 30 (see buildCronPattern), so the picker-// only needs to offer half-hour slots — flatten to a single column instead of-// antd's hour×minute grid.-const TIME_OPTIONS = Array.from({ length: 48 }, (_, i) => {- const hour = Math.floor(i / 2);- const minute = i % 2 === 0 ? 0 : 30;- const label = `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`;- return { label, value: hour * 60 + minute };-});+const pad = (n: number) => String(n).padStart(2, '0');++const HOUR_OPTIONS = Array.from({ length: 24 }, (_, hour) => ({ label: pad(hour), value: hour }));++/** Sentinel minute option that opens the upgrade flow instead of changing the value. */+const CUSTOM_MINUTE_UPGRADE = -1;export interface SchedulerFormChange {maxExecutions: number | null;@@ -74,6 +75,7 @@ interface SchedulerFormProps {const SchedulerForm = memo<SchedulerFormProps>(({ maxExecutions, onChange, pattern, timezone }) => {const { t } = useTranslation('chat');+ const { allowed: canUseCustomMinute, onUpgrade } = useBusinessPreciseSchedule();const weekdayOptions = useMemo(() => WEEKDAYS.map(({ key, label }) => ({ label: t(label as any), value: String(key) })),@@ -155,16 +157,18 @@ const SchedulerForm = memo<SchedulerFormProps>(({ maxExecutions, onChange, patteemit({ scheduleType: value, weekdays: nextWeekdays });};- const handleTimeChange = (totalMinutes: number) => {- const next = dayjs()- .hour(Math.floor(totalMinutes / 60))- .minute(totalMinutes % 60);+ const handleHourChange = (hour: number) => {+ const next = triggerTime.hour(hour);setTriggerTime(next);emit({ triggerTime: next });};- const handleHourlyMinuteChange = (minute: number) => {- const next = dayjs().hour(0).minute(minute);+ const handleMinuteChange = (minute: number) => {+ if (minute === CUSTOM_MINUTE_UPGRADE) {+ onUpgrade?.();+ return;+ }+ const next = triggerTime.minute(minute);setTriggerTime(next);emit({ triggerTime: next });};@@ -210,6 +214,38 @@ const SchedulerForm = memo<SchedulerFormProps>(({ maxExecutions, onChange, patteconst showTimeRow = scheduleType !== 'hourly';+ const minuteSelect = (+ <Select+ popupMatchSelectWidth={false}+ showSearch={canUseCustomMinute}+ style={{ flexShrink: 0, width: 80 }}+ value={triggerTime.minute()}+ variant="filled"+ options={[+ ...getMinuteChoices(canUseCustomMinute, triggerTime.minute()).map((minute) => ({+ label: `:${pad(minute)}`,+ value: minute,+ })),+ ...(canUseCustomMinute+ ? []+ : [+ {+ label: (+ <Flexbox horizontal align="center" gap={8}>+ {t('taskSchedule.customMinute')}+ <Tag color="gold" size="small" style={{ marginInlineEnd: 0 }}>+ {t('taskSchedule.customMinute.badge')}+ </Tag>+ </Flexbox>+ ),+ value: CUSTOM_MINUTE_UPGRADE,+ },+ ]),+ ]}+ onChange={handleMinuteChange}+ />+ );+return (<Flexbox gap={16}><Flexbox horizontal gap={12}>@@ -228,12 +264,16 @@ const SchedulerForm = memo<SchedulerFormProps>(({ maxExecutions, onChange, patte{showTimeRow && (<Flexbox flex={1} gap={6}><Text className={styles.fieldLabel}>{t('taskSchedule.time')}</Text>- <Select- options={TIME_OPTIONS}- value={triggerTime.hour() * 60 + triggerTime.minute()}- variant="filled"- onChange={handleTimeChange}- />+ <Flexbox horizontal align="center" gap={6}>+ <Select+ options={HOUR_OPTIONS}+ style={{ flex: 1, minWidth: 0 }}+ value={triggerTime.hour()}+ variant="filled"+ onChange={handleHourChange}+ />+ {minuteSelect}+ </Flexbox></Flexbox>)}{scheduleType === 'hourly' && (@@ -249,18 +289,7 @@ const SchedulerForm = memo<SchedulerFormProps>(({ maxExecutions, onChange, pattevariant="filled"onChange={handleHourlyIntervalChange}/>- <Select- style={{ flexShrink: 0, 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}- />+ {minuteSelect}</Flexbox></Flexbox>)}diff --git a/src/features/AgentTasks/AgentTaskDetail/scheduler/helpers.ts b/src/features/AgentTasks/AgentTaskDetail/scheduler/helpers.tsindex 16e4dfbd2db..2b37cd39754 100644--- a/src/features/AgentTasks/AgentTaskDetail/scheduler/helpers.ts+++ b/src/features/AgentTasks/AgentTaskDetail/scheduler/helpers.ts@@ -47,18 +47,20 @@ export const formatScheduleDescription = (pattern: string, t: TFunction<'chat'>)switch (parsed.scheduleType) {case 'hourly': {const interval = parsed.hourlyInterval ?? 1;- // Cron storage rounds minutes to 0 or 30 (see buildCronPattern). Reading- // ':30' literally felt awkward in the summary, so call it out as- // "half past" only when it's actually non-zero and stay implicit on :00.- const isHalfPast = parsed.triggerMinute === 30;+ // Reading ':30' literally felt awkward in the summary, so call it out as+ // "half past" and stay implicit on :00; any other minute is named as is.+ const minute = parsed.triggerMinute;if (interval === 1) {- return isHalfPast- ? t('taskSchedule.summary.hourlyHalfPast')- : t('taskSchedule.summary.hourly');+ if (minute === 0) return t('taskSchedule.summary.hourly');+ if (minute === 30) return t('taskSchedule.summary.hourlyHalfPast');+ return t('taskSchedule.summary.hourlyAtMinute', { minute: padTime(minute) });}- return isHalfPast- ? t('taskSchedule.summary.everyNHoursHalfPast', { count: interval })- : t('taskSchedule.summary.everyNHours', { count: interval });+ if (minute === 0) return t('taskSchedule.summary.everyNHours', { count: interval });+ if (minute === 30) return t('taskSchedule.summary.everyNHoursHalfPast', { count: interval });+ return t('taskSchedule.summary.everyNHoursAtMinute', {+ count: interval,+ minute: padTime(minute),+ });}case 'daily': {return t('taskSchedule.summary.daily', {diff --git a/src/features/RecommendTaskTemplates/useTaskTemplateCreate.ts b/src/features/RecommendTaskTemplates/useTaskTemplateCreate.tsindex 366755f2e44..bec2519a9e1 100644--- a/src/features/RecommendTaskTemplates/useTaskTemplateCreate.ts+++ b/src/features/RecommendTaskTemplates/useTaskTemplateCreate.ts@@ -1,8 +1,10 @@import type { TaskTemplate } from '@lobechat/const';+import { snapScheduleToStandardMinute } from '@lobechat/utils/cronEval';import { toast } from '@lobehub/ui';import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import { useBusinessPreciseSchedule } from '@/business/client/hooks/useBusinessPreciseSchedule';import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { usePermission } from '@/hooks/usePermission';@@ -55,6 +57,7 @@ export const useTaskTemplateCreate = ({const { t } = useTranslation('common');const { allowed: canCreateTask } = usePermission('create_content');+ const { allowed: canUsePreciseSchedule } = useBusinessPreciseSchedule();const [loading, setLoading] = useState(false);const [created, setCreated] = useState(false);const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);@@ -77,7 +80,10 @@ export const useTaskTemplateCreate = ({description,instruction: template.instruction,name: title,- schedulePattern: template.cronPattern,+ // A template must stay usable on any plan, so a time the plan cannot pick moves to the nearest half hour.+ schedulePattern: canUsePreciseSchedule+ ? template.cronPattern+ : snapScheduleToStandardMinute(template.cronPattern),scheduleTimezone: Intl.DateTimeFormat().resolvedOptions().timeZone,});await taskTemplateService.recordCreated(template.id).catch((recordError) => {@@ -101,6 +107,7 @@ export const useTaskTemplateCreate = ({setLoading(false);}}, [+ canUsePreciseSchedule,createTask,description,inboxAgentId,