π€― 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
π fix(task): evaluate schedule cron with full semantics and validate it on write (#19984)
Arvin Xu288f93aa708b
diff --git a/apps/desktop/pnpm-lock.yaml b/apps/desktop/pnpm-lock.yamlindex fd92cefd823..9da1255a9da 100644--- a/apps/desktop/pnpm-lock.yaml+++ b/apps/desktop/pnpm-lock.yaml@@ -23,7 +23,7 @@ importers:version: 0.0.16'@lobehub/fluent-emoji':specifier: ^4.1.0- version: 4.1.0(@types/[email protected])([email protected]([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ version: 4.1.0(@types/[email protected])([email protected]([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])'@lydell/node-pty':specifier: 1.2.0-beta.12version: 1.2.0-beta.12@@ -315,7 +315,7 @@ importers:version: link:../../apps/desktop/stubs/business-const'@lobehub/ui':specifier: ^5- version: 5.20.0(@lobehub/[email protected](@types/[email protected])([email protected]([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]))(@lobehub/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@emotion/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ version: 5.20.0(@lobehub/[email protected](@types/[email protected])([email protected]([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]))(@lobehub/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@emotion/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])query-string:specifier: ^9.4.1version: 9.5.1@@ -507,7 +507,7 @@ importers:version: link:../utils'@lobehub/icons':specifier: ^5.15.0- version: 5.18.0(@lobehub/[email protected])(@types/[email protected])([email protected]([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ version: 5.18.0(@lobehub/[email protected])(@types/[email protected])([email protected]([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])'@modelcontextprotocol/sdk':specifier: ^1.29.0version: 1.29.0([email protected])@@ -637,7 +637,7 @@ importers:version: 1.17.1'@lobehub/ui':specifier: ^5- version: 5.20.0(@lobehub/[email protected](@types/[email protected])([email protected]([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]))(@lobehub/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@emotion/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ version: 5.20.0(@lobehub/[email protected](@types/[email protected])([email protected]([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]))(@lobehub/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@emotion/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])ajv:specifier: ^8.20.0version: 8.20.0@@ -680,6 +680,9 @@ importers:countries-and-timezones:specifier: ^3.9.0version: 3.10.0+ cron-parser:+ specifier: ^5.10.1+ version: 5.10.1dayjs:specifier: ^1.11.21version: 1.11.23@@ -4688,6 +4691,10 @@ packages:resolution: {integrity: sha512-HQ1GtXWNZy0r5MnZMLF9xmBmFNmtDVBeKQgX/5DY+RVmcZTODA+EPN/JLPCYRNP86nHG0QQrb1yJwGzXeqCCXw==}engines: {node: '>=8.x', npm: '>=5.x'}+ resolution: {integrity: sha512-pKRrRagItwk9rGIStcUyMxFX34x56zoX3KDf9HJ4ttwkXIK1qxK63EvXvEDmlxI9AdPJ+Y7TEKRftRlW5eSS7A==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-+R08/oI0nl3vfPcqftZRpytksBXDzOUveBq/NBVx0sUp1axwzPQrKinNx5yd5sxPu8j1wIy8AfnVQ+5eFdha6Q==}@@ -6574,6 +6581,10 @@ packages:peerDependencies:react: 19.2.7+ resolution: {integrity: sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==}+ engines: {node: '>=12'}+resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}@@ -10382,10 +10393,10 @@ snapshots:'@lobehub/[email protected]': {}- '@lobehub/[email protected](@types/[email protected])([email protected]([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])':+ '@lobehub/[email protected](@types/[email protected])([email protected]([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])':dependencies:'@lobehub/emojilib': 1.0.0- antd-style: 4.1.0(@types/[email protected])([email protected]([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ antd-style: 4.1.0(@types/[email protected])([email protected]([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])emoji-regex: 10.6.0es-toolkit: 1.52.0lucide-react: 0.562.0([email protected])@@ -10442,11 +10453,11 @@ snapshots:- ws- zod- '@lobehub/[email protected](@lobehub/[email protected])(@types/[email protected])([email protected]([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])':+ '@lobehub/[email protected](@lobehub/[email protected])(@types/[email protected])([email protected]([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])':dependencies:- '@lobehub/ui': 5.20.0(@lobehub/[email protected](@types/[email protected])([email protected]([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]))(@lobehub/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@emotion/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])- antd-style: 4.1.0(@types/[email protected])([email protected]([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ '@lobehub/ui': 5.20.0(@lobehub/[email protected](@types/[email protected])([email protected]([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]))(@lobehub/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@emotion/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ antd: 6.5.0([email protected])([email protected])([email protected]([email protected]))([email protected])+ antd-style: 4.1.0(@types/[email protected])([email protected]([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])es-toolkit: 1.51.0lucide-react: 0.469.0([email protected])polished: 4.3.1@@ -10470,7 +10481,7 @@ snapshots:dependencies:zod: 3.25.76- '@lobehub/[email protected](@lobehub/[email protected](@types/[email protected])([email protected]([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]))(@lobehub/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@emotion/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])':+ '@lobehub/[email protected](@lobehub/[email protected](@types/[email protected])([email protected]([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]))(@lobehub/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@emotion/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])':dependencies:'@base-ui/react': 1.7.0(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])@@ -10483,8 +10494,8 @@ snapshots:'@emotion/is-prop-valid': 1.4.0- '@lobehub/fluent-emoji': 4.1.0(@types/[email protected])([email protected]([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])- '@lobehub/icons': 5.18.0(@lobehub/[email protected])(@types/[email protected])([email protected]([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ '@lobehub/fluent-emoji': 4.1.0(@types/[email protected])([email protected]([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ '@lobehub/icons': 5.18.0(@lobehub/[email protected])(@types/[email protected])([email protected]([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])'@mdx-js/mdx': 3.1.1'@mdx-js/react': 3.1.1(@types/[email protected])([email protected])@@ -10493,8 +10504,8 @@ snapshots:'@shikijs/transformers': 4.4.3'@splinetool/runtime': 0.9.526- antd-style: 4.1.0(@types/[email protected])([email protected]([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ antd: 6.5.0([email protected])([email protected])([email protected]([email protected]))([email protected])+ antd-style: 4.1.0(@types/[email protected])([email protected]([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])chroma-js: 3.2.0class-variance-authority: 0.7.1clsx: 2.1.1@@ -11260,7 +11271,7 @@ snapshots:react: 19.2.7react-dom: 19.2.7([email protected])- '@rc-component/[email protected]([email protected])([email protected])([email protected]([email protected]))([email protected])':+ '@rc-component/[email protected]([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])':dependencies:@@ -11272,6 +11283,7 @@ snapshots:optionalDependencies:date-fns: 4.4.0dayjs: 1.11.23+ luxon: 3.7.2dependencies:@@ -12533,7 +12545,7 @@ snapshots:- [email protected](@types/[email protected])([email protected]([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]):+ [email protected](@types/[email protected])([email protected]([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]):dependencies:'@babel/runtime': 7.29.7@@ -12542,7 +12554,7 @@ snapshots:'@emotion/react': 11.14.0(@types/[email protected])([email protected])'@emotion/serialize': 1.3.3'@emotion/utils': 1.4.2+ antd: 6.5.0([email protected])([email protected])([email protected]([email protected]))([email protected])react: 19.2.7use-merge-value: 1.2.0([email protected])transitivePeerDependencies:@@ -12550,7 +12562,7 @@ snapshots:- react-dom- supports-color+ [email protected]([email protected])([email protected])([email protected]([email protected]))([email protected]):dependencies:'@ant-design/colors': 8.0.1@@ -12576,7 +12588,7 @@ snapshots:- '@rc-component/picker': 1.11.0([email protected])([email protected])([email protected]([email protected]))([email protected])+ '@rc-component/picker': 1.11.0([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])@@ -13162,6 +13174,10 @@ snapshots:+ dependencies:+ luxon: 3.7.2+optional: true@@ -15208,6 +15224,8 @@ snapshots:dependencies:react: 19.2.7+ [email protected]: {}+dependencies:'@jridgewell/sourcemap-codec': 1.5.5diff --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.tsnew file mode 100644index 00000000000..686cd059b93--- /dev/null+++ b/apps/server/src/router-hono/workflows/task/handlers/__tests__/scheduleDispatch.test.ts@@ -0,0 +1,205 @@+import { Hono } from 'hono';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { scheduleDispatch } from '../scheduleDispatch';++const mocks = vi.hoisted(() => ({+ appEnv: { enableQueueAgentRuntime: false },+ getScheduledTasks: vi.fn(),+ getServerDB: vi.fn(),+ publishJSON: vi.fn(),+ runScheduleTick: vi.fn(),+ swapDispatchedScheduleOccurrence: vi.fn(),+}));++vi.mock('@/database/server', () => ({ getServerDB: mocks.getServerDB }));++vi.mock('@/database/models/task', () => ({+ TaskModel: {+ getScheduledTasks: mocks.getScheduledTasks,+ swapDispatchedScheduleOccurrence: mocks.swapDispatchedScheduleOccurrence,+ },+}));++vi.mock('@/envs/app', () => ({ appEnv: mocks.appEnv }));++vi.mock('@/libs/qstash', () => ({ qstashClient: { publishJSON: mocks.publishJSON } }));++vi.mock('@/server/services/taskRunner/scheduleTick', () => ({+ runScheduleTick: mocks.runScheduleTick,+}));++const dispatch = async (dryRun: boolean) => {+ const app = new Hono();+ app.post('/schedule-dispatch', scheduleDispatch);+ const res = await app.request('/schedule-dispatch', {+ body: JSON.stringify({ dryRun }),+ method: 'POST',+ });+ return {+ status: res.status,+ ...((await res.json()) as { dispatched: number; due: number; total: number }),+ };+};++const dryRun = () => dispatch(true);++const dailyNineTask = (context: unknown) => ({+ context,+ createdByUserId: 'user-1',+ id: 'task-1',+ identifier: 'T-1',+ lastHeartbeatAt: null,+ schedulePattern: '0 9 * * *',+ scheduleTimezone: 'UTC',+});++describe('scheduleDispatch', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ // The 09:10 tick, right after a 09:00 slot.+ vi.setSystemTime(new Date('2026-09-21T09:10:00Z'));+ mocks.getServerDB.mockResolvedValue({});+ });++ afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllEnvs();+ vi.clearAllMocks();+ mocks.appEnv.enableQueueAgentRuntime = false;+ });++ it('does not fire a slot that passed before the schedule was armed', async () => {+ mocks.getScheduledTasks.mockResolvedValue([+ dailyNineTask({ scheduler: { scheduleStartedAt: '2026-09-21T09:05:00.000Z' } }),+ ]);++ expect(await dryRun()).toMatchObject({ due: 0, total: 1 });+ });++ it('fires the slot when the schedule was armed before it', async () => {+ mocks.getScheduledTasks.mockResolvedValue([+ dailyNineTask({ scheduler: { scheduleStartedAt: '2026-09-21T08:55:00.000Z' } }),+ ]);++ expect(await dryRun()).toMatchObject({ due: 1, total: 1 });+ });++ it('keeps firing tasks that were armed before the stamp existed', async () => {+ mocks.getScheduledTasks.mockResolvedValue([dailyNineTask(null)]);++ expect(await dryRun()).toMatchObject({ due: 1, total: 1 });+ });++ describe('occurrence reservation', () => {+ const armed = { scheduleStartedAt: '2026-09-21T08:55:00.000Z' };++ beforeEach(() => {+ mocks.appEnv.enableQueueAgentRuntime = true;+ vi.stubEnv('APP_URL', 'https://app.test');+ mocks.publishJSON.mockResolvedValue({ messageId: 'msg-1' });+ });++ it('does not re-dispatch an occurrence whose delivery is still queued', async () => {+ // The 09:00 occurrence was published on the 09:00 tick but its run has+ // not started, so lastHeartbeatAt still predates it on the 09:10 tick.+ mocks.getScheduledTasks.mockResolvedValue([+ dailyNineTask({+ scheduler: { ...armed, lastDispatchedOccurrenceAt: '2026-09-21T09:00:00.000Z' },+ }),+ ]);++ expect(await dryRun()).toMatchObject({ due: 0, total: 1 });+ });++ it('reserves the occurrence before publishing it', async () => {+ mocks.getScheduledTasks.mockResolvedValue([dailyNineTask({ scheduler: armed })]);+ mocks.swapDispatchedScheduleOccurrence.mockResolvedValue(true);++ expect(await dispatch(false)).toMatchObject({ dispatched: 1, due: 1 });+ expect(mocks.swapDispatchedScheduleOccurrence).toHaveBeenCalledWith(+ {},+ 'task-1',+ null,+ '2026-09-21T09:00:00.000Z',+ );+ expect(mocks.publishJSON).toHaveBeenCalledTimes(1);+ });++ it('does not publish when another dispatcher already reserved the occurrence', async () => {+ mocks.getScheduledTasks.mockResolvedValue([dailyNineTask({ scheduler: armed })]);+ mocks.swapDispatchedScheduleOccurrence.mockResolvedValue(false);++ expect(await dispatch(false)).toMatchObject({ dispatched: 0, due: 1 });+ expect(mocks.publishJSON).not.toHaveBeenCalled();+ });++ it('releases the reservation when publishing fails', async () => {+ mocks.getScheduledTasks.mockResolvedValue([dailyNineTask({ scheduler: armed })]);+ mocks.swapDispatchedScheduleOccurrence.mockResolvedValue(true);+ mocks.publishJSON.mockRejectedValue(new Error('qstash down'));+ vi.spyOn(console, 'error').mockImplementation(() => {});++ expect(await dispatch(false)).toMatchObject({ dispatched: 0, due: 1 });+ expect(mocks.swapDispatchedScheduleOccurrence).toHaveBeenLastCalledWith(+ {},+ 'task-1',+ '2026-09-21T09:00:00.000Z',+ null,+ );+ });++ it('releases every reservation when APP_URL is missing', async () => {+ vi.stubEnv('APP_URL', '');+ mocks.getScheduledTasks.mockResolvedValue([dailyNineTask({ scheduler: armed })]);+ mocks.swapDispatchedScheduleOccurrence.mockResolvedValue(true);+ vi.spyOn(console, 'error').mockImplementation(() => {});++ expect(await dispatch(false)).toMatchObject({ status: 500 });+ expect(mocks.publishJSON).not.toHaveBeenCalled();+ expect(mocks.swapDispatchedScheduleOccurrence).toHaveBeenCalledTimes(2);+ expect(mocks.swapDispatchedScheduleOccurrence).toHaveBeenLastCalledWith(+ {},+ 'task-1',+ '2026-09-21T09:00:00.000Z',+ null,+ );+ });+ });++ describe('inline dispatch', () => {+ const armed = { scheduleStartedAt: '2026-09-21T08:55:00.000Z' };++ it('keeps the reservation when the tick succeeds', async () => {+ mocks.getScheduledTasks.mockResolvedValue([dailyNineTask({ scheduler: armed })]);+ mocks.swapDispatchedScheduleOccurrence.mockResolvedValue(true);+ mocks.runScheduleTick.mockResolvedValue({ ran: true, taskIdentifier: 'T-1' });++ expect(await dispatch(false)).toMatchObject({ dispatched: 1, due: 1 });+ expect(mocks.runScheduleTick).toHaveBeenCalledWith('task-1', 'user-1');+ expect(mocks.swapDispatchedScheduleOccurrence).toHaveBeenCalledTimes(1);+ });++ it('releases the reservation when the tick fails', async () => {+ mocks.getScheduledTasks.mockResolvedValue([+ dailyNineTask({+ scheduler: { ...armed, lastDispatchedOccurrenceAt: '2026-09-20T09:00:00.000Z' },+ }),+ ]);+ mocks.swapDispatchedScheduleOccurrence.mockResolvedValue(true);+ mocks.runScheduleTick.mockRejectedValue(new Error('transient'));+ vi.spyOn(console, 'error').mockImplementation(() => {});++ expect(await dispatch(false)).toMatchObject({ dispatched: 0, due: 1 });+ expect(mocks.swapDispatchedScheduleOccurrence).toHaveBeenCalledTimes(2);+ // Compare-and-set back to the previous value: only succeeds while the row+ // still holds this reservation, so a newer one is never clobbered.+ expect(mocks.swapDispatchedScheduleOccurrence).toHaveBeenLastCalledWith(+ {},+ 'task-1',+ '2026-09-21T09:00:00.000Z',+ '2026-09-20T09:00:00.000Z',+ );+ });+ });+});diff --git a/apps/server/src/router-hono/workflows/task/handlers/scheduleDispatch.ts b/apps/server/src/router-hono/workflows/task/handlers/scheduleDispatch.tsindex dd87116a517..ede863a9dc0 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,4 @@-import { isExecutionTime } from '@lobechat/utils/cronEval';+import { findDueOccurrence } from '@lobechat/utils/cronEval';import debug from 'debug';import type { Context } from 'hono';@@ -18,7 +18,11 @@ export interface ScheduleDispatchPayload {}interface DueTask {+ /** The cron occurrence (ISO) this dispatch fires. */+ occurrence: string;pattern: string;+ /** `context.scheduler.lastDispatchedOccurrenceAt` as read on this tick. */+ previousOccurrence: string | null;taskId: string;taskIdentifier: string;timezone: string | null;@@ -26,12 +30,14 @@ interface DueTask {}/**- * Cron-style central dispatcher. Registered as a QStash Schedule (e.g.- * `*\/30 * * * *`) pointing at this endpoint. On each tick:+ * Cron-style central dispatcher. Registered as a QStash Schedule+ * (`*\/10 * * * *`, see `scripts/serverLauncher/startServer.js`) pointing at+ * this endpoint. On each tick:** 1. Loads all schedule-mode tasks in dispatchable status (`scheduled`/`backlog`).- * 2. Filters by cron pattern + timezone + last-run dedup (`isExecutionTime`).- * 3. Fan-outs one QStash message per due task to `/schedule-execute`.+ * 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`.** No per-user authentication: this is a global sweep. Signature verification is* handled by the `qstashAuth` middleware on the route.@@ -48,15 +54,31 @@ export async function scheduleDispatch(c: Context) {const due: DueTask[] = [];for (const task of tasks) {if (!task.schedulePattern) continue;- const matches = isExecutionTime({+ const scheduler = (+ task.context as {+ scheduler?: { lastDispatchedOccurrenceAt?: string; scheduleStartedAt?: string };+ } | null+ )?.scheduler;+ // Stamped when the user (re)starts the schedule; an occurrence before it+ // must not fire, or arming just after a slot would replay that slot.+ const scheduleStartedAt = scheduler?.scheduleStartedAt;+ // `lastHeartbeatAt` only moves once the run starts, and the grace window+ // 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({+ armedAt: scheduleStartedAt ? new Date(scheduleStartedAt) : null,cronPattern: task.schedulePattern,currentTime: now,- lastExecutedAt: task.lastHeartbeatAt ?? null,+ lastExecutedAt: coveredUntil,timezone: task.scheduleTimezone,});- if (!matches) continue;+ if (!occurrence) continue;due.push({+ occurrence: occurrence.toISOString(),pattern: task.schedulePattern,+ previousOccurrence,taskId: task.id,taskIdentifier: task.identifier,timezone: task.scheduleTimezone,@@ -83,7 +105,16 @@ export async function scheduleDispatch(c: Context) {});}- const dispatched = await fanout(due);+ const reserved = await reserve(db, due);+ let dispatched: number;+ try {+ dispatched = await fanout(db, reserved);+ } catch (error) {+ // Nothing was handed off, so give every reservation back; otherwise+ // later sweeps would treat these occurrences as covered and drop them.+ await Promise.all(reserved.map((d) => release(db, d)));+ throw error;+ }return c.json({dispatched,@@ -98,7 +129,73 @@ export async function scheduleDispatch(c: Context) {}}-const fanout = async (due: DueTask[]): Promise<number> => {+const latest = (...dates: (Date | string | null | undefined)[]): Date | null => {+ let result: Date | null = null;+ for (const value of dates) {+ if (!value) continue;+ const date = new Date(value);+ if (Number.isNaN(date.getTime())) continue;+ if (!result || date > result) result = date;+ }+ return result;+};++type ServerDB = Awaited<ReturnType<typeof getServerDB>>;++/**+ * Reserve each due occurrence with a compare-and-set on the task row. Only the+ * dispatcher that wins the swap publishes it, so an occurrence still queued+ * from an earlier tick (or claimed by an overlapping dispatcher run) is never+ * published twice.+ */+const reserve = async (db: ServerDB, due: DueTask[]): Promise<DueTask[]> => {+ const results = await Promise.allSettled(+ due.map((d) =>+ TaskModel.swapDispatchedScheduleOccurrence(db, d.taskId, d.previousOccurrence, d.occurrence),+ ),+ );+ const reserved: DueTask[] = [];+ for (const [i, r] of results.entries()) {+ if (r.status === 'fulfilled' && r.value) {+ reserved.push(due[i]);+ } else if (r.status === 'fulfilled') {+ log('skip task=%s occurrence=%s reason=already-reserved', due[i].taskId, due[i].occurrence);+ } else {+ console.error(+ '[task/schedule-dispatch] failed to reserve task=%s occurrence=%s: %O',+ due[i].taskId,+ due[i].occurrence,+ r.reason,+ );+ }+ }+ return reserved;+};++/**+ * Hand a reservation back when its handoff failed, so the next tick retries it.+ * The swap only succeeds while the row still holds this reservation, so a newer+ * one written in the meantime is left untouched.+ */+const release = async (db: ServerDB, d: DueTask) => {+ try {+ await TaskModel.swapDispatchedScheduleOccurrence(+ db,+ d.taskId,+ d.occurrence,+ d.previousOccurrence,+ );+ } catch (error) {+ console.error(+ '[task/schedule-dispatch] failed to release task=%s occurrence=%s: %O',+ d.taskId,+ d.occurrence,+ error,+ );+ }+};++const fanout = async (db: ServerDB, due: DueTask[]): Promise<number> => {// In queue mode, hand off via QStash so each task gets its own retry budget// and runs in an isolated handler invocation. Locally, just run inline so// dev / electron can exercise the path without QStash.@@ -128,13 +225,15 @@ const fanout = async (due: DueTask[]): Promise<number> => {due[i].taskIdentifier,r.reason,);+ await release(db, due[i]);}}return dispatched;}// Local / dev: invoke runScheduleTick directly. Errors are logged but don't- // fail the dispatch β one bad task shouldn't block the rest.+ // fail the dispatch β one bad task shouldn't block the rest. A failed tick+ // releases its reservation so the next sweep retries the occurrence.const results = await Promise.allSettled(due.map((d) => runScheduleTick(d.taskId, d.userId)));let dispatched = 0;for (const [i, r] of results.entries()) {@@ -146,6 +245,7 @@ const fanout = async (due: DueTask[]): Promise<number> => {due[i].taskId,r.reason,);+ await release(db, due[i]);}}return dispatched;diff --git a/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.tsindex 03cefca33cc..18e044fdb37 100644--- a/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts+++ b/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts@@ -414,6 +414,63 @@ describe('Task Router Integration', () => {});});+ describe('schedule pattern validation', () => {+ it('accepts standard cron with day-of-month, month and weekday ranges', async () => {+ const created = await caller.create({+ automationMode: 'schedule',+ instruction: 'One-shot reminder',+ schedulePattern: '0 10 27 9 *',+ scheduleTimezone: 'Asia/Shanghai',+ });+ const updated = await caller.update({+ id: created.data.id,+ schedulePattern: '45 11 * * 1-5',+ });+ expect(updated.data.schedulePattern).toBe('45 11 * * 1-5');+ });++ it('rejects cron the dispatcher cannot evaluate on create and update', async () => {+ await expect(+ caller.create({+ automationMode: 'schedule',+ instruction: 'Bad cron',+ schedulePattern: '0 0 9 * * *',+ }),+ ).rejects.toThrow(/Invalid schedulePattern .*0 0 9 \* \* \*.*expected 5 fields/);++ const created = await caller.create({ instruction: 'Later scheduled' });+ await expect(+ caller.update({ id: created.data.id, schedulePattern: '0 0 30 2 *' }),+ ).rejects.toThrow(/Invalid schedulePattern .*0 0 30 2 \*.*day of month/);+ await expect(+ caller.update({ id: created.data.id, scheduleTimezone: 'Mars/Base' }),+ ).rejects.toThrow(/IANA timezone/);+ });++ it('checks the resulting pattern/timezone pair against the stored schedule', async () => {+ const created = await caller.create({ instruction: 'Legacy schedule' });+ // A row written before write-time validation existed.+ await new TaskModel(testDB, userId).update(created.data.id, {+ schedulePattern: '0 0 9 * * *',+ scheduleTimezone: 'Mars/Base',+ });++ await expect(+ caller.update({ id: created.data.id, schedulePattern: '0 9 * * *' }),+ ).rejects.toThrow(/Invalid schedule: unknown timezone "Mars\/Base"/);+ await expect(+ caller.update({ automationMode: 'schedule', id: created.data.id }),+ ).rejects.toThrow(/Invalid schedule: expected 5 fields/);++ const updated = await caller.update({+ id: created.data.id,+ schedulePattern: '0 9 * * *',+ scheduleTimezone: 'Asia/Shanghai',+ });+ expect(updated.data.scheduleTimezone).toBe('Asia/Shanghai');+ });+ });+describe('status transitions', () => {it('should transition backlog β running β paused β completed', async () => {const task = await caller.create({ instruction: 'Test' });diff --git a/apps/server/src/routers/lambda/task.ts b/apps/server/src/routers/lambda/task.tsindex d505beda2d5..4ae10ac8612 100644--- a/apps/server/src/routers/lambda/task.ts+++ b/apps/server/src/routers/lambda/task.ts@@ -1,6 +1,11 @@import { TASK_STATUSES } from '@lobechat/builtin-tool-task';import { AgentRuntimeErrorType } from '@lobechat/model-runtime';import type { TaskListItem, TaskParticipant, TaskVerifyConfig } from '@lobechat/types';+import {+ isValidTimezone,+ validateCronPattern,+ validateScheduleUpdate,+} from '@lobechat/utils/cronEval';import { TRPCError } from '@trpc/server';import { z } from 'zod';@@ -75,6 +80,23 @@ const taskVerifyConfigPatchSchema = z.object({verifyRubricId: z.string().nullish(),});+// Reject cron the schedule dispatcher cannot evaluate at write time, instead of+// storing it and letting it silently never fire. An empty string still clears.+const schedulePatternSchema = z.string().superRefine((pattern, ctx) => {+ if (!pattern) return;+ const result = validateCronPattern(pattern, null);+ if (!result.valid) {+ ctx.addIssue({+ code: 'custom',+ message: `Invalid schedulePattern "${pattern}": ${result.error}`,+ });+ }+});++const scheduleTimezoneSchema = z.string().refine((tz) => !tz || isValidTimezone(tz), {+ message: 'scheduleTimezone must be an IANA timezone such as "Asia/Shanghai"',+});+// Priority: 0=None, 1=Urgent, 2=High, 3=Normal, 4=Lowconst createSchema = z.object({assigneeAgentId: z.string().optional(),@@ -93,8 +115,8 @@ const createSchema = z.object({parentTaskId: z.string().optional(),priority: z.number().min(0).max(4).optional(),projectId: z.string().optional(),- schedulePattern: z.string().optional(),- scheduleTimezone: z.string().optional(),+ schedulePattern: schedulePatternSchema.optional(),+ scheduleTimezone: scheduleTimezoneSchema.optional(),// When omitted, the server derives visibility from the parent task or the// assignee agent's visibility (private agent β private task). UI surfaces// such as the top-level "Tasks" create form pass it explicitly.@@ -129,8 +151,8 @@ const updateSchema = z.object({name: z.string().optional(),parentTaskId: z.string().nullish(),priority: z.number().min(0).max(4).optional(),- schedulePattern: z.string().nullish(),- scheduleTimezone: z.string().nullish(),+ schedulePattern: schedulePatternSchema.nullish(),+ scheduleTimezone: scheduleTimezoneSchema.nullish(),status: z.enum(TASK_STATUSES).optional(),});@@ -192,6 +214,29 @@ const groupListSchema = z});// Helper: resolve id/identifier and throw if not found+/**+ * The field schemas check `schedulePattern` and `scheduleTimezone` one at a+ * time; this checks the pair the task ends up with, filling any field the+ * input leaves out from the stored row, so e.g. a pattern-only update cannot+ * keep a legacy invalid timezone and still report success.+ */+function assertResultingScheduleValid(+ stored: { schedulePattern?: string | null; scheduleTimezone?: string | null } | null,+ input: {+ automationMode?: string | null;+ schedulePattern?: string | null;+ scheduleTimezone?: string | null;+ },+) {+ const result = validateScheduleUpdate(+ stored ? { pattern: stored.schedulePattern, timezone: stored.scheduleTimezone } : null,+ input,+ );+ if (result && !result.valid) {+ throw new TRPCError({ code: 'BAD_REQUEST', message: `Invalid schedule: ${result.error}` });+ }+}+async function resolveOrThrow(model: TaskModel, id: string) {const task = await model.resolve(id);if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });@@ -750,6 +795,7 @@ export const taskRouter = router({'Creating a goal through task.create is no longer supported. Reload the app, then create the goal again.',});}+ assertResultingScheduleValid(null, createInput);try {const parsedVerify = taskVerifyConfigPatchSchema.safeParse(createInput.config?.verify);const { verify: _legacyVerify, ...taskConfig } = createInput.config ?? {};@@ -1467,6 +1513,7 @@ export const taskRouter = router({data.assigneeAgentId,);const resolved = await resolveOrThrow(model, id);+ assertResultingScheduleValid(resolved, data);// Collaborative edit lock: reject writes to a workspace task another member// is actively editing. Inert until a client acquires the lock.diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.tsindex 5812e24fdc8..c8b30424e32 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts@@ -833,6 +833,100 @@ describe('createTaskRuntime', () => {);});+ it('returns a next-run preview in the task timezone', async () => {+ vi.useFakeTimers({ now: new Date('2026-09-25T05:00:00Z') });+ const taskCaller = {+ update: vi.fn().mockResolvedValue({}),+ updateConfig: vi.fn().mockResolvedValue({}),+ };+ const taskModel = {+ resolve: vi.fn().mockResolvedValue({ id: 'task-1', identifier: 'T-13' }),+ };+ const runtime = createTaskRuntime({+ agentModel: { existsById: vi.fn() } as any,+ taskCaller: taskCaller as any,+ taskModel: taskModel as any,+ taskService: {} as any,+ toolCallId: 'tool-call-schedule',+ });++ const result = await runtime.setTaskSchedule({+ automationMode: 'schedule',+ identifier: 'T-13',+ schedulePattern: '45 11 * * 1-5',+ scheduleTimezone: 'Asia/Ho_Chi_Minh',+ });+ vi.useRealTimers();++ expect(result.success).toBe(true);+ expect(result.content).toContain(+ 'next runs (Asia/Ho_Chi_Minh) β Mon 2026-09-28 11:45; Tue 2026-09-29 11:45; Wed 2026-09-30 11:45',+ );+ });++ it.each([+ ['0 9 * *', undefined, /expected 5 fields/],+ ['0 0 9 * * *', undefined, /expected 5 fields/],+ ['0 0 30 2 *', undefined, /day of month/],+ ['0 9 * * *', 'Mars/Base', /unknown timezone/],+ ])('rejects schedule %s (%s) without writing anything', async (pattern, tz, error) => {+ const taskCaller = {+ update: vi.fn().mockResolvedValue({}),+ updateConfig: vi.fn().mockResolvedValue({}),+ };+ const taskModel = {+ resolve: vi.fn().mockResolvedValue({ id: 'task-1', identifier: 'T-1' }),+ };+ const runtime = createTaskRuntime({+ agentModel: { existsById: vi.fn() } as any,+ taskCaller: taskCaller as any,+ taskModel: taskModel as any,+ taskService: {} as any,+ toolCallId: 'tool-call-schedule',+ });++ const result = await runtime.setTaskSchedule({+ automationMode: 'schedule',+ identifier: 'T-1',+ maxExecutions: 1,+ schedulePattern: pattern,+ scheduleTimezone: tz,+ });++ expect(result.success).toBe(false);+ expect(result.content).toMatch(error);+ expect(result.content).toContain('Nothing was updated');+ expect(taskCaller.update).not.toHaveBeenCalled();+ expect(taskCaller.updateConfig).not.toHaveBeenCalled();+ });++ it('validates a timezone-only change against the stored pattern', async () => {+ const taskCaller = { update: vi.fn().mockResolvedValue({}) };+ const taskModel = {+ resolve: vi.fn().mockResolvedValue({+ id: 'task-1',+ identifier: 'T-1',+ schedulePattern: '0 9 * * *',+ scheduleTimezone: 'UTC',+ }),+ };+ const runtime = createTaskRuntime({+ agentModel: { existsById: vi.fn() } as any,+ taskCaller: taskCaller as any,+ taskModel: taskModel as any,+ taskService: {} as any,+ toolCallId: 'tool-call-schedule',+ });++ const result = await runtime.setTaskSchedule({+ identifier: 'T-1',+ scheduleTimezone: 'Europe/Moscow',+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain('next runs (Europe/Moscow) β');+ });+it('applies verify config changes and succeeds', async () => {const taskCaller = {updateVerifyConfig: vi.fn().mockResolvedValue({}),diff --git a/apps/server/src/services/toolExecution/serverRuntimes/task.ts b/apps/server/src/services/toolExecution/serverRuntimes/task.tsindex fe80c321480..fe41de8f0e4 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/task.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/task.ts@@ -20,6 +20,7 @@ import {priorityLabel,} from '@lobechat/prompts';import type { TaskAutomationMode, TaskStatus } from '@lobechat/types';+import { formatInvalidScheduleMessage, validateScheduleUpdate } from '@lobechat/utils/cronEval';import { eq } from 'drizzle-orm';import { notifyTaskAssigned } from '@/business/server/task/notifyTaskAssigned';@@ -633,6 +634,20 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {const task = await taskModel().resolve(args.identifier);if (!task) return { content: `Task not found: ${args.identifier}`, success: false };+ // Validate the schedule the task will end up with before writing anything,+ // so an unsupported pattern is refused instead of stored and misfired.+ const schedule = validateScheduleUpdate(+ { pattern: task.schedulePattern, timezone: task.scheduleTimezone },+ args,+ );+ if (schedule && !schedule.valid) {+ return {+ content: formatInvalidScheduleMessage(task.identifier, schedule.error),+ success: false,+ };+ }+ const schedulePreview = schedule?.valid ? schedule.preview : undefined;+const changes: string[] = [];const ops: Promise<unknown>[] = [];@@ -699,6 +714,8 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {await Promise.all(ops);+ if (schedulePreview) changes.push(schedulePreview);+return { content: formatTaskEdited(task.identifier, changes), success: true };},diff --git a/packages/builtin-tool-task/package.json b/packages/builtin-tool-task/package.jsonindex 013d12b07b9..679ba393c15 100644--- a/packages/builtin-tool-task/package.json+++ b/packages/builtin-tool-task/package.json@@ -10,7 +10,8 @@"main": "./src/index.ts","dependencies": {"@lobechat/const": "workspace:*",- "@lobechat/prompts": "workspace:*"+ "@lobechat/prompts": "workspace:*",+ "@lobechat/utils": "workspace:*"},"devDependencies": {"@lobechat/types": "workspace:*"diff --git a/packages/builtin-tool-task/src/client/executor/index.ts b/packages/builtin-tool-task/src/client/executor/index.tsindex 425957b1efb..404c1ae4c06 100644--- a/packages/builtin-tool-task/src/client/executor/index.ts+++ b/packages/builtin-tool-task/src/client/executor/index.ts@@ -20,6 +20,7 @@ import type {ToolAfterCallContext,} from '@lobechat/types';import { BaseExecutor } from '@lobechat/types';+import { formatInvalidScheduleMessage, validateScheduleUpdate } from '@lobechat/utils/cronEval';import debug from 'debug';import { getActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';@@ -506,6 +507,29 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {}};+ /**+ * Validate the schedule the task will end up with, like the server runtime.+ * A field the call leaves out keeps its stored value, so the stored schedule+ * is fetched to check the resulting pattern/timezone pair (and to preview+ * its next runs) before anything is written.+ */+ private checkResultingSchedule = async (params: {+ automationMode?: TaskAutomationMode | null;+ identifier: string;+ schedulePattern?: string | null;+ scheduleTimezone?: string | null;+ }) => {+ const needsStored =+ (params.schedulePattern !== undefined ||+ params.scheduleTimezone !== undefined ||+ params.automationMode === 'schedule') &&+ (params.schedulePattern === undefined || params.scheduleTimezone === undefined);+ const stored = needsStored+ ? (await taskService.getDetail(params.identifier))?.data?.schedule+ : undefined;+ return validateScheduleUpdate(stored, params);+ };+setTaskSchedule = async (params: {automationMode?: TaskAutomationMode | null;@@ -525,6 +549,17 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {const changes: string[] = [];const ops: Promise<unknown>[] = [];+ // Refuse an unusable schedule before writing anything, like the server+ // runtime does, so a half-applied update never leaves a bad cron behind.+ const schedule = await this.checkResultingSchedule(params);+ if (schedule && !schedule.valid) {+ return {+ content: formatInvalidScheduleMessage(identifier, schedule.error),+ error: { message: schedule.error, type: 'InvalidSchedule' },+ success: false,+ };+ }+// Top-level schedule columns β direct service.update bypasses the// store.updateTask optimistic path, which would otherwise need to map// flat columns onto the detail's nested `schedule.*` shape.@@ -602,6 +637,8 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {await Promise.all(ops);await store.internal_refreshTaskDetail(identifier);+ if (schedule?.valid) changes.push(schedule.preview);+return {content: formatTaskEdited(identifier, changes),state: { automationMode: params.automationMode, identifier, success: true },diff --git a/packages/builtin-tool-task/src/client/executor/setTaskSchedule.test.ts b/packages/builtin-tool-task/src/client/executor/setTaskSchedule.test.tsnew file mode 100644index 00000000000..307fc8d4c56--- /dev/null+++ b/packages/builtin-tool-task/src/client/executor/setTaskSchedule.test.ts@@ -0,0 +1,152 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ getDetail: vi.fn(),+ refreshTaskDetail: vi.fn(),+ update: vi.fn(),+ updateConfig: vi.fn(),+}));++vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({+ getActiveWorkspaceSlug: vi.fn(),+}));++vi.mock('@/business/client/hooks/useWorkspaceMembers', () => ({+ getWorkspaceMembers: vi.fn(),+}));++vi.mock('@/store/user', () => ({ useUserStore: { getState: () => ({}) } }));++vi.mock('@/store/user/selectors', () => ({ userProfileSelectors: {} }));++vi.mock('@/store/chat', () => ({ getChatStoreState: vi.fn() }));++vi.mock('@/store/task', () => ({+ getTaskStoreState: () => ({ internal_refreshTaskDetail: mocks.refreshTaskDetail }),+}));++vi.mock('@/store/task/slices/detail/reducer', () => ({+ findSubtaskParentId: vi.fn(() => undefined),+}));++vi.mock('@/services/task', () => ({+ taskService: {+ getDetail: mocks.getDetail,+ update: mocks.update,+ updateConfig: mocks.updateConfig,+ },+}));++const { taskExecutor } = await import('./index');++describe('TaskExecutor β setTaskSchedule', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-09-26T00:00:00Z'));+ mocks.update.mockResolvedValue(undefined);+ mocks.updateConfig.mockResolvedValue(undefined);+ mocks.refreshTaskDetail.mockResolvedValue(undefined);+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('lists the next runs after setting a schedule, like the server runtime', async () => {+ const result = await taskExecutor.setTaskSchedule({+ automationMode: 'schedule',+ identifier: 'T-1',+ schedulePattern: '30 9 * * 1-5',+ scheduleTimezone: 'Asia/Shanghai',+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain(+ 'next runs (Asia/Shanghai) β Mon 2026-09-28 09:30; Tue 2026-09-29 09:30; Wed 2026-09-30 09:30',+ );+ expect(mocks.getDetail).not.toHaveBeenCalled();+ });++ it('fills a field the call left out from the stored schedule', async () => {+ mocks.getDetail.mockResolvedValue({+ data: { schedule: { pattern: '0 10 27 9 *', timezone: 'Asia/Shanghai' } },+ });++ const result = await taskExecutor.setTaskSchedule({+ identifier: 'T-1',+ scheduleTimezone: 'Asia/Shanghai',+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain('next runs (Asia/Shanghai) β Sun 2026-09-27 10:00');+ });++ it('refuses an unusable pattern without writing anything', async () => {+ const result = await taskExecutor.setTaskSchedule({+ identifier: 'T-1',+ maxExecutions: 1,+ schedulePattern: '0 0 9 * * *',+ });++ expect(result.success).toBe(false);+ expect(result.content).toMatch(/^Invalid schedule for task T-1: expected 5 fields/);+ expect(mocks.update).not.toHaveBeenCalled();+ expect(mocks.updateConfig).not.toHaveBeenCalled();+ });++ it('does not add a preview when the schedule is untouched', async () => {+ const result = await taskExecutor.setTaskSchedule({ identifier: 'T-1', maxExecutions: 3 });++ expect(result.success).toBe(true);+ expect(result.content).not.toContain('next runs');+ expect(mocks.getDetail).not.toHaveBeenCalled();+ });++ it('validates a pattern-only change against the stored timezone', async () => {+ mocks.getDetail.mockResolvedValue({+ data: { schedule: { pattern: '0 9 * * *', timezone: 'Mars/Base' } },+ });++ const result = await taskExecutor.setTaskSchedule({+ identifier: 'T-1',+ schedulePattern: '0 10 * * *',+ });++ expect(result.success).toBe(false);+ expect(result.content).toMatch(/^Invalid schedule for task T-1: unknown timezone "Mars\/Base"/);+ expect(mocks.update).not.toHaveBeenCalled();+ });++ it('refuses to enable schedule mode over a stored pattern the dispatcher cannot run', async () => {+ mocks.getDetail.mockResolvedValue({+ data: { schedule: { pattern: '0 0 9 * * *', timezone: 'UTC' } },+ });++ const result = await taskExecutor.setTaskSchedule({+ automationMode: 'schedule',+ identifier: 'T-1',+ });++ expect(result.success).toBe(false);+ expect(result.content).toMatch(/^Invalid schedule for task T-1: expected 5 fields/);+ expect(mocks.update).not.toHaveBeenCalled();+ });++ it('checks the stored schedule before any write happens', async () => {+ mocks.getDetail.mockResolvedValue({+ data: { schedule: { pattern: '0 9 * * *', timezone: 'Asia/Shanghai' } },+ });++ const result = await taskExecutor.setTaskSchedule({+ automationMode: 'schedule',+ identifier: 'T-1',+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain('next runs (Asia/Shanghai) β Sat 2026-09-26 09:00');+ expect(mocks.getDetail.mock.invocationCallOrder[0]).toBeLessThan(+ mocks.update.mock.invocationCallOrder[0],+ );+ });+});diff --git a/packages/builtin-tool-task/src/manifest.ts b/packages/builtin-tool-task/src/manifest.tsindex 5d300d593da..2587ca3b878 100644--- a/packages/builtin-tool-task/src/manifest.ts+++ b/packages/builtin-tool-task/src/manifest.ts@@ -375,7 +375,7 @@ export const TaskManifest: BuiltinToolManifest = {},schedulePattern: {description:- 'Cron expression for scheduled mode, e.g. "0 9 * * *" (every day at 09:00). Pass null to clear the pattern.',+ 'Standard 5-field cron expression "minute hour day-of-month month day-of-week" for scheduled mode, e.g. "0 9 * * *" (every day at 09:00), "30 9 * * 1-5" (weekdays at 09:30) or "0 10 27 9 *" (Sep 27 at 10:00; pair with maxExecutions=1 for a one-off). Invalid patterns are rejected; on success the result lists the next run times β check them against what the user asked for. Pass null to clear the pattern.',type: ['string', 'null'],},scheduleTimezone: {diff --git a/packages/builtin-tool-task/src/systemRole.ts b/packages/builtin-tool-task/src/systemRole.tsindex ba05ca64f67..4d669209801 100644--- a/packages/builtin-tool-task/src/systemRole.ts+++ b/packages/builtin-tool-task/src/systemRole.ts@@ -16,7 +16,7 @@ export const systemPrompt = `You have access to Task management tools. Use themSchedule fields (setTaskSchedule):- **automationMode**: 'schedule' (cron-based) or 'heartbeat' (fixed interval). Pass null to disable automation-- **schedulePattern + scheduleTimezone**: cron expression (e.g. "0 9 * * *") and IANA timezone (e.g. "Asia/Shanghai"); used by schedule mode+- **schedulePattern + scheduleTimezone**: standard 5-field cron expression (e.g. "0 9 * * *", "30 9 * * 1-5", "0 10 27 9 *") and IANA timezone (e.g. "Asia/Shanghai"); used by schedule mode. The result lists the next run times β confirm they match what the user asked for- **heartbeatInterval**: seconds between ticks; used by heartbeat mode (recommend β₯600s). Pass 0 to clear- **maxExecutions**: cap on total scheduled runs; null means unlimiteddiff --git a/packages/database/src/models/__tests__/task.test.ts b/packages/database/src/models/__tests__/task.test.tsindex 44467b5ea97..c071ee73c9c 100644--- a/packages/database/src/models/__tests__/task.test.ts+++ b/packages/database/src/models/__tests__/task.test.ts@@ -2525,6 +2525,45 @@ describe('TaskModel', () => {});});+ describe('static swapDispatchedScheduleOccurrence', () => {+ it('reserves an occurrence once and keeps the rest of the context', async () => {+ const model = new TaskModel(serverDB, userId);+ const task = await model.create({+ automationMode: 'schedule',+ instruction: 'Daily',+ schedulePattern: '0 9 * * *',+ });+ await model.updateContext(task.id, {+ scheduler: { scheduleStartedAt: '2026-09-20T00:00:00.000Z' },+ });+ const occurrence = '2026-09-21T09:00:00.000Z';++ expect(+ await TaskModel.swapDispatchedScheduleOccurrence(serverDB, task.id, null, occurrence),+ ).toBe(true);+ // A second dispatcher tick that read the pre-reservation state loses.+ expect(+ await TaskModel.swapDispatchedScheduleOccurrence(serverDB, task.id, null, occurrence),+ ).toBe(false);++ const stored = await model.findById(task.id);+ expect(stored?.context).toMatchObject({+ scheduler: {+ lastDispatchedOccurrenceAt: occurrence,+ scheduleStartedAt: '2026-09-20T00:00:00.000Z',+ },+ });++ // Releasing (e.g. after a failed publish) restores the previous value.+ expect(+ await TaskModel.swapDispatchedScheduleOccurrence(serverDB, task.id, occurrence, null),+ ).toBe(true);+ expect(+ await TaskModel.swapDispatchedScheduleOccurrence(serverDB, task.id, null, occurrence),+ ).toBe(true);+ });+ });+describe('static findStuckTasks', () => {it('should find running tasks whose heartbeat timed out', async () => {const model = new TaskModel(serverDB, userId);diff --git a/packages/database/src/models/task.ts b/packages/database/src/models/task.tsindex 6ab0215571e..cb3137bc86e 100644--- a/packages/database/src/models/task.ts+++ b/packages/database/src/models/task.ts@@ -1515,6 +1515,37 @@ export class TaskModel {);}+ /**+ * Atomically move `context.scheduler.lastDispatchedOccurrenceAt` from+ * `expected` to `next`. Returns false when another writer changed it first.+ *+ * The schedule dispatcher reserves a cron occurrence this way before+ * publishing its execution, so a later tick inside the grace window (or an+ * overlapping dispatcher run) cannot publish the same occurrence again while+ * the first delivery is still queued.+ */+ static async swapDispatchedScheduleOccurrence(+ db: LobeChatDatabase,+ taskId: string,+ expected: string | null,+ next: string | null,+ ): Promise<boolean> {+ const current = sql`coalesce(${tasks.context}, '{}'::jsonb)`;+ const rows = await db+ .update(tasks)+ .set({+ context: sql`${current} || jsonb_build_object('scheduler', coalesce(${current} -> 'scheduler', '{}'::jsonb) || jsonb_build_object('lastDispatchedOccurrenceAt', ${next}::text))`,+ })+ .where(+ and(+ eq(tasks.id, taskId),+ sql`coalesce(${current} -> 'scheduler' ->> 'lastDispatchedOccurrenceAt', '') = ${expected ?? ''}`,+ ),+ )+ .returning({ id: tasks.id });+ return rows.length > 0;+ }+// Find stuck tasks (running but heartbeat timed out)// Only checks tasks that have both lastHeartbeatAt and heartbeatTimeout setstatic async findStuckTasks(db: LobeChatDatabase): Promise<TaskItem[]> {diff --git a/packages/utils/package.json b/packages/utils/package.jsonindex 7c65488c561..c4a58cf5d46 100644--- a/packages/utils/package.json+++ b/packages/utils/package.json@@ -21,6 +21,7 @@"brotli-wasm": "^3.0.1","chroma-js": "^3.2.0","countries-and-timezones": "^3.9.0",+ "cron-parser": "^5.10.1","dayjs": "^1.11.21","debug": "^4.4.3","dompurify": "^3.4.11",diff --git a/packages/utils/src/cronEval.test.ts b/packages/utils/src/cronEval.test.tsindex 50d9fb2af9b..c4b37f29acd 100644--- a/packages/utils/src/cronEval.test.ts+++ b/packages/utils/src/cronEval.test.ts@@ -1,6 +1,11 @@import { describe, expect, it } from 'vitest';-import { isExecutionTime } from './cronEval';+import {+ findDueOccurrence,+ isExecutionTime,+ validateCronPattern,+ validateScheduleUpdate,+} from './cronEval';const SHANGHAI = 'Asia/Shanghai';@@ -90,18 +95,29 @@ describe('isExecutionTime', () => {});describe('daily pattern β catch-up after missed scheduled time', () => {- it('catches up at 23:00 if 21:00 was missed and the task never ran today', () => {- // Last run was yesterday at 21:00; dispatcher comes online at 23:00 today.+ it('catches up a missed 21:00 tick within the grace window', () => {+ // Last run was yesterday at 21:00; the 21:00 and 21:05 ticks were lost.expect(isExecutionTime({cronPattern: '0 21 * * *',- currentTime: utc('2026-04-29T23:00:00'),+ currentTime: utc('2026-04-29T21:10:00'),lastExecutedAt: utc('2026-04-28T21:00:00'),timezone: 'UTC',}),).toBe(true);});+ it('does NOT replay a 21:00 occurrence two hours late β waits for the next one', () => {+ expect(+ isExecutionTime({+ cronPattern: '0 21 * * *',+ currentTime: utc('2026-04-29T23:00:00'),+ lastExecutedAt: utc('2026-04-28T21:00:00'),+ timezone: 'UTC',+ }),+ ).toBe(false);+ });+it('does NOT catch-up after manual run already covered today (manual at 22:00, dispatcher at 23:00)', () => {expect(isExecutionTime({@@ -114,9 +130,20 @@ describe('isExecutionTime', () => {});});- describe('hourly / interval patterns are unaffected by the fix', () => {- it('every-hour-at-:00 still dedups within the 60-minute window', () => {- // Last run 30 minutes ago β same hour window, do not refire.+ describe('hourly / interval patterns', () => {+ it('every-hour-at-:00 does not refire on the next tick of the same hour', () => {+ // The 15:00 occurrence already ran at 15:00:03; the 15:05 tick must skip.+ expect(+ isExecutionTime({+ cronPattern: '0 * * * *',+ currentTime: utc('2026-04-29T15:05:00'),+ lastExecutedAt: utc('2026-04-29T15:00:03'),+ timezone: 'UTC',+ }),+ ).toBe(false);+ });++ it('every-hour-at-:00 still fires 15:00 after a manual run at 14:30', () => {expect(isExecutionTime({cronPattern: '0 * * * *',@@ -124,7 +151,7 @@ describe('isExecutionTime', () => {lastExecutedAt: utc('2026-04-29T14:30:00'),timezone: 'UTC',}),- ).toBe(false);+ ).toBe(true);});it('every-hour-at-:00 fires after 60 minutes since last run', () => {@@ -176,6 +203,116 @@ describe('isExecutionTime', () => {});});+ describe('full cron semantics', () => {+ it('honours day-of-month and month fields', () => {+ expect(+ isExecutionTime({+ cronPattern: '0 9 1 5 *',+ currentTime: utc('2026-05-01T09:00:00'),+ lastExecutedAt: null,+ timezone: 'UTC',+ }),+ ).toBe(true);+ expect(+ isExecutionTime({+ cronPattern: '0 9 1 5 *',+ currentTime: utc('2026-05-02T09:00:00'),+ lastExecutedAt: null,+ timezone: 'UTC',+ }),+ ).toBe(false);+ });++ it('treats a weekday range as every day in the range', () => {+ // 2026-04-30 is a Thursday.+ expect(+ isExecutionTime({+ cronPattern: '0 9 * * 1-5',+ currentTime: utc('2026-04-30T09:00:00'),+ lastExecutedAt: utc('2026-04-29T09:00:00'),+ timezone: 'UTC',+ }),+ ).toBe(true);+ // 2026-05-02 is a Saturday.+ expect(+ isExecutionTime({+ cronPattern: '0 9 * * 1-5',+ currentTime: utc('2026-05-02T09:00:00'),+ lastExecutedAt: utc('2026-05-01T09:00:00'),+ timezone: 'UTC',+ }),+ ).toBe(false);+ });++ it('fires each occurrence of a minute-offset pattern once, at or after the target', () => {+ const tick = (time: string, last: string) =>+ isExecutionTime({+ cronPattern: '30 14 * * *',+ currentTime: utc(time),+ lastExecutedAt: utc(last),+ timezone: 'UTC',+ });+ expect(tick('2026-04-29T14:25:00', '2026-04-28T14:30:00')).toBe(false);+ expect(tick('2026-04-29T14:30:00', '2026-04-28T14:30:00')).toBe(true);+ expect(tick('2026-04-29T14:35:00', '2026-04-29T14:30:05')).toBe(false);+ });++ it('never fires an invalid pattern or timezone', () => {+ for (const [cronPattern, timezone] of [+ ['0 9 * *', 'UTC'],+ ['0 0 9 * * *', 'UTC'],+ ['61 9 * * *', 'UTC'],+ ['0 9 * * *', 'Mars/Base'],+ ] as const) {+ expect(+ isExecutionTime({+ cronPattern,+ currentTime: utc('2026-04-29T09:00:00'),+ lastExecutedAt: null,+ timezone,+ }),+ ).toBe(false);+ }+ });+ });++ describe('validateCronPattern', () => {+ it('previews the next runs in the pattern timezone', () => {+ const result = validateCronPattern('45 11 * * 1-5', 'Asia/Ho_Chi_Minh', {+ from: utc('2026-09-25T05:00:00'),+ });+ expect(result).toEqual({+ nextRuns: [+ utc('2026-09-28T04:45:00'),+ utc('2026-09-29T04:45:00'),+ utc('2026-09-30T04:45:00'),+ ],+ valid: true,+ });+ });++ it('previews a one-shot date on its actual date', () => {+ const result = validateCronPattern('0 10 27 9 *', SHANGHAI, {+ count: 1,+ from: utc('2026-09-20T03:15:55'),+ });+ expect(result).toEqual({ nextRuns: [utc('2026-09-27T02:00:00')], valid: true });+ });++ it.each([+ ['0 9 * *', 'UTC', /expected 5 fields/],+ ['0 0 9 * * *', 'UTC', /expected 5 fields/],+ ['@daily', 'UTC', /expected 5 fields/],+ ['61 9 * * *', 'UTC', /61/],+ ['0 0 30 2 *', 'UTC', /day of month/],+ ['0 9 * * *', 'Mars/Base', /unknown timezone/],+ ])('rejects %s (%s)', (pattern, timezone, error) => {+ const result = validateCronPattern(pattern, timezone);+ expect(result.valid).toBe(false);+ expect(!result.valid && result.error).toMatch(error);+ });+ });+describe('null / first-run handling', () => {it('fires when there is no lastExecutedAt and clock matches', () => {expect(@@ -189,3 +326,157 @@ describe('isExecutionTime', () => {});});});++describe('isExecutionTime β arming lower bound', () => {+ it('does NOT fire an occurrence that predates arming (09:00 slot, armed 09:05, 09:10 tick)', () => {+ expect(+ isExecutionTime({+ armedAt: utc('2026-04-29T09:05:00'),+ cronPattern: '0 9 * * *',+ currentTime: utc('2026-04-29T09:10:00'),+ lastExecutedAt: null,+ timezone: 'UTC',+ }),+ ).toBe(false);+ });++ it('does NOT replay the slot just before a re-arm when the last run is older', () => {+ expect(+ isExecutionTime({+ armedAt: utc('2026-04-29T09:05:00'),+ cronPattern: '0 9 * * *',+ currentTime: utc('2026-04-29T09:10:00'),+ lastExecutedAt: utc('2026-04-27T09:00:00'),+ timezone: 'UTC',+ }),+ ).toBe(false);+ });++ it('fires the first occurrence after arming', () => {+ expect(+ isExecutionTime({+ armedAt: utc('2026-04-29T08:55:00'),+ cronPattern: '0 9 * * *',+ currentTime: utc('2026-04-29T09:00:00'),+ lastExecutedAt: null,+ timezone: 'UTC',+ }),+ ).toBe(true);+ });++ it('fires the next day once the armed slot has passed', () => {+ expect(+ isExecutionTime({+ armedAt: utc('2026-04-29T09:05:00'),+ cronPattern: '0 9 * * *',+ currentTime: utc('2026-04-30T09:00:00'),+ lastExecutedAt: null,+ timezone: 'UTC',+ }),+ ).toBe(true);+ });+});++describe('isExecutionTime β grace window vs the 10-minute dispatcher', () => {+ it('still fires a 09:01 occurrence on the 09:20 tick when the 09:10 tick was missed', () => {+ expect(+ isExecutionTime({+ cronPattern: '1 9 * * *',+ currentTime: utc('2026-04-29T09:20:00'),+ lastExecutedAt: utc('2026-04-28T09:10:00'),+ timezone: 'UTC',+ }),+ ).toBe(true);+ });++ it('covers one missed tick plus jitter: a 09:01 occurrence on a late 09:20 tick (09:25)', () => {+ expect(+ isExecutionTime({+ cronPattern: '1 9 * * *',+ currentTime: utc('2026-04-29T09:25:00'),+ lastExecutedAt: utc('2026-04-28T09:10:00'),+ timezone: 'UTC',+ }),+ ).toBe(true);+ });++ it('does NOT replay an occurrence older than the grace window', () => {+ expect(+ isExecutionTime({+ cronPattern: '1 9 * * *',+ currentTime: utc('2026-04-29T09:40:00'),+ lastExecutedAt: utc('2026-04-28T09:10:00'),+ timezone: 'UTC',+ }),+ ).toBe(false);+ });+});++describe('findDueOccurrence', () => {+ it('identifies the occurrence each tick in the grace window would fire', () => {+ const input = { cronPattern: '0 9 * * *', timezone: 'UTC' };+ const occurrence = new Date('2026-09-21T09:00:00Z');++ // Every tick inside the grace window resolves to the same occurrence, so+ // the dispatcher can key a reservation on it.+ for (const tick of ['09:00', '09:10', '09:20']) {+ expect(+ findDueOccurrence({ ...input, currentTime: new Date(`2026-09-21T${tick}:00Z`) }),+ ).toEqual(occurrence);+ }+ // Once reserved, later ticks see it as covered.+ expect(+ findDueOccurrence({+ ...input,+ currentTime: new Date('2026-09-21T09:10:00Z'),+ lastExecutedAt: occurrence,+ }),+ ).toBeNull();+ });+});++describe('validateScheduleUpdate', () => {+ const from = new Date('2026-09-26T00:00:00Z');++ it('ignores patches that do not touch the schedule', () => {+ expect(validateScheduleUpdate({ pattern: '0 0 9 * * *' }, {})).toBeUndefined();+ expect(+ validateScheduleUpdate({ pattern: '0 0 9 * * *' }, { automationMode: 'heartbeat' }),+ ).toBeUndefined();+ });++ it('checks a pattern-only change against the stored timezone', () => {+ expect(+ validateScheduleUpdate(+ { pattern: '0 9 * * *', timezone: 'Mars/Base' },+ { schedulePattern: '0 10 * * *' },+ ),+ ).toEqual({ error: 'unknown timezone "Mars/Base"', valid: false });+ });++ it('re-checks the stored pair when schedule mode is enabled', () => {+ expect(+ validateScheduleUpdate(+ { pattern: '0 0 9 * * *', timezone: 'UTC' },+ { automationMode: 'schedule' },+ ),+ ).toMatchObject({ valid: false });+ });++ it('previews the resulting schedule when it is valid', () => {+ expect(+ validateScheduleUpdate(+ { pattern: '0 9 * * *', timezone: 'UTC' },+ { scheduleTimezone: 'Asia/Shanghai' },+ { count: 1, from },+ ),+ ).toEqual({ preview: 'next runs (Asia/Shanghai) β Sat 2026-09-26 09:00', valid: true });+ });++ it('rejects an invalid timezone even when no pattern is set', () => {+ expect(validateScheduleUpdate(null, { scheduleTimezone: 'Mars/Base' })).toMatchObject({+ valid: false,+ });+ expect(validateScheduleUpdate(null, { scheduleTimezone: null })).toBeUndefined();+ });+});diff --git a/packages/utils/src/cronEval.ts b/packages/utils/src/cronEval.tsindex e8d31ecd290..bcea488695b 100644--- a/packages/utils/src/cronEval.ts+++ b/packages/utils/src/cronEval.ts@@ -1,169 +1,241 @@-import dayjs from 'dayjs';-import timezone from 'dayjs/plugin/timezone';-import utc from 'dayjs/plugin/utc';--dayjs.extend(utc);-dayjs.extend(timezone);+import { CronExpressionParser } from 'cron-parser';export interface IsExecutionTimeInput {+ /**+ * When the schedule was (re)armed. An occurrence before it is never fired:+ * arming after a slot has passed waits for the next one, even when the task+ * has never run or its last run is older than the arming.+ */+ armedAt?: Date | null;/** Cron pattern in standard 5-field form: `minute hour day month weekday`. */cronPattern: string;/** Defaults to `Date.now()` when omitted β exposed for tests. */currentTime?: Date;- /** Last successful execution; used to dedup within the same window. */+ /**+ * How long after a scheduled occurrence a dispatcher tick may still fire it.+ * Covers a late or skipped tick of the central dispatcher; an occurrence+ * older than this is skipped rather than replayed.+ */+ graceMinutes?: number;+ /** Last successful execution; an occurrence at or before it is already covered. */lastExecutedAt?: Date | null;/** IANA timezone (e.g. `Asia/Shanghai`); defaults to `UTC` when null/empty. */timezone: string | null;- /** Tolerance window in minutes β central dispatchers run on a coarse cadence- * (e.g. every 30 min), so an exact-minute match is too brittle. */- toleranceMinutes?: number;}-const DAILY_PATTERN_HOUR_REGEX = /^\d+$/;+/**+ * Cadence of the central schedule dispatcher (`lobe-task-schedule-dispatch`,+ * `*\/10 * * * *` in `scripts/serverLauncher/startServer.js`).+ */+export const SCHEDULE_DISPATCH_INTERVAL_MINUTES = 10;/**- * Decide whether a cron pattern is "due now" within a tolerance window.+ * An occurrence can be up to one interval old on the tick that should fire it;+ * tolerate one more missed tick plus delivery jitter. Anything older is skipped+ * rather than replayed, so a stale slot never fires long after the fact.+ */+export const DEFAULT_SCHEDULE_GRACE_MINUTES = SCHEDULE_DISPATCH_INTERVAL_MINUTES * 2 + 5;++const CRON_FIELD_COUNT = 5;+const MINUTE_MS = 60 * 1000;++export const isValidTimezone = (tz: string): boolean => {+ try {+ new Intl.DateTimeFormat('en-US', { timeZone: tz });+ return true;+ } catch {+ return false;+ }+};++const parseCron = (cronPattern: string, timezone: string | null, currentDate: Date) => {+ const pattern = cronPattern.trim();+ // Only the standard 5-field form is accepted: 6-field (seconds) and `@daily`+ // style aliases are rejected so every stored pattern means the same thing to+ // the dispatcher, the task UI and the agent that wrote it.+ if (pattern.split(/\s+/).length !== CRON_FIELD_COUNT) {+ throw new Error(+ `expected 5 fields "minute hour day-of-month month day-of-week", got "${cronPattern}"`,+ );+ }+ const tz = timezone || 'UTC';+ if (!isValidTimezone(tz)) throw new Error(`unknown timezone "${tz}"`);++ return CronExpressionParser.parse(pattern, { currentDate, tz });+};++/**+ * Find the occurrence a cron pattern is due for on this dispatcher tick, or+ * `null` when nothing is due. The returned instant identifies the occurrence,+ * so the dispatcher can reserve it and never publish it twice.*- * Designed for a central dispatcher polling on a fixed cadence (e.g. QStash- * Schedule firing every 30 minutes). The matcher:+ * The central dispatcher polls on a fixed cadence (every 10 minutes), so the+ * question is not "does `now` match the pattern" but "is there a scheduled+ * occurrence that has passed and has not run yet". The matcher:*- * - Converts the dispatcher's UTC `now` to the pattern's local timezone.- * - Dedups against `lastExecutedAt` so the same pattern doesn't fire twice- * within its own interval (e.g. a daily 09:00 job won't refire at 09:15- * on the same day in `Asia/Shanghai`).- * - Catches up missed daily runs: if the dispatcher missed the scheduled hour- * (downtime / cold start) and the job hasn't run today yet, a later tick- * on the same day still fires it.+ * - Finds `prev`, the latest occurrence at or before `now` within the grace+ * window, in the pattern's timezone with full cron semantics (day-of-month,+ * month, ranges, steps, lists, names).+ * - Fires only when such an occurrence exists, so a task never fires+ * ahead of its occurrence.+ * - Fires only when `prev` is at or after `armedAt`, so arming a task after+ * today's slot has passed waits for the next slot instead of replaying the+ * missed one.+ * - Fires only when `lastExecutedAt < prev`, so each occurrence runs at most+ * once no matter how many ticks fall inside the grace window. A manual run+ * before the occurrence does not consume it.*- * Supported patterns (matches what `packages/utils/src/cron.ts` produces):+ * The grace window spans more than one tick, so `lastExecutedAt` alone cannot+ * stop a second tick from re-firing an occurrence whose run has not started+ * yet; callers pass the latest reserved occurrence into it as well.*- * - `*\/N * * * *` β every N minutes- * - `M * * * *` β every hour at minute M- * - `M *\/N * * *` β every N hours at minute M- * - `M H * * *` β daily at H:M- * - `M H * * D[,D]` β weekly on weekday list at H:M- * - `M *,M * * *` β minute list (e.g. `0,15,30,45`)- * - `M H,H * * *` β hour list+ * Invalid patterns or timezones never fire; use `validateCronPattern` on the+ * write path to reject them up front.*/-export const isExecutionTime = (input: IsExecutionTimeInput): boolean => {+export const findDueOccurrence = (input: IsExecutionTimeInput): Date | null => {const {+ armedAt,cronPattern,- timezone: tz,+ timezone,lastExecutedAt,currentTime = new Date(),- toleranceMinutes = 5,+ graceMinutes = DEFAULT_SCHEDULE_GRACE_MINUTES,} = input;- const jobTimezone = tz || 'UTC';- const localTime = dayjs(currentTime).tz(jobTimezone);- const minute = localTime.minute();- const hour = localTime.hour();-- const parts = cronPattern.trim().split(/\s+/);- if (parts.length !== 5) return false;- const [cronMinute, cronHour, , , cronWeekday] = parts;-- // ββ Dedup against last execution ββββββββββββββββββββββββββββββββ- if (lastExecutedAt) {- const last = new Date(lastExecutedAt);- const minutesSince = (currentTime.getTime() - last.getTime()) / (1000 * 60);-- if (cronMinute.startsWith('*/')) {- const minIntervalMin = Number.parseInt(cronMinute.slice(2), 10);- if (Number.isFinite(minIntervalMin) && minutesSince < minIntervalMin) return false;- } else if (cronHour.startsWith('*/')) {- const hourInterval = Number.parseInt(cronHour.slice(2), 10);- if (Number.isFinite(hourInterval) && minutesSince < hourInterval * 60) return false;- } else if (cronHour === '*') {- // Every hour at a specific minute (e.g. `30 * * * *`)- if (minutesSince < 60) return false;- } else if (DAILY_PATTERN_HOUR_REGEX.test(cronHour)) {- // Daily at specific H:M β dedup against today's scheduled target, not- // the calendar day. A pre-target manual run (e.g. user clicks "run now"- // at 18:00 for a 21:00 schedule) must NOT consume the upcoming tick.- const targetHour = Number.parseInt(cronHour, 10);- const targetMinute = /^\d+$/.test(cronMinute) ? Number.parseInt(cronMinute, 10) : 0;- const todaysTarget = dayjs(currentTime)- .tz(jobTimezone)- .hour(targetHour)- .minute(targetMinute)- .second(0)- .millisecond(0);- if (last.getTime() >= todaysTarget.valueOf()) {- return false;- }- }+ let expression: ReturnType<typeof parseCron>;+ try {+ expression = parseCron(cronPattern, timezone, currentTime);+ } catch {+ return null;}- const weekday = localTime.day();-- // ββ Daily catch-up: scheduled hour passed today and we haven't run yet ββ- const isDailyPattern =- DAILY_PATTERN_HOUR_REGEX.test(cronHour) && /^(?:\d+|\*\/\d+)$/.test(cronMinute);-- if (isDailyPattern) {- const targetHour = Number.parseInt(cronHour, 10);- let shouldCatchUp: boolean;-- if (lastExecutedAt) {- const targetMinute = /^\d+$/.test(cronMinute) ? Number.parseInt(cronMinute, 10) : 0;- const todaysTarget = dayjs(currentTime)- .tz(jobTimezone)- .hour(targetHour)- .minute(targetMinute)- .second(0)- .millisecond(0);- const lastCoveredToday = new Date(lastExecutedAt).getTime() >= todaysTarget.valueOf();- shouldCatchUp = !lastCoveredToday && hour > targetHour;- } else {- shouldCatchUp = hour > targetHour;- }-- if (shouldCatchUp) {- if (cronWeekday !== '*') {- const allowedWeekdays = cronWeekday.split(',').map((d) => Number.parseInt(d.trim(), 10));- if (!allowedWeekdays.includes(weekday)) return false;- }- return true;+ // Walk the grace window backwards minute by minute instead of calling+ // `prev()`: the dispatcher evaluates every scheduled task on each tick, and+ // `prev()` on a sparse pattern (e.g. a yearly date) scans a whole year.+ const nowMinute = Math.floor(currentTime.getTime() / MINUTE_MS) * MINUTE_MS;+ let prev: number | undefined;+ for (let offset = 0; offset <= graceMinutes; offset += 1) {+ const candidate = nowMinute - offset * MINUTE_MS;+ if (expression.includesDate(new Date(candidate))) {+ prev = candidate;+ break;}}- // ββ Minute field ββββββββββββββββββββββββββββββββββββββββββββββββ- if (cronMinute !== '*') {- if (cronMinute.startsWith('*/')) {- const interval = Number.parseInt(cronMinute.slice(2), 10);- if (!Number.isFinite(interval) || interval <= 0) return false;- const lastSlot = Math.floor(minute / interval) * interval;- if (minute - lastSlot > toleranceMinutes) return false;- } else if (cronMinute.includes(',')) {- const allowed = cronMinute.split(',').map((m) => Number.parseInt(m, 10));- if (!allowed.some((target) => Math.abs(minute - target) <= toleranceMinutes)) return false;- } else {- const target = Number.parseInt(cronMinute, 10);- if (Math.abs(minute - target) > toleranceMinutes) return false;- }- }+ if (prev === undefined) return null;+ if (armedAt && new Date(armedAt).getTime() > prev) return null;+ if (lastExecutedAt && new Date(lastExecutedAt).getTime() >= prev) return null;- // ββ Hour field ββββββββββββββββββββββββββββββββββββββββββββββββββ- if (cronHour !== '*') {- if (cronHour.startsWith('*/')) {- const interval = Number.parseInt(cronHour.slice(2), 10);- if (!Number.isFinite(interval) || interval <= 0) return false;- const lastSlot = Math.floor(hour / interval) * interval;- if (hour - lastSlot > 0) return false;- } else if (cronHour.includes(',')) {- const allowed = cronHour.split(',').map((h) => Number.parseInt(h, 10));- if (!allowed.includes(hour)) return false;- } else {- if (hour !== Number.parseInt(cronHour, 10)) return false;- }- }+ return new Date(prev);+};++/** Whether `findDueOccurrence` finds an occurrence to fire on this tick. */+export const isExecutionTime = (input: IsExecutionTimeInput): boolean =>+ findDueOccurrence(input) !== null;++export type CronValidationResult =+ { error: string; valid: false } | { nextRuns: Date[]; valid: true };- // ββ Weekday field βββββββββββββββββββββββββββββββββββββββββββββββ- if (cronWeekday !== '*') {- const allowed = cronWeekday.split(',').map((d) => Number.parseInt(d.trim(), 10));- if (!allowed.includes(weekday)) return false;+/**+ * Validate a cron pattern for the task scheduler and preview its next runs.+ *+ * Rejects anything the dispatcher cannot evaluate (wrong field count, out of+ * range values, unknown timezone) and patterns that never occur (e.g.+ * `0 0 30 2 *`), so callers can refuse the write instead of storing a+ * schedule that silently misfires.+ */+export const validateCronPattern = (+ cronPattern: string,+ timezone: string | null,+ options: { count?: number; from?: Date } = {},+): CronValidationResult => {+ const { count = 3, from = new Date() } = options;+ try {+ const expression = parseCron(cronPattern, timezone, from);+ const nextRuns = expression.take(count).map((date) => new Date(date.getTime()));+ if (nextRuns.length === 0) return { error: 'the pattern never occurs', valid: false };+ return { nextRuns, valid: true };+ } catch (error) {+ return { error: error instanceof Error ? error.message : String(error), valid: false };}+};++/** "next runs (Asia/Shanghai) β Mon 2026-09-28 09:00; β¦" so the agent can check the schedule it set. */+export const formatScheduleNextRuns = (runs: Date[], timezone: string | null): string => {+ const tz = timezone || 'UTC';+ const format = new Intl.DateTimeFormat('en-CA', {+ day: '2-digit',+ hour: '2-digit',+ hourCycle: 'h23',+ minute: '2-digit',+ month: '2-digit',+ timeZone: tz,+ weekday: 'short',+ year: 'numeric',+ });+ const label = (date: Date) => {+ const parts = Object.fromEntries(format.formatToParts(date).map((p) => [p.type, p.value]));+ return `${parts.weekday} ${parts.year}-${parts.month}-${parts.day} ${parts.hour}:${parts.minute}`;+ };+ return `next runs (${tz}) β ${runs.map(label).join('; ')}`;+};- return true;+export type SchedulePreviewResult =+ { error: string; valid: false } | { preview: string; valid: true };++/**+ * Validate the schedule a task will end up with and describe its next runs,+ * shared by every runtime of the `setTaskSchedule` tool so they all return the+ * same confirmation (or refusal) to the agent.+ */+export const previewSchedule = (+ cronPattern: string,+ timezone: string | null,+ options: { count?: number; from?: Date } = {},+): SchedulePreviewResult => {+ const result = validateCronPattern(cronPattern, timezone, options);+ if (!result.valid) return result;+ return { preview: formatScheduleNextRuns(result.nextRuns, timezone), valid: true };+};++/** The refusal both runtimes return when `setTaskSchedule` is given an unusable schedule. */+export const formatInvalidScheduleMessage = (identifier: string, error: string): string =>+ `Invalid schedule for task ${identifier}: ${error}. Use a standard 5-field cron expression "minute hour day-of-month month day-of-week" (e.g. "0 9 * * 1-5") with an IANA timezone. Nothing was updated.`;++export interface ScheduleUpdatePatch {+ automationMode?: string | null;+ schedulePattern?: string | null;+ scheduleTimezone?: string | null;+}++/**+ * Validate the pattern/timezone pair a task will end up with after `patch` is+ * applied to its stored schedule. A field the patch leaves out keeps its+ * stored value, so a pattern-only change is checked against the stored+ * timezone and enabling schedule mode re-checks the stored pair: a legacy+ * invalid value is refused instead of being carried into a schedule the+ * dispatcher can never run.+ *+ * Returns `undefined` when the patch does not touch the schedule or leaves no+ * pattern to check, otherwise the same result as `previewSchedule`.+ */+export const validateScheduleUpdate = (+ stored: { pattern?: string | null; timezone?: string | null } | null | undefined,+ patch: ScheduleUpdatePatch,+ options: { count?: number; from?: Date } = {},+): SchedulePreviewResult | undefined => {+ const touched =+ patch.schedulePattern !== undefined ||+ patch.scheduleTimezone !== undefined ||+ patch.automationMode === 'schedule';+ if (!touched) return undefined;++ const pattern = patch.schedulePattern !== undefined ? patch.schedulePattern : stored?.pattern;+ const timezone = patch.scheduleTimezone !== undefined ? patch.scheduleTimezone : stored?.timezone;++ if (pattern) return previewSchedule(pattern, timezone ?? null, options);+ if (timezone && !isValidTimezone(timezone)) {+ return { error: `unknown timezone "${timezone}"`, valid: false };+ }+ return undefined;};diff --git a/packages/utils/src/cronEval.vent.test.ts b/packages/utils/src/cronEval.vent.test.tsnew file mode 100644index 00000000000..3226a7ff066--- /dev/null+++ b/packages/utils/src/cronEval.vent.test.ts@@ -0,0 +1,155 @@+import { describe, expect, it } from 'vitest';++import { isExecutionTime, SCHEDULE_DISPATCH_INTERVAL_MINUTES } from './cronEval';++const at = (iso: string) => new Date(iso);++// Reproductions of scheduled tasks that fired early, fired twice, or stopped+// firing in production. Times and patterns are copied from real task rows.+describe('isExecutionTime β scheduled task misfire regressions', () => {+ it('A: one-shot date cron must not fire 7 days early (T-9, Asia/Shanghai)', () => {+ expect(+ isExecutionTime({+ cronPattern: '0 10 27 9 *',+ currentTime: at('2026-09-20T03:20:00Z'),+ lastExecutedAt: null,+ timezone: 'Asia/Shanghai',+ }),+ ).toBe(false);+ });++ it('A: one-shot date cron must not fire 5 weeks early (T-2, Europe/Moscow)', () => {+ expect(+ isExecutionTime({+ cronPattern: '0 12 27 10 *',+ currentTime: at('2026-09-18T20:00:00Z'),+ lastExecutedAt: null,+ timezone: 'Europe/Moscow',+ }),+ ).toBe(false);+ });++ it('E: freshly armed daily "5 0" must wait for next 00:05, not fire at 01:55', () => {+ expect(+ isExecutionTime({+ cronPattern: '5 0 * * *',+ currentTime: at('2026-09-17T15:55:00Z'),+ lastExecutedAt: null,+ timezone: 'Australia/Sydney',+ }),+ ).toBe(false);+ });++ it('B: "5 0 * * *" must not fire at 00:00 (before target)', () => {+ expect(+ isExecutionTime({+ cronPattern: '5 0 * * *',+ currentTime: at('2026-09-18T14:00:00Z'),+ lastExecutedAt: at('2026-09-17T14:06:00Z'),+ timezone: 'Australia/Sydney',+ }),+ ).toBe(false);+ });++ it('C: hour-list "0 8,10,...,20" must not refire at :05 after running at :00', () => {+ expect(+ isExecutionTime({+ cronPattern: '0 8,10,12,14,16,18,20 * * *',+ currentTime: at('2026-09-21T19:05:00Z'),+ lastExecutedAt: at('2026-09-21T19:02:33Z'),+ timezone: 'America/Los_Angeles',+ }),+ ).toBe(false);+ });++ it('D: "45 11 * * 1-5" must fire on Tuesday 11:45 (T-13)', () => {+ expect(+ isExecutionTime({+ cronPattern: '45 11 * * 1-5',+ currentTime: at('2026-09-22T04:45:00Z'),+ lastExecutedAt: at('2026-09-21T05:00:24Z'),+ timezone: 'Asia/Ho_Chi_Minh',+ }),+ ).toBe(true);+ });++ describe('dispatcher replay (10-minute ticks from the arm time)', () => {+ const TICK_MS = SCHEDULE_DISPATCH_INTERVAL_MINUTES * 60 * 1000;++ /** Replays the central dispatcher and returns every tick that fired. */+ const replay = (cronPattern: string, timezone: string, armedAt: string, until: string) => {+ const fires: string[] = [];+ let lastExecutedAt: Date | null = null;+ const start = Math.ceil(at(armedAt).getTime() / TICK_MS) * TICK_MS;+ for (let t = start; t <= at(until).getTime(); t += TICK_MS) {+ const currentTime = new Date(t);+ if (+ isExecutionTime({+ armedAt: at(armedAt),+ cronPattern,+ currentTime,+ lastExecutedAt,+ timezone,+ })+ ) {+ fires.push(currentTime.toISOString());+ lastExecutedAt = currentTime;+ }+ }+ return fires;+ };++ it('A1: T-9 "0 10 27 9 *" armed 09-20 fires only on 09-27 10:00 Shanghai', () => {+ expect(+ replay('0 10 27 9 *', 'Asia/Shanghai', '2026-09-20T03:15:55Z', '2026-09-28T00:00:00Z'),+ ).toEqual(['2026-09-27T02:00:00.000Z']);+ });++ it('B1: Sydney "5 0 * * *" fires once per night, on the first tick after 00:05', () => {+ expect(+ replay('5 0 * * *', 'Australia/Sydney', '2026-09-17T15:50:17Z', '2026-09-20T23:00:00Z'),+ ).toEqual([+ '2026-09-18T14:10:00.000Z',+ '2026-09-19T14:10:00.000Z',+ '2026-09-20T14:10:00.000Z',+ ]);+ });++ it('C1: LA hour list fires once per window', () => {+ expect(+ replay(+ '0 8,10,12,14,16,18,20 * * *',+ 'America/Los_Angeles',+ '2026-09-21T14:30:00Z',+ '2026-09-22T04:00:00Z',+ ),+ ).toEqual([+ '2026-09-21T15:00:00.000Z',+ '2026-09-21T17:00:00.000Z',+ '2026-09-21T19:00:00.000Z',+ '2026-09-21T21:00:00.000Z',+ '2026-09-21T23:00:00.000Z',+ '2026-09-22T01:00:00.000Z',+ '2026-09-22T03:00:00.000Z',+ ]);+ });++ it('D1: T-13 "45 11 * * 1-5" fires every weekday (11:50 tick), not only Monday', () => {+ expect(+ replay('45 11 * * 1-5', 'Asia/Ho_Chi_Minh', '2026-09-21T13:01:40Z', '2026-09-28T23:00:00Z'),+ ).toEqual([+ '2026-09-22T04:50:00.000Z',+ '2026-09-23T04:50:00.000Z',+ '2026-09-24T04:50:00.000Z',+ '2026-09-25T04:50:00.000Z',+ '2026-09-28T04:50:00.000Z',+ ]);+ });++ it('E1: daily "0 9 * * *" armed at 09:05 skips that 09:00 and fires the next day', () => {+ expect(replay('0 9 * * *', 'UTC', '2026-09-21T09:05:00Z', '2026-09-22T12:00:00Z')).toEqual([+ '2026-09-22T09:00:00.000Z',+ ]);+ });+ });+});