import { existsSync } from 'node:fs'; import { mkdir, mkdtemp, readFile, rm, unlink, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; import type { PluginRuntimeContext, RunAgentTurnResult } from '../../../src/plugin-sdk.js'; import { sessionFileFor } from '../../../src/context/sessionPath.js'; import type { CronTask } from '../src/types.js'; let root = ''; let store: typeof import('../src/store.js'); let commands: typeof import('../src/commands.js'); let schedulerMod: typeof import('../src/scheduler.js'); let lockMod: typeof import('../src/lock.js'); const provider = { name: 'test', baseURL: 'https://example.invalid', apiKey: 'test', model: 'test-model', contextWindow: 128000, }; describe('cron-runner store and scheduler', () => { beforeAll(async () => { root = await mkdtemp(join(tmpdir(), 'cron-runner-test-')); process.env.MINIMAL_AGENT_HOME = root; process.env.MINIMAL_AGENT_CRON_RUNNER_HOME = root; process.env.MINIMAL_AGENT_CRON_DISABLE_JITTER = '1'; store = await import('../src/store.js'); const commandModule = await import('../src/commands.js'); commands = { ...commandModule, handleCronCommand: (name, args, scheduler, context) => commandModule.handleCronCommand(name, args, scheduler, context ?? { cwd: root, sessionId: 'test-session' }) }; schedulerMod = await import('../src/scheduler.js'); lockMod = await import('../src/lock.js'); }); afterAll(async () => { delete process.env.MINIMAL_AGENT_HOME; delete process.env.MINIMAL_AGENT_CRON_RUNNER_HOME; delete process.env.MINIMAL_AGENT_CRON_DISABLE_JITTER; if (root) await rm(root, { recursive: true, force: true }); }); async function createBoundSession(cwd: string, sessionId: string): Promise { const sessionFile = sessionFileFor(cwd, sessionId); await mkdir(join(sessionFile, '..'), { recursive: true }); await writeFile(sessionFile, JSON.stringify({ messages: [{ role: 'system', content: 'test' }] }), 'utf8'); } test('creates, pauses, resumes, shows, and deletes tasks through command handler', async () => { const created = await commands.handleCronCommand( 'cron', 'create --name "Morning" --cron "7 6 * * 1" --prompt "hello"', null, ); expect(created).toContain('已创建 cron'); let tasks = await store.listTasks(); expect(tasks).toHaveLength(1); expect(tasks[0]!.name).toBe('Morning'); expect(tasks[0]!.status).toBe('active'); expect(await commands.handleCronCommand('cron', `pause ${tasks[0]!.id}`, null)).toContain('已暂停'); tasks = await store.listTasks(); expect(tasks[0]!.status).toBe('paused'); expect(await commands.handleCronCommand('cron', `resume ${tasks[0]!.id}`, null)).toContain('已恢复'); expect(await commands.handleCronCommand('crons', '', null)).toContain('下次运行'); expect(await commands.handleCronCommand('cron', `show ${tasks[0]!.id}`, null)).toContain('最近运行'); expect(await commands.handleCronCommand('cron', `delete ${tasks[0]!.id}`, null)).toContain('已删除'); expect(await store.listTasks()).toHaveLength(0); }); test('creates tasks with friendly shortcut syntax', async () => { await commands.handleCronCommand('cron', '120m 整理最近 AI 新闻', null); await commands.handleCronCommand('cron', '2h 两小时巡检', null); await commands.handleCronCommand('cron', '1w 每周素材整理', null); await commands.handleCronCommand('cron', '1d 每日国际新闻 /workflow research 生成中文新闻稿', null); await commands.handleCronCommand('cron', '1m 检查学生作业 workflow plan camera.jpg', null); await commands.handleCronCommand('cron', '每天 6:07 写国际 AI 晨间简报', null); await commands.handleCronCommand('cron', '工作日 6:07 写过去 48 小时国际 AI 大事', null); await commands.handleCronCommand('cron', '每周一 6:07 整理国际 AI 超级个体创业案例', null); const tasks = await store.listTasks(); expect(tasks.some((t) => t.schedule.type === 'interval' && t.schedule.intervalMs === 120 * 60_000)).toBe(true); expect(tasks.some((t) => t.schedule.type === 'interval' && t.schedule.intervalMs === 2 * 60 * 60_000)).toBe(true); expect(tasks.some((t) => t.schedule.type === 'interval' && t.schedule.intervalMs === 7 * 24 * 60 * 60_000)).toBe(true); expect(tasks.some((t) => t.schedule.type === 'cron' && t.schedule.cron === '7 6 * * *')).toBe(true); expect(tasks.some((t) => t.schedule.type === 'cron' && t.schedule.cron === '7 6 * * 1-5')).toBe(true); expect(tasks.some((t) => t.schedule.type === 'cron' && t.schedule.cron === '7 6 * * 1')).toBe(true); const daily = tasks.find((t) => t.description === '每日国际新闻'); expect(daily?.action).toEqual({ type: 'workflow', command: 'research 生成中文新闻稿' }); expect(daily?.schedule.type).toBe('interval'); const camera = tasks.find((t) => t.description === '检查学生作业'); expect(camera?.action).toEqual({ type: 'workflow', command: 'plan camera.jpg' }); expect(camera?.schedule.type === 'interval' && camera.schedule.intervalMs).toBe(60_000); }); test('friendly shortcuts reject invalid intervals and missing workflow names', async () => { expect(await commands.handleCronCommand('cron', '0m inspect', null)).toContain('无效间隔'); expect(await commands.handleCronCommand('cron', '1x inspect', null)).toContain('无效间隔'); expect(await commands.handleCronCommand('cron', '1d task /workflow', null)).toContain( '缺少工作流名称', ); }); test('migrates old task shape and writes tasks atomically', async () => { const taskRoot = join(root, 'cron-runner'); await mkdir(taskRoot, { recursive: true }); await writeFile( join(taskRoot, 'tasks.json'), JSON.stringify({ tasks: [ { id: 'cron-old', name: 'Old', status: 'active', schedule: { cron: '7 6 * * 1', human: 'old' }, action: { type: 'prompt', prompt: 'hello' }, runtime: { cwd: process.cwd(), environment: 'project', sessionId: 'cron-old' }, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), }, ], }), ); const tasks = await store.listTasks(); expect(tasks[0]!.kind).toBe('recurring'); expect(tasks[0]!.stats.runCount).toBe(0); expect(tasks[0]!.stats.skippedCount).toBe(0); expect(tasks[0]!.runtime.sessionMode).toBe('persistent'); expect(tasks[0]!.schedule.type).toBe('cron'); if (tasks[0]!.schedule.type === 'cron') expect(tasks[0]!.schedule.timezone).toBeTruthy(); await store.writeTasks(tasks); const raw = await readFile(join(taskRoot, 'tasks.json'), 'utf8'); expect(JSON.parse(raw).tasks[0].kind).toBe('recurring'); }); test('manual run writes success history and stats', async () => { const sessionId = 'manual-run-session'; await createBoundSession(process.cwd(), sessionId); const task = store.createTask({ name: 'Run me', cron: '* * * * *', timezone: 'local', cwd: process.cwd(), sessionId, action: { type: 'prompt', prompt: 'hello' }, }); await store.upsertTask(task); const ctx: PluginRuntimeContext = { provider, runAgentTurn: async (): Promise => ({ ok: true, result: 'done', numTurns: 1, events: [{ type: 'turn_done', completionStatus: 'completed' }], }), }; const scheduler = new schedulerMod.Scheduler(ctx); await scheduler.runTaskNow(task.id); const updated = await store.getTask(task.id); expect(updated?.stats.runCount).toBe(1); expect(updated?.stats.successCount).toBe(1); const runs = await store.recentRuns(task.id, 10); expect(runs.some((r) => r.status === 'success')).toBe(true); expect(runs.filter((r) => r.id === runs[0]!.id)).toHaveLength(1); }); test('manual run completes once tasks after completion', async () => { const sessionId = 'once-run-session'; await createBoundSession(process.cwd(), sessionId); const task = store.createTask({ name: 'Once', cron: '* * * * *', timezone: 'local', cwd: process.cwd(), sessionId, kind: 'once', action: { type: 'prompt', prompt: 'hello' }, }); await store.upsertTask(task); const ctx: PluginRuntimeContext = { provider, runAgentTurn: async (): Promise => ({ ok: false, result: '', error: 'failed', numTurns: 1, events: [], }), }; const scheduler = new schedulerMod.Scheduler(ctx); await scheduler.runTaskNow(task.id); const updated = await store.getTask(task.id); expect(updated?.status).toBe('completed'); expect(updated?.stats.failureCount).toBe(1); }); test('missed command lists recorded missed tasks', async () => { await store.appendMissed({ id: 'missed-test', taskId: 'cron-missed', taskName: 'Missed', scheduledFor: new Date().toISOString(), detectedAt: new Date().toISOString(), actionPreview: 'hello', reason: 'offline', missedCount: 1, }); const text = await commands.handleCronCommand('cron', 'missed', null); expect(text).toContain('错过任务'); expect(text).toContain('cron-missed'); }); test('scheduler lock refuses live owners and recovers stale owners', async () => { const lockFile = join(root, 'cron-runner', 'test-scheduler.lock'); await writeFile( lockFile, JSON.stringify({ owner: 'live-owner', pid: process.pid, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), }), ); expect(await lockMod.tryAcquireSchedulerLock(lockFile, 'other-owner')).toBe(false); await writeFile( lockFile, JSON.stringify({ owner: 'stale-owner', pid: 9_999_999, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), }), ); expect(await lockMod.tryAcquireSchedulerLock(lockFile, 'new-owner')).toBe(true); await lockMod.releaseSchedulerLock(lockFile, 'new-owner'); }); test('scheduler stop releases its lock before a replacement starts', async () => { await store.writeTasks([]); const ctx: PluginRuntimeContext = { provider, runAgentTurn: async (): Promise => ({ ok: true, result: 'ok', numTurns: 1, events: [{ type: 'turn_done', completionStatus: 'completed' }], }), }; const first = new schedulerMod.Scheduler(ctx); first.start(); await waitFor(async () => await first.isActiveScheduler()); await first.stop(); const second = new schedulerMod.Scheduler(ctx); second.start(); await waitFor(async () => await second.isActiveScheduler()); expect(await second.isActiveScheduler()).toBe(true); await second.stop(); }); test('scheduler stop aborts and drains an in-flight task', async () => { const sessionId = 'long-run-session'; await createBoundSession(process.cwd(), sessionId); const task = store.createTask({ name: 'Long run', cron: '* * * * *', timezone: 'local', cwd: process.cwd(), sessionId, action: { type: 'prompt', prompt: 'wait' }, }); await store.upsertTask(task); let started = false; const scheduler = new schedulerMod.Scheduler({ provider, runAgentTurn: async (opts): Promise => { started = true; await new Promise((resolve) => { if (opts.signal?.aborted) resolve(); else opts.signal?.addEventListener('abort', () => resolve(), { once: true }); }); return { ok: false, result: '', error: 'aborted', numTurns: 0, events: [] }; }, }); const running = scheduler.runTaskNow(task.id); await waitFor(async () => started); await scheduler.stop(); await running; const updated = await store.getTask(task.id); expect(updated?.stats.failureCount).toBe(0); expect((await store.recentRuns(task.id))[0]?.status).toBe('cancelled'); }); test('nextRunAt is a sane near-future time for every task, never the Unix epoch (map-index regression)', async () => { // 真机 e2e 抓到的回归:listTasks/writeTasks 曾写成 .map(refreshNextRun),Array.map 把 // (element, index, array) 全传进去 → 第二实参 index(0,1,2...) 顶掉了 refreshNextRun 的 // fromMs=Date.now() 默认值 → nextCronRunMs 从 Unix 纪元(≈0ms)起算 → nextRunAt 恒为 // 1970-01-01。这里建**多个**任务,断言每一个(尤其 index>0)的 nextRunAt 都落在「现在」 // 附近的未来,绝不落在 1970——修复前 index=0 那条必 < now,本用例会红。 const a = store.createTask({ name: 'Every-min A', cron: '* * * * *', timezone: 'local', cwd: process.cwd(), action: { type: 'prompt', prompt: 'a' } }); const b = store.createTask({ name: 'Every-min B', cron: '* * * * *', timezone: 'local', cwd: process.cwd(), action: { type: 'prompt', prompt: 'b' } }); await store.upsertTask(a); await store.upsertTask(b); const now = Date.now(); const mine = (await store.listTasks()).filter((t) => t.id === a.id || t.id === b.id); expect(mine).toHaveLength(2); for (const t of mine) { const iso = t.schedule.nextRunAt; expect(iso).toBeTruthy(); const ms = Date.parse(iso!); expect(Number.isFinite(ms)).toBe(true); // 全通配下一次运行必在未来 1 分钟内;留 5s 容差防跨秒抖动。关键:绝不能是 1970。 expect(ms).toBeGreaterThan(now - 5_000); expect(ms).toBeLessThan(now + 65_000); expect(new Date(ms).getUTCFullYear()).toBeGreaterThanOrEqual(2025); } }); test('maxRuns completes the task after N runs (generalizes once)', async () => { const sessionId = 'max-runs-session'; await createBoundSession(process.cwd(), sessionId); const task = store.createTask({ name: 'Twice', cron: '* * * * *', timezone: 'local', cwd: process.cwd(), sessionId, maxRuns: 2, action: { type: 'prompt', prompt: 'hi' }, }); await store.upsertTask(task); const ctx: PluginRuntimeContext = { provider, runAgentTurn: async (): Promise => ({ ok: true, result: 'ok', numTurns: 1, events: [{ type: 'turn_done', completionStatus: 'completed' }] }), }; const scheduler = new schedulerMod.Scheduler(ctx); await scheduler.runTaskNow(task.id); expect((await store.getTask(task.id))?.status).toBe('active'); // 1/2 未满,继续 await scheduler.runTaskNow(task.id); const done = await store.getTask(task.id); expect(done?.status).toBe('completed'); // 2/2 达到 → 完成 expect(done?.stats.runCount).toBe(2); }); test('overlapping interval slots are skipped and never queued for catch-up', async () => { const now = Date.parse('2026-07-10T10:05:20.000Z'); const anchor = '2026-07-10T10:00:00.000Z'; const task = store.createTask({ name: 'Camera', intervalMs: 60_000, anchorAt: anchor, timezone: 'local', cwd: process.cwd(), action: { type: 'prompt', prompt: 'inspect' }, }); task.createdAt = anchor; task.schedule.lastScheduledFor = '2026-07-10T10:01:00.000Z'; await store.upsertTask(task); let calls = 0; const scheduler = new schedulerMod.Scheduler({ provider, runAgentTurn: async (): Promise => { calls++; return { ok: true, result: 'ok', numTurns: 1, events: [{ type: 'turn_done', completionStatus: 'completed' }] }; }, }); const internal = scheduler as unknown as { executions: Map>; processDueTask(task: CronTask, now: number): Promise; }; internal.executions.set(task.id, new Promise(() => {})); await internal.processDueTask((await store.getTask(task.id))!, now); internal.executions.delete(task.id); await internal.processDueTask((await store.getTask(task.id))!, now); const updated = await store.getTask(task.id); expect(updated?.stats.skippedCount).toBe(4); expect(updated?.stats.runCount).toBe(0); expect(updated?.schedule.lastScheduledFor).toBe('2026-07-10T10:05:00.000Z'); expect(calls).toBe(0); const missed = await store.listMissed(20); expect(missed.some((item) => item.taskId === task.id && item.reason === 'overlap')).toBe(true); }); test('all cron runs reuse the bound original session', async () => { const seen: string[] = []; const ctx: PluginRuntimeContext = { provider, runAgentTurn: async (opts): Promise => { seen.push(opts.sessionId); return { ok: true, result: 'ok', numTurns: 1, events: [{ type: 'turn_done', completionStatus: 'completed' }] }; }, }; const firstSessionId = 'persistent-session-a'; const secondSessionId = 'persistent-session-b'; await createBoundSession(process.cwd(), firstSessionId); await createBoundSession(process.cwd(), secondSessionId); const persistent = store.createTask({ name: 'Persistent', cron: '* * * * *', timezone: 'local', cwd: process.cwd(), sessionId: firstSessionId, action: { type: 'prompt', prompt: 'x' }, }); const second = store.createTask({ name: 'Second persistent', cron: '* * * * *', timezone: 'local', cwd: process.cwd(), sessionId: secondSessionId, action: { type: 'prompt', prompt: 'x' }, }); await store.upsertTask(persistent); await store.upsertTask(second); const scheduler = new schedulerMod.Scheduler(ctx); await scheduler.runTaskNow(persistent.id); await scheduler.runTaskNow(persistent.id); await scheduler.runTaskNow(second.id); await scheduler.runTaskNow(second.id); expect(seen[0]).toBe(seen[1]); expect(seen[0]).toBe(persistent.runtime.sessionId); expect(seen[2]).toBe(seen[3]); expect(seen[2]).toBe(second.runtime.sessionId); }); test('deleting a bound session pauses the task instead of silently starting over', async () => { const fakeCwd = await mkdtemp(join(tmpdir(), 'cron-runner-session-test-')); const sessionId = 'my-bound-session'; const sessionFile = sessionFileFor(fakeCwd, sessionId); await mkdir(join(sessionFile, '..'), { recursive: true }); await writeFile(sessionFile, JSON.stringify({ messages: [{ role: 'system', content: 'x' }] }), 'utf8'); const task = store.createTask({ name: 'Bound to a real session', cron: '* * * * *', timezone: 'local', cwd: fakeCwd, sessionId, action: { type: 'prompt', prompt: 'hi' }, }); await store.upsertTask(task); expect(task.runtime.bindingStatus).toBe('bound'); let calls = 0; const ctx: PluginRuntimeContext = { provider, runAgentTurn: async (): Promise => { calls++; return { ok: true, result: 'ok', numTurns: 1, events: [{ type: 'turn_done', completionStatus: 'completed' }] }; }, }; const scheduler = new schedulerMod.Scheduler(ctx); // Session still exists: the task runs normally. await scheduler.runTaskNow(task.id); expect(calls).toBe(1); expect((await store.getTask(task.id))?.runtime.bindingStatus).toBe('bound'); // Simulate the desktop client deleting this session. expect(existsSync(sessionFile)).toBe(true); await unlink(sessionFile); await scheduler.runTaskNow(task.id); // Must NOT silently start a fresh turn against an empty history. expect(calls).toBe(1); const updated = await store.getTask(task.id); expect(updated?.runtime.bindingStatus).toBe('needs_binding'); expect(updated?.status).toBe('paused'); expect(updated?.stats.runCount).toBe(1); expect(updated?.stats.failureCount).toBe(0); const runs = await store.recentRuns(task.id, 10); expect(runs.filter((r) => r.status === 'success')).toHaveLength(1); const missed = await store.listMissed(); expect(missed.some((record) => record.taskId === task.id && record.reason === 'binding_unavailable')).toBe(true); await rm(fakeCwd, { recursive: true, force: true }); }); test('create --max-runs validates and persists the run limit', async () => { expect( await commands.handleCronCommand('cron', 'create --name Bad --cron "* * * * *" --prompt x --max-runs 0', null), ).toContain('无效 max-runs'); expect( await commands.handleCronCommand('cron', 'create --name Bad2 --cron "* * * * *" --prompt x --max-runs abc', null), ).toContain('无效 max-runs'); await commands.handleCronCommand('cron', 'create --name Good --cron "* * * * *" --prompt x --max-runs 3', null); const good = (await store.listTasks()).find((x) => x.name === 'Good'); expect(good?.maxRuns).toBe(3); }); test('create --workflow schedules a workflow action (cron × workflow-runner 联动路径)', async () => { await commands.handleCronCommand( 'cron', 'create --name "定时PPT" --cron "0 */2 * * *" --workflow "e2e-write-greet hello" --max-runs 2 --fresh-session', null, ); const t = (await store.listTasks()).find((x) => x.name === '定时PPT'); expect(t?.action).toEqual({ type: 'workflow', command: 'e2e-write-greet hello' }); expect(t?.maxRuns).toBe(2); expect(t?.runtime.sessionMode).toBe('fresh'); }); }); async function waitFor(check: () => Promise, timeoutMs = 500): Promise { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { if (await check()) return; await new Promise((resolve) => setTimeout(resolve, 5)); } throw new Error('condition not reached before timeout'); }