import { afterEach, beforeEach, expect, test } from 'bun:test'; import { mkdtemp, rm, readFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { Scheduler } from '../src/scheduler.js'; import { createTask, upsertTask, getTask, deleteTask, recentRuns, listTasks, } from '../src/store.js'; import { requestRun, requestStop } from '../src/requests.js'; import { updateCronFromPatch } from '../src/service.js'; import { handleCronCommand } from '../src/commands.js'; import { executionOutcome } from '../../../src/session/executionOutcome.js'; import { scheduleTool } from '../../../src/tools/schedule/schedule.js'; import { startBackgroundTask, type BackgroundTask, } from '../../../src/tools/tasks/backgroundTaskService.js'; import { taskTransaction, outsideTaskTransaction } from '../src/transaction.js'; import { compactRunLog, appendRun as appendRunFile, recentRuns as readRuns, } from '../src/runs.js'; import type { RunAgentTurnOptions, RunAgentTurnResult, } from '../../../src/session/runAgentTurn.js'; let root: string; let oldRoot: string | undefined; let oldHome: string | undefined; const schedulers: Scheduler[] = []; const provider = { name: 'test', baseURL: 'https://example.invalid', apiKey: 'test', model: 'test', contextWindow: 128000, }; const success = (): RunAgentTurnResult => ({ ok: true, result: 'ok', events: [{ type: 'turn_done', completionStatus: 'completed' }], numTurns: 1, }); const task = () => createTask({ name: 'audit', intervalMs: 60000, timezone: 'UTC', cwd: root, sessionMode: 'fresh', action: { type: 'prompt', prompt: 'old prompt' }, }); function scheduler( run: (o: RunAgentTurnOptions) => Promise, limits?: { concurrency: number; timeoutMs: number }, ) { const s = new Scheduler({ provider, runAgentTurn: run }, limits); schedulers.push(s); return s; } beforeEach(async () => { oldRoot = process.env.MINIMAL_AGENT_CRON_RUNNER_HOME; oldHome = process.env.MINIMAL_AGENT_HOME; root = await mkdtemp(join(tmpdir(), 'cron-lifecycle-')); process.env.MINIMAL_AGENT_CRON_RUNNER_HOME = root; process.env.MINIMAL_AGENT_HOME = root; }); afterEach(async () => { for (const s of schedulers.splice(0)) await s.stop(); await rm(root, { recursive: true, force: true }); if (oldRoot === undefined) delete process.env.MINIMAL_AGENT_CRON_RUNNER_HOME; else process.env.MINIMAL_AGENT_CRON_RUNNER_HOME = oldRoot; if (oldHome === undefined) delete process.env.MINIMAL_AGENT_HOME; else process.env.MINIMAL_AGENT_HOME = oldHome; }); test('deletion between task listing and enqueue cannot execute the deleted task', async () => { const t = task(); t.createdAt = new Date(Date.now() - 120000).toISOString(); if (t.schedule.type === 'interval') t.schedule.anchorAt = t.createdAt; t.catchUp = 'latest'; await upsertTask(t); let invoked = false; const s = scheduler(async () => { invoked = true; return success(); }); const engine = s as any; const processDue = engine.processDueTask.bind(s); engine.processDueTask = async (snapshot: typeof t, now: number) => { await requestStop(t.id); await deleteTask(t.id); await processDue(snapshot, now); }; await engine.reconcile(); await Promise.all(engine.executions.values()); expect(invoked).toBe(false); expect(await getTask(t.id)).toBeUndefined(); }); test('deletion after enqueue prevents claim and keeps a cancelled receipt', async () => { const t = await upsertTask(task()); await requestRun(t.id); await deleteTask(t.id); let invoked = false; const s = scheduler(async () => { invoked = true; return success(); }); await (s as any).reconcile(); expect(invoked).toBe(false); expect((await recentRuns(t.id))[0]?.status).toBe('cancelled'); }); test('queued executions use a complete immutable snapshot after editing', async () => { const t = await upsertTask(task()); await requestRun(t.id); await updateCronFromPatch({ id: t.id, action: { type: 'prompt', prompt: 'new prompt' }, runtime: { cwd: join(root, 'different'), model: 'new-model' }, }); let seen: RunAgentTurnOptions | undefined; const s = scheduler(async (o) => { seen = o; return success(); }); await s.runTaskNow(t.id); expect(seen?.input).toBe('old prompt'); expect(seen?.cwd).toBe(root); expect(seen?.model).toBeUndefined(); }); test('an old one-shot result cannot complete a rescheduled plan', async () => { const t = task(); t.kind = 'once'; t.schedule = { type: 'once', at: new Date(Date.now() + 60000).toISOString(), human: '', }; await upsertTask(t); let started!: () => void; const ready = new Promise((r) => (started = r)); let finish!: () => void; const wait = new Promise((r) => (finish = r)); const s = scheduler(async () => { started(); await wait; return success(); }); const work = s.runTaskNow(t.id); await ready; try { await updateCronFromPatch({ id: t.id, schedule: { type: 'once', at: new Date(Date.now() + 120000).toISOString(), }, }); } finally { finish(); } await work; expect((await getTask(t.id))?.status).toBe('active'); expect((await getTask(t.id))?.stats.runCount).toBe(1); }); test.each([ 'delivery_incomplete', 'delivery_unverified', 'claims_unverified', 'no_answer', ])( 'non-final delivery %s never becomes cron success', async (completionStatus) => { const t = await upsertTask(task()); const s = scheduler(async () => ({ ...success(), events: [{ type: 'turn_done', completionStatus }], })); await s.runTaskNow(t.id); expect((await recentRuns(t.id))[0]).toMatchObject({ status: 'failure', completionStatus, }); }, ); test('background work, blocked and acceptance-pending receipts remain explicit', () => { expect(executionOutcome([]).error).toContain('缺少回合完成回执'); for (const done of [ { pendingBackground: [{}] }, { pendingRequired: [{}] }, { managedStatus: 'blocked' }, { managedStatus: 'ready_for_acceptance' }, ]) expect( executionOutcome([{ type: 'turn_done', ...done }]).error, ).toBeTruthy(); }); test('execution timeout cancels the runtime and records failure, not success', async () => { const t = await upsertTask(task()); const s = scheduler( async (o) => { await new Promise((r) => { if (o.signal?.aborted) r(); else o.signal?.addEventListener('abort', () => r(), { once: true }); }); return success(); }, { concurrency: 1, timeoutMs: 20 }, ); await s.runTaskNow(t.id); expect((await recentRuns(t.id))[0]).toMatchObject({ status: 'failure', error: '计划执行超时', }); }); test('global concurrency bounds distinct queued schedules', async () => { const tasks = await Promise.all([ upsertTask(task()), upsertTask(task()), upsertTask(task()), ]); for (const t of tasks) await requestRun(t.id); let active = 0; let maximum = 0; const s = scheduler( async (o) => { active++; maximum = Math.max(maximum, active); await new Promise((r) => { if (o.signal?.aborted) r(); else o.signal?.addEventListener('abort', () => r(), { once: true }); }); active--; return success(); }, { concurrency: 2, timeoutMs: 1000 }, ); await (s as any).reconcile(); for (let i = 0; active < 2 && i < 100; i++) await Bun.sleep(5); expect(active).toBe(2); expect(maximum).toBe(2); }); test('commands require real host identity and preserve Windows paths', async () => { expect(await handleCronCommand('cron', '120m hello', null)).toContain( '缺少当前会话', ); expect(await listTasks()).toHaveLength(0); await handleCronCommand( 'cron', 'create --name audit --interval 2h --prompt "Read C:\\code\\file.txt"', null, { cwd: root, sessionId: 'actual-session' }, ); expect((await listTasks())[0]?.runtime.sessionId).toBe('actual-session'); expect((await listTasks())[0]?.action).toEqual({ type: 'prompt', prompt: 'Read C:\\code\\file.txt', }); }); test('invalid patches do not write and Schedule denies background callers', async () => { const t = await upsertTask(task()); const before = await getTask(t.id); await expect( updateCronFromPatch({ id: t.id, expiresAt: 'invalid' }), ).rejects.toThrow(); expect(await getTask(t.id)).toEqual(before); const r = await scheduleTool.callWithContext!( { action: 'delete', id: t.id }, undefined, { cwd: root, sessionId: 's', surface: 'headless', memoryAccess: 'local-owner', }, ); expect(r.ok).toBe(false); expect(await getTask(t.id)).toBeTruthy(); }); test('Schedule creates idempotently, scopes listing and deletes through the shared service', async () => { const ctx = { cwd: root, sessionId: 's', surface: 'tui' as const, owner: 'local-owner' as const, memoryAccess: 'denied' as const, }; const input = { action: 'create' as const, requestId: 'stable', name: 'test', schedule: { type: 'interval' as const, intervalMs: 60000 }, execution: { type: 'prompt' as const, prompt: 'hello' }, sessionMode: 'fresh' as const, }; for (let i = 0; i < 2; i++) expect( (await scheduleTool.callWithContext!(input, undefined, ctx)).ok, ).toBe(true); const tasks = await listTasks(); expect(tasks).toHaveLength(1); const denied = await scheduleTool.callWithContext!( { action: 'delete', id: tasks[0]!.id }, undefined, { ...ctx, cwd: join(root, 'other') }, ); expect(denied.ok).toBe(false); expect( ( await scheduleTool.callWithContext!( { action: 'delete', id: tasks[0]!.id }, undefined, ctx, ) ).ok, ).toBe(true); expect(await listTasks()).toHaveLength(0); }); test('archiving retains full raw history, IDs, plan identity and active snapshots', async () => { const t = task(); const dir = join(root, 'logs'); for (let i = 0; i < 103; i++) await appendRunFile(dir, { id: `r${i}`, taskId: t.id, taskName: t.name, startedAt: new Date(1000 + i).toISOString(), status: i === 102 ? 'queued' : 'success', snapshot: t, result: `full result ${i}`, cwd: root, sessionId: 's', }); await compactRunLog(dir, t.id); const all = await readRuns(dir, t.id, Infinity); expect(all).toHaveLength(103); expect(all[0]?.snapshot?.planId).toBe(t.planId); const archived = all.find((r) => r.id === 'r0')!; expect(archived.result).toBeUndefined(); expect(archived.planId).toBe(t.planId); expect(await readFile(archived.archiveFile!, 'utf8')).toContain( 'full result 0', ); expect(await readRuns(dir, t.id, Infinity, true)).toHaveLength(1); }); test('notifications cannot inherit a writer transaction and bypass its lock', async () => { const order: string[] = []; let listener!: Promise; await taskTransaction(root, 'same', async () => { listener = outsideTaskTransaction(() => taskTransaction(root, 'same', async () => { order.push('listener'); }), ); await Bun.sleep(30); expect(order).toEqual([]); order.push('writer'); }); await listener; expect(order).toEqual(['writer', 'listener']); }); test('changing schedule type and clearing limits rotate the execution identity', async () => { const t = task(); t.runtime.maxTurns = 10; t.kind = 'once'; await upsertTask(t); const cleared = await updateCronFromPatch({ id: t.id, clearMaxTurns: true }); expect(cleared.planId).not.toBe(t.planId); const recurring = await updateCronFromPatch({ id: t.id, schedule: { type: 'interval', intervalMs: 120000 }, }); expect(recurring.kind).toBe('recurring'); }); test('a real unfinished process is reported and stopped without leaking to later cron runs', async () => { const t = await upsertTask(task()); let child: BackgroundTask | undefined; const s = scheduler(async (options) => { child = await startBackgroundTask( { command: 'isolated cron test', cwd: root, env: process.env, executable: process.execPath, args: ['-e', 'setInterval(() => {}, 1000)'], sessionId: options.sessionId, }, options.sessionState!.backgroundTasks, ); return success(); }); await s.runTaskNow(t.id); expect((await recentRuns(t.id))[0]).toMatchObject({ status: 'failure', completionStatus: 'delivery_incomplete', }); expect(child?.status).toBe('stopped'); });