@celljs/ta-cron 0.0.0-stage → 4.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +48 -0
- package/README.md +47 -2
- package/extension/index.mjs +856 -0
- package/host/index.mjs +877 -0
- package/package.json +44 -4
- package/web/index.js +1985 -0
- package/web-src/commands.spec.ts +55 -0
- package/web-src/commands.ts +259 -0
- package/web-src/cron-expression.spec.ts +41 -0
- package/web-src/cron-expression.ts +150 -0
- package/web-src/cron-protocol.ts +151 -0
- package/web-src/editor.tsx +249 -0
- package/web-src/extension.ts +187 -0
- package/web-src/form-util.spec.ts +33 -0
- package/web-src/form-util.ts +141 -0
- package/web-src/host.ts +12 -0
- package/web-src/i18n.ts +175 -0
- package/web-src/index.tsx +35 -0
- package/web-src/model-picker.spec.ts +32 -0
- package/web-src/model-picker.tsx +227 -0
- package/web-src/notifier.ts +47 -0
- package/web-src/page.ts +126 -0
- package/web-src/react.ts +11 -0
- package/web-src/reply.tsx +80 -0
- package/web-src/schedule-util.spec.ts +48 -0
- package/web-src/schedule-util.ts +233 -0
- package/web-src/scheduler.spec.ts +254 -0
- package/web-src/scheduler.ts +380 -0
- package/web-src/server-texts.spec.ts +10 -0
- package/web-src/server-texts.ts +18 -0
- package/web-src/style.ts +133 -0
- package/web-src/task-store.ts +67 -0
- package/web-src/task-util.ts +174 -0
- package/web-src/tasks-view.tsx +279 -0
- package/web-src/tool.ts +135 -0
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import type { WebCustomMessage } from '@celljs/ta-web/lib/browser/extension/web-extension-api';
|
|
2
|
+
import { HELP } from './commands';
|
|
3
|
+
import type { Reply, Task } from './cron-protocol';
|
|
4
|
+
import { basename, icon, PAGE, pi, t } from './page';
|
|
5
|
+
// biome-ignore lint/style/useImportType: the JSX below compiles to React.createElement (jsxFactory)
|
|
6
|
+
import { React } from './react';
|
|
7
|
+
import { ScheduleUtil } from './schedule-util';
|
|
8
|
+
|
|
9
|
+
function TaskLine({ task }: { task: Task }) {
|
|
10
|
+
const now = new Date();
|
|
11
|
+
return (
|
|
12
|
+
<div className="tcr-reply-task">
|
|
13
|
+
<span className="tcr-task-name">{task.name}</span>
|
|
14
|
+
<span className="tcr-chip">{ScheduleUtil.describe(task.schedule, pi.ui.language, now)}</span>
|
|
15
|
+
<span className="tcr-muted" title={task.cwd}>
|
|
16
|
+
{basename(task.cwd)}
|
|
17
|
+
</span>
|
|
18
|
+
{task.enabled && task.nextRunAt && <span className="tcr-muted">{t('nextAt', { time: ScheduleUtil.clock(new Date(task.nextRunAt), now) })}</span>}
|
|
19
|
+
</div>
|
|
20
|
+
);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function Card({ title, children }: { title: string; children?: React.ReactNode }) {
|
|
24
|
+
const Alarm = icon('AlarmClock');
|
|
25
|
+
return (
|
|
26
|
+
<div className="tcr-reply">
|
|
27
|
+
<div className="tcr-reply-head">
|
|
28
|
+
<Alarm size={14} />
|
|
29
|
+
<span>{title}</span>
|
|
30
|
+
<button type="button" className="tcr-link" onClick={() => pi.ui.showView(PAGE)}>
|
|
31
|
+
{t('show')}
|
|
32
|
+
</button>
|
|
33
|
+
</div>
|
|
34
|
+
{children}
|
|
35
|
+
</div>
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** What `/loop`, `/remind` and `/schedule` answered, in the language of the page. */
|
|
40
|
+
export function ReplyMessage({ message }: { message: WebCustomMessage }) {
|
|
41
|
+
const reply = message.details as Reply | undefined;
|
|
42
|
+
if (!reply?.kind) {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
switch (reply.kind) {
|
|
46
|
+
case 'task':
|
|
47
|
+
return (
|
|
48
|
+
<Card title={t(reply.event)}>
|
|
49
|
+
<TaskLine task={reply.task} />
|
|
50
|
+
</Card>
|
|
51
|
+
);
|
|
52
|
+
case 'removed':
|
|
53
|
+
return <Card title={reply.tasks.length ? t('removed', { names: reply.tasks.map(task => task.name).join(', ') }) : t('removedNone')} />;
|
|
54
|
+
case 'started':
|
|
55
|
+
return <Card title={t('started', { name: reply.task.name })} />;
|
|
56
|
+
case 'list':
|
|
57
|
+
return (
|
|
58
|
+
<Card title={reply.tasks.length ? t('count', { count: reply.tasks.length }) : t('noTasks')}>
|
|
59
|
+
{reply.tasks.map(task => (
|
|
60
|
+
<TaskLine key={task.id} task={task} />
|
|
61
|
+
))}
|
|
62
|
+
</Card>
|
|
63
|
+
);
|
|
64
|
+
case 'show':
|
|
65
|
+
return (
|
|
66
|
+
<Card title={reply.task.name}>
|
|
67
|
+
<TaskLine task={reply.task} />
|
|
68
|
+
<div className="tcr-prompt-text">{reply.task.prompt}</div>
|
|
69
|
+
</Card>
|
|
70
|
+
);
|
|
71
|
+
case 'help':
|
|
72
|
+
return (
|
|
73
|
+
<Card title={t('help')}>
|
|
74
|
+
<pre className="tcr-help">{HELP}</pre>
|
|
75
|
+
</Card>
|
|
76
|
+
);
|
|
77
|
+
case 'error':
|
|
78
|
+
return <div className="tcr-reply tcr-reply-error">{reply.message}</div>;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { describe, expect, it } from 'bun:test';
|
|
2
|
+
import { Duration, ScheduleUtil } from './schedule-util';
|
|
3
|
+
|
|
4
|
+
describe('Duration', () => {
|
|
5
|
+
it('reads durations as people write them, and writes them back', () => {
|
|
6
|
+
expect(Duration.parse('30m')).toBe(30 * 60_000);
|
|
7
|
+
expect(Duration.parse('1h30m')).toBe(90 * 60_000);
|
|
8
|
+
expect(Duration.parse('2d')).toBe(2 * 86_400_000);
|
|
9
|
+
expect(Duration.parse('10min')).toBe(10 * 60_000);
|
|
10
|
+
expect(Duration.parse('soon')).toBeUndefined();
|
|
11
|
+
expect(Duration.parse('30m later')).toBeUndefined();
|
|
12
|
+
expect(Duration.format(90 * 60_000)).toBe('1h30m');
|
|
13
|
+
});
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
describe('ScheduleUtil', () => {
|
|
17
|
+
const now = new Date('2026-11-11T10:00:00');
|
|
18
|
+
|
|
19
|
+
it('checks rules and works out the next run', () => {
|
|
20
|
+
expect(ScheduleUtil.check({ kind: 'interval', every: '90m' })).toEqual({ kind: 'interval', every: '1h30m' });
|
|
21
|
+
expect(() => ScheduleUtil.check({ kind: 'interval', every: '30s' })).toThrow('at least 1m');
|
|
22
|
+
expect(() => ScheduleUtil.check({ kind: 'once', at: 'tomorrow' })).toThrow('runs once');
|
|
23
|
+
expect(() => ScheduleUtil.check({ kind: 'weekly' })).toThrow('A schedule is');
|
|
24
|
+
expect(ScheduleUtil.next({ kind: 'interval', every: '30m' }, now)?.getTime()).toBe(now.getTime() + 30 * 60_000);
|
|
25
|
+
expect(ScheduleUtil.next({ kind: 'once', at: '2026-11-11T09:00:00.000Z' }, new Date('2026-11-11T09:30:00.000Z'))).toBeUndefined();
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
it('says rules in words, in both languages', () => {
|
|
29
|
+
expect(ScheduleUtil.describe({ kind: 'cron', expression: '0 9 * * *' }, 'en')).toBe('Daily at 09:00');
|
|
30
|
+
expect(ScheduleUtil.describe({ kind: 'cron', expression: '0 18 * * 1-5' }, 'zh-CN')).toBe('工作日 18:00');
|
|
31
|
+
expect(ScheduleUtil.describe({ kind: 'cron', expression: '30 8 * * 1' }, 'zh-CN')).toBe('每周一 08:30');
|
|
32
|
+
expect(ScheduleUtil.describe({ kind: 'cron', expression: '@hourly' }, 'zh-CN')).toBe('每小时');
|
|
33
|
+
expect(ScheduleUtil.describe({ kind: 'cron', expression: '*/5 * * * *' }, 'en')).toBe('Every 5 minutes');
|
|
34
|
+
expect(ScheduleUtil.describe({ kind: 'interval', every: '30m' }, 'zh-CN')).toBe('每 30 分钟');
|
|
35
|
+
expect(ScheduleUtil.describe({ kind: 'interval', every: '1d' }, 'zh-CN')).toBe('每天');
|
|
36
|
+
expect(ScheduleUtil.describe({ kind: 'interval', every: '1h' }, 'en')).toBe('Every hour');
|
|
37
|
+
expect(ScheduleUtil.describe({ kind: 'cron', expression: '0 0 1,15 * *' }, 'en')).toBe('Cron 0 0 1,15 * *');
|
|
38
|
+
expect(ScheduleUtil.describe({ kind: 'once', at: new Date('2026-11-12T09:00').toISOString() }, 'zh-CN', now)).toBe('11/12 09:00 运行一次');
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('tells of runs by the notify level, whose default depends on whether the task repeats', () => {
|
|
42
|
+
expect(ScheduleUtil.notifyLevel({ schedule: { kind: 'once', at: '' } })).toBe('always');
|
|
43
|
+
expect(ScheduleUtil.notifyLevel({ schedule: { kind: 'interval', every: '1h' } })).toBe('error');
|
|
44
|
+
expect(ScheduleUtil.notifyLevel({ schedule: { kind: 'interval', every: '1h' }, notify: 'never' })).toBe('never');
|
|
45
|
+
expect(ScheduleUtil.shouldNotify('error', false)).toBe(false);
|
|
46
|
+
expect(ScheduleUtil.shouldNotify('error', true)).toBe(true);
|
|
47
|
+
});
|
|
48
|
+
});
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import { CronExpression, NICKNAMES } from './cron-expression';
|
|
2
|
+
import { Limits, type NotifyLevel, type Schedule, type Task } from './cron-protocol';
|
|
3
|
+
|
|
4
|
+
export const THINKING_LEVELS: readonly string[] = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
|
|
5
|
+
export const NOTIFY_LEVELS: readonly NotifyLevel[] = ['always', 'error', 'never'];
|
|
6
|
+
|
|
7
|
+
const UNITS: Readonly<Record<string, number>> = {
|
|
8
|
+
s: 1000,
|
|
9
|
+
sec: 1000,
|
|
10
|
+
m: 60_000,
|
|
11
|
+
min: 60_000,
|
|
12
|
+
h: 3_600_000,
|
|
13
|
+
hr: 3_600_000,
|
|
14
|
+
d: 86_400_000,
|
|
15
|
+
w: 7 * 86_400_000,
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
/** Durations as people write them: `30m`, `1h30m`, `2d`. */
|
|
19
|
+
export namespace Duration {
|
|
20
|
+
const PART = /(\d+)\s*(sec|min|hr|s|m|h|d|w)/gy;
|
|
21
|
+
|
|
22
|
+
/** Milliseconds; undefined when the text is not a duration. */
|
|
23
|
+
export function parse(text: string): number | undefined {
|
|
24
|
+
const source = text.trim().toLowerCase();
|
|
25
|
+
if (!source) {
|
|
26
|
+
return undefined;
|
|
27
|
+
}
|
|
28
|
+
PART.lastIndex = 0;
|
|
29
|
+
let total = 0;
|
|
30
|
+
let match: RegExpExecArray | null;
|
|
31
|
+
let end = 0;
|
|
32
|
+
// biome-ignore lint/suspicious/noAssignInExpressions: a sticky regular expression, part after part
|
|
33
|
+
while ((match = PART.exec(source))) {
|
|
34
|
+
total += Number(match[1]) * UNITS[match[2]];
|
|
35
|
+
end = PART.lastIndex;
|
|
36
|
+
}
|
|
37
|
+
return end === source.length && total > 0 ? total : undefined;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** `1h30m`. */
|
|
41
|
+
export function format(ms: number): string {
|
|
42
|
+
const parts: string[] = [];
|
|
43
|
+
let rest = Math.round(ms / 1000);
|
|
44
|
+
for (const [unit, size] of [
|
|
45
|
+
['d', 86_400],
|
|
46
|
+
['h', 3_600],
|
|
47
|
+
['m', 60],
|
|
48
|
+
['s', 1],
|
|
49
|
+
] as const) {
|
|
50
|
+
if (rest >= size) {
|
|
51
|
+
parts.push(`${Math.floor(rest / size)}${unit}`);
|
|
52
|
+
rest %= size;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return parts.join('') || '0s';
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Words for the rules of tasks, in the two languages of Ta. */
|
|
60
|
+
interface ScheduleWords {
|
|
61
|
+
once(time: string): string;
|
|
62
|
+
every(amount: number, unit: 'minute' | 'hour' | 'day'): string;
|
|
63
|
+
everyRaw(duration: string): string;
|
|
64
|
+
daily(time: string): string;
|
|
65
|
+
weekdays(time: string): string;
|
|
66
|
+
weekly(day: number, time: string): string;
|
|
67
|
+
monthly(day: number, time: string): string;
|
|
68
|
+
hourly(minute: number): string;
|
|
69
|
+
cron(expression: string): string;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const EN_DAYS = ['Sundays', 'Mondays', 'Tuesdays', 'Wednesdays', 'Thursdays', 'Fridays', 'Saturdays'];
|
|
73
|
+
const ZH_DAYS = ['日', '一', '二', '三', '四', '五', '六'];
|
|
74
|
+
|
|
75
|
+
const WORDS: Record<'en' | 'zh', ScheduleWords> = {
|
|
76
|
+
en: {
|
|
77
|
+
once: time => `Once, ${time}`,
|
|
78
|
+
every: (amount, unit) => (amount === 1 ? `Every ${unit}` : `Every ${amount} ${unit}s`),
|
|
79
|
+
everyRaw: duration => `Every ${duration}`,
|
|
80
|
+
daily: time => `Daily at ${time}`,
|
|
81
|
+
weekdays: time => `Weekdays at ${time}`,
|
|
82
|
+
weekly: (day, time) => `${EN_DAYS[day]} at ${time}`,
|
|
83
|
+
monthly: (day, time) => `Monthly on day ${day} at ${time}`,
|
|
84
|
+
hourly: minute => (minute === 0 ? 'Hourly' : `Hourly at :${pad(minute)}`),
|
|
85
|
+
cron: expression => `Cron ${expression}`,
|
|
86
|
+
},
|
|
87
|
+
zh: {
|
|
88
|
+
once: time => `${time} 运行一次`,
|
|
89
|
+
every: (amount, unit) => `每 ${amount === 1 ? '' : `${amount} `}${{ minute: '分钟', hour: '小时', day: '天' }[unit]}`.replace('每 天', '每天'),
|
|
90
|
+
everyRaw: duration => `每 ${duration}`,
|
|
91
|
+
daily: time => `每天 ${time}`,
|
|
92
|
+
weekdays: time => `工作日 ${time}`,
|
|
93
|
+
weekly: (day, time) => `每周${ZH_DAYS[day]} ${time}`,
|
|
94
|
+
monthly: (day, time) => `每月 ${day} 日 ${time}`,
|
|
95
|
+
hourly: minute => (minute === 0 ? '每小时' : `每小时第 ${minute} 分`),
|
|
96
|
+
cron: expression => `cron ${expression}`,
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
function pad(value: number): string {
|
|
101
|
+
return String(value).padStart(2, '0');
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export namespace ScheduleUtil {
|
|
105
|
+
/** A rule as a tool or a page sends it, checked; a time of `once` becomes ISO. Throws with what is wrong. */
|
|
106
|
+
export function check(value: unknown): Schedule {
|
|
107
|
+
const schedule = (value ?? {}) as Record<string, unknown>;
|
|
108
|
+
switch (schedule.kind) {
|
|
109
|
+
case 'once': {
|
|
110
|
+
const at = new Date(String(schedule.at ?? ''));
|
|
111
|
+
if (typeof schedule.at !== 'string' || Number.isNaN(at.getTime())) {
|
|
112
|
+
throw new Error('A task that runs once needs `at`, a time such as 2026-11-12T09:00 (local time) or an ISO time.');
|
|
113
|
+
}
|
|
114
|
+
return { kind: 'once', at: at.toISOString() };
|
|
115
|
+
}
|
|
116
|
+
case 'interval': {
|
|
117
|
+
const every = typeof schedule.every === 'string' ? schedule.every.trim() : '';
|
|
118
|
+
const ms = Duration.parse(every);
|
|
119
|
+
if (ms === undefined) {
|
|
120
|
+
throw new Error('An interval needs `every`, a duration such as 30m, 2h or 1d.');
|
|
121
|
+
}
|
|
122
|
+
if (ms < Limits.MIN_INTERVAL_MS) {
|
|
123
|
+
throw new Error(`An interval is at least 1m; ${every} is shorter.`);
|
|
124
|
+
}
|
|
125
|
+
return { kind: 'interval', every: Duration.format(ms) };
|
|
126
|
+
}
|
|
127
|
+
case 'cron': {
|
|
128
|
+
const expression = typeof schedule.expression === 'string' ? schedule.expression : '';
|
|
129
|
+
return { kind: 'cron', expression: CronExpression.parse(expression).source };
|
|
130
|
+
}
|
|
131
|
+
default:
|
|
132
|
+
throw new Error('A schedule is { kind: "once", at }, { kind: "interval", every } or { kind: "cron", expression }.');
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** The next time after `now`; undefined when there is none (a time that passed, a rule that never matches). */
|
|
137
|
+
export function next(schedule: Schedule, now: Date): Date | undefined {
|
|
138
|
+
switch (schedule.kind) {
|
|
139
|
+
case 'once': {
|
|
140
|
+
const at = new Date(schedule.at);
|
|
141
|
+
return at.getTime() > now.getTime() ? at : undefined;
|
|
142
|
+
}
|
|
143
|
+
case 'interval':
|
|
144
|
+
return new Date(now.getTime() + (Duration.parse(schedule.every) ?? Limits.MIN_INTERVAL_MS));
|
|
145
|
+
case 'cron':
|
|
146
|
+
return CronExpression.parse(schedule.expression).next(now);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export function repeats(schedule: Schedule): boolean {
|
|
151
|
+
return schedule.kind !== 'once';
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** What the task's notify level is, with its default. */
|
|
155
|
+
export function notifyLevel(task: Pick<Task, 'notify' | 'schedule'>): NotifyLevel {
|
|
156
|
+
return task.notify ?? (repeats(task.schedule) ? 'error' : 'always');
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function shouldNotify(level: NotifyLevel, failed: boolean): boolean {
|
|
160
|
+
return level === 'always' || (level === 'error' && failed);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** `11/12 09:00` in local time; the year too when it is not this one. */
|
|
164
|
+
export function clock(time: Date, now = new Date()): string {
|
|
165
|
+
const day = `${time.getMonth() + 1}/${time.getDate()}`;
|
|
166
|
+
const year = time.getFullYear() === now.getFullYear() ? '' : `${time.getFullYear()}/`;
|
|
167
|
+
return `${year}${day} ${pad(time.getHours())}:${pad(time.getMinutes())}`;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** The rule in words: `Daily at 09:00`, `每 30 分钟`. */
|
|
171
|
+
export function describe(schedule: Schedule, language: string, now = new Date()): string {
|
|
172
|
+
const words = WORDS[language.startsWith('zh') ? 'zh' : 'en'];
|
|
173
|
+
switch (schedule.kind) {
|
|
174
|
+
case 'once':
|
|
175
|
+
return words.once(clock(new Date(schedule.at), now));
|
|
176
|
+
case 'interval':
|
|
177
|
+
return describeInterval(schedule.every, words);
|
|
178
|
+
case 'cron':
|
|
179
|
+
return describeCron(schedule.expression, words);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function describeInterval(every: string, words: ScheduleWords): string {
|
|
184
|
+
const ms = Duration.parse(every) ?? 0;
|
|
185
|
+
for (const [unit, size] of [
|
|
186
|
+
['day', 86_400_000],
|
|
187
|
+
['hour', 3_600_000],
|
|
188
|
+
['minute', 60_000],
|
|
189
|
+
] as const) {
|
|
190
|
+
if (ms >= size && ms % size === 0) {
|
|
191
|
+
return words.every(ms / size, unit);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return words.everyRaw(every);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function describeCron(expression: string, words: ScheduleWords): string {
|
|
198
|
+
const fields = (NICKNAMES[expression.toLowerCase()] ?? expression).split(' ');
|
|
199
|
+
const [minute, hour, day, month, weekday] = fields;
|
|
200
|
+
const number = (text: string) => (/^\d+$/.test(text) ? Number(text) : undefined);
|
|
201
|
+
const m = number(minute);
|
|
202
|
+
const h = number(hour);
|
|
203
|
+
const time = m !== undefined && h !== undefined ? `${pad(h)}:${pad(m)}` : undefined;
|
|
204
|
+
if (month === '*') {
|
|
205
|
+
if (time && day === '*' && weekday === '*') {
|
|
206
|
+
return words.daily(time);
|
|
207
|
+
}
|
|
208
|
+
if (time && day === '*' && weekday === '1-5') {
|
|
209
|
+
return words.weekdays(time);
|
|
210
|
+
}
|
|
211
|
+
const d = number(weekday);
|
|
212
|
+
if (time && day === '*' && d !== undefined && d <= 7) {
|
|
213
|
+
return words.weekly(d % 7, time);
|
|
214
|
+
}
|
|
215
|
+
const date = number(day);
|
|
216
|
+
if (time && date !== undefined && weekday === '*') {
|
|
217
|
+
return words.monthly(date, time);
|
|
218
|
+
}
|
|
219
|
+
if (m !== undefined && hour === '*' && day === '*' && weekday === '*') {
|
|
220
|
+
return words.hourly(m);
|
|
221
|
+
}
|
|
222
|
+
const everyMinutes = /^\*\/(\d+)$/.exec(minute);
|
|
223
|
+
if (everyMinutes && hour === '*' && day === '*' && weekday === '*') {
|
|
224
|
+
return words.every(Number(everyMinutes[1]), 'minute');
|
|
225
|
+
}
|
|
226
|
+
const everyHours = /^\*\/(\d+)$/.exec(hour);
|
|
227
|
+
if (m === 0 && everyHours && day === '*' && weekday === '*') {
|
|
228
|
+
return words.every(Number(everyHours[1]), 'hour');
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
return words.cron(expression);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it } from 'bun:test';
|
|
2
|
+
import type { TaOpenSessionOptions, TaPromptInput, TaSessionInfo } from '@celljs/ta-protocol';
|
|
3
|
+
import { type FinishedRun, Keys, NAME, RUN_MARK, type Run, type Task } from './cron-protocol';
|
|
4
|
+
import { type CronHost, CronScheduler } from './scheduler';
|
|
5
|
+
|
|
6
|
+
interface FakeSession {
|
|
7
|
+
info: TaSessionInfo;
|
|
8
|
+
options: TaOpenSessionOptions;
|
|
9
|
+
prompts: TaPromptInput[];
|
|
10
|
+
/** Ends the run of the last prompt; until then it streams. */
|
|
11
|
+
answer?: string;
|
|
12
|
+
streaming: boolean;
|
|
13
|
+
aborted: boolean;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** The Ta service, as the scheduler sees it: sessions that answer when the test says, and the data of the package. */
|
|
17
|
+
class FakeHost implements CronHost {
|
|
18
|
+
readonly data = new Map<string, unknown>();
|
|
19
|
+
readonly sessions = new Map<string, FakeSession>();
|
|
20
|
+
readonly closed: string[] = [];
|
|
21
|
+
/** What each new run answers at once; undefined keeps it working. */
|
|
22
|
+
reply: string | undefined = 'All green.';
|
|
23
|
+
failOpen?: string;
|
|
24
|
+
protected count = 0;
|
|
25
|
+
|
|
26
|
+
async getServerInfo() {
|
|
27
|
+
return { cwd: '/work' } as never;
|
|
28
|
+
}
|
|
29
|
+
async listSessions() {
|
|
30
|
+
return [...this.sessions.values()].map(session => ({ ...session.info, isStreaming: session.streaming }));
|
|
31
|
+
}
|
|
32
|
+
async openSession(options: TaOpenSessionOptions) {
|
|
33
|
+
if (this.failOpen) {
|
|
34
|
+
throw new Error(this.failOpen);
|
|
35
|
+
}
|
|
36
|
+
const sessionId = `s${++this.count}`;
|
|
37
|
+
const info = {
|
|
38
|
+
sessionId,
|
|
39
|
+
piSessionId: `p${this.count}`,
|
|
40
|
+
cwd: options.cwd,
|
|
41
|
+
sessionFile: `/sessions/${sessionId}.jsonl`,
|
|
42
|
+
attached: 0,
|
|
43
|
+
group: options.group,
|
|
44
|
+
} as TaSessionInfo;
|
|
45
|
+
this.sessions.set(sessionId, { info, options, prompts: [], streaming: false, aborted: false });
|
|
46
|
+
return info;
|
|
47
|
+
}
|
|
48
|
+
async closeSession(sessionId: string) {
|
|
49
|
+
this.sessions.delete(sessionId);
|
|
50
|
+
this.closed.push(sessionId);
|
|
51
|
+
}
|
|
52
|
+
async setSessionName() {}
|
|
53
|
+
async prompt(sessionId: string, input: TaPromptInput) {
|
|
54
|
+
const session = this.session(sessionId);
|
|
55
|
+
session.prompts.push(input);
|
|
56
|
+
session.streaming = this.reply === undefined;
|
|
57
|
+
session.answer = this.reply;
|
|
58
|
+
return { clientMessageId: input.clientMessageId, status: 'accepted' as const };
|
|
59
|
+
}
|
|
60
|
+
async abort(sessionId: string) {
|
|
61
|
+
const session = this.session(sessionId);
|
|
62
|
+
session.aborted = true;
|
|
63
|
+
session.streaming = false;
|
|
64
|
+
}
|
|
65
|
+
async getState(sessionId: string) {
|
|
66
|
+
const session = this.session(sessionId);
|
|
67
|
+
return {
|
|
68
|
+
isStreaming: session.streaming,
|
|
69
|
+
pendingMessageCount: 0,
|
|
70
|
+
messageCount: session.prompts.length * 2,
|
|
71
|
+
sessionFile: session.info.sessionFile,
|
|
72
|
+
} as never;
|
|
73
|
+
}
|
|
74
|
+
async getLastAssistantText(sessionId: string) {
|
|
75
|
+
return { text: this.session(sessionId).answer ?? null } as never;
|
|
76
|
+
}
|
|
77
|
+
async getExtensionData(name: string, key: string) {
|
|
78
|
+
return structuredClone(this.data.get(`${name}:${key}`));
|
|
79
|
+
}
|
|
80
|
+
async setExtensionData(name: string, key: string, value: unknown) {
|
|
81
|
+
if (value === null || value === undefined) {
|
|
82
|
+
this.data.delete(`${name}:${key}`);
|
|
83
|
+
} else {
|
|
84
|
+
this.data.set(`${name}:${key}`, structuredClone(value));
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
finish(sessionId: string, answer: string): void {
|
|
89
|
+
const session = this.session(sessionId);
|
|
90
|
+
session.answer = answer;
|
|
91
|
+
session.streaming = false;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
protected session(sessionId: string): FakeSession {
|
|
95
|
+
const session = this.sessions.get(sessionId);
|
|
96
|
+
if (!session) {
|
|
97
|
+
throw new Error(`No session ${sessionId}`);
|
|
98
|
+
}
|
|
99
|
+
return session;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function until(test: () => boolean | Promise<boolean>, what: string, ms = 3000): Promise<void> {
|
|
104
|
+
const start = Date.now();
|
|
105
|
+
while (!(await test())) {
|
|
106
|
+
if (Date.now() - start > ms) {
|
|
107
|
+
throw new Error(`Timed out waiting for ${what}`);
|
|
108
|
+
}
|
|
109
|
+
await new Promise(resolve => setTimeout(resolve, 5));
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
describe('CronScheduler', () => {
|
|
114
|
+
let clock = new Date('2026-11-11T10:00:00').getTime();
|
|
115
|
+
const schedulers: CronScheduler[] = [];
|
|
116
|
+
const make = (host: FakeHost, options: Partial<ConstructorParameters<typeof CronScheduler>[1]> = {}) => {
|
|
117
|
+
const scheduler = new CronScheduler(host, { now: () => new Date(clock), tickMs: 20, pollMs: 5, ...options });
|
|
118
|
+
schedulers.push(scheduler);
|
|
119
|
+
return scheduler;
|
|
120
|
+
};
|
|
121
|
+
const runs = (host: FakeHost, taskId: string) => (host.data.get(`${NAME}:${Keys.runs(taskId)}`) as Run[] | undefined) ?? [];
|
|
122
|
+
|
|
123
|
+
afterEach(async () => {
|
|
124
|
+
await Promise.all(schedulers.splice(0).map(scheduler => scheduler.dispose()));
|
|
125
|
+
clock = new Date('2026-11-11T10:00:00').getTime();
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
it('runs a due task in a conversation of its own, records the run and closes the conversation', async () => {
|
|
129
|
+
const host = new FakeHost();
|
|
130
|
+
const scheduler = make(host);
|
|
131
|
+
await scheduler.start();
|
|
132
|
+
const task = await scheduler.add({ prompt: 'Check CI', schedule: { kind: 'interval', every: '30m' } });
|
|
133
|
+
expect(task).toMatchObject({ name: 'Check CI', cwd: '/work', enabled: true, nextRunAt: new Date(clock + 30 * 60_000).toISOString() });
|
|
134
|
+
|
|
135
|
+
clock += 30 * 60_000;
|
|
136
|
+
await until(() => runs(host, task.id)[0]?.status === 'success', 'the run ended');
|
|
137
|
+
const [run] = runs(host, task.id);
|
|
138
|
+
expect(run).toMatchObject({ trigger: 'schedule', summary: 'All green.', cwd: '/work', sessionFile: '/sessions/s1.jsonl' });
|
|
139
|
+
const [opened] = [...host.closed];
|
|
140
|
+
expect(opened).toBe('s1');
|
|
141
|
+
const updated = await scheduler.get(task.id);
|
|
142
|
+
expect(updated).toMatchObject({ lastStatus: 'success', runCount: 1, failCount: 0, nextRunAt: new Date(clock + 30 * 60_000).toISOString() });
|
|
143
|
+
// Pages hear of it; a repeating task tells only of failures by default.
|
|
144
|
+
expect(host.data.get(`${NAME}:${Keys.LATEST}`) as FinishedRun).toMatchObject({ taskName: 'Check CI', notify: false, run: { id: run.id } });
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
it('runs by hand without touching the schedule, and not twice at once', async () => {
|
|
148
|
+
const host = new FakeHost();
|
|
149
|
+
host.reply = undefined;
|
|
150
|
+
const scheduler = make(host);
|
|
151
|
+
await scheduler.start();
|
|
152
|
+
const task = await scheduler.add({
|
|
153
|
+
prompt: 'Report',
|
|
154
|
+
schedule: { kind: 'cron', expression: '0 9 * * *' },
|
|
155
|
+
model: 'openai/gpt-5',
|
|
156
|
+
thinking: 'low',
|
|
157
|
+
cwd: 'ssh://box/srv',
|
|
158
|
+
});
|
|
159
|
+
const run = await scheduler.run(task.id);
|
|
160
|
+
expect(run.trigger).toBe('manual');
|
|
161
|
+
await until(() => host.sessions.get('s1')?.prompts.length === 1, 'the prompt was sent');
|
|
162
|
+
const options = host.sessions.get('s1')?.options;
|
|
163
|
+
expect(options).toMatchObject({ cwd: 'ssh://box/srv', group: NAME, model: 'openai/gpt-5', thinkingLevel: 'low' });
|
|
164
|
+
expect(options?.appendSystemPrompt).toContain(RUN_MARK);
|
|
165
|
+
expect(scheduler.isRun('s1')).toBe(true);
|
|
166
|
+
await expect(scheduler.run(task.id)).rejects.toThrow('running now');
|
|
167
|
+
host.finish('s1', 'Done.');
|
|
168
|
+
await until(() => runs(host, task.id)[0]?.status === 'success', 'the run ended');
|
|
169
|
+
expect((await scheduler.get(task.id)).nextRunAt).toBe(task.nextRunAt);
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
it('lets the time of a task still at work go, and stops a run that takes too long', async () => {
|
|
173
|
+
const host = new FakeHost();
|
|
174
|
+
host.reply = undefined;
|
|
175
|
+
const scheduler = make(host, { timeoutMs: 150 });
|
|
176
|
+
await scheduler.start();
|
|
177
|
+
const task = await scheduler.add({ prompt: 'Slow', schedule: { kind: 'interval', every: '1m' } });
|
|
178
|
+
clock += 60_000;
|
|
179
|
+
await until(() => host.sessions.size === 1, 'the run started');
|
|
180
|
+
clock += 60_000;
|
|
181
|
+
await new Promise(resolve => setTimeout(resolve, 60));
|
|
182
|
+
expect(host.sessions.size).toBe(1);
|
|
183
|
+
await until(() => runs(host, task.id)[0]?.status === 'error', 'the run was stopped');
|
|
184
|
+
expect(runs(host, task.id)).toHaveLength(1);
|
|
185
|
+
expect(runs(host, task.id)[0]).toMatchObject({ reason: 'timeout' });
|
|
186
|
+
expect(host.sessions.get('s1')?.aborted ?? host.closed.includes('s1')).toBe(true);
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
it('records a failed run, and a task that runs once is done after it', async () => {
|
|
190
|
+
const host = new FakeHost();
|
|
191
|
+
host.failOpen = 'No such directory: /gone';
|
|
192
|
+
const scheduler = make(host);
|
|
193
|
+
await scheduler.start();
|
|
194
|
+
const task = await scheduler.add({ prompt: 'Remind me', schedule: { kind: 'once', at: new Date(clock + 60_000).toISOString() }, cwd: '/gone' });
|
|
195
|
+
clock += 60_000;
|
|
196
|
+
await until(() => runs(host, task.id)[0]?.status === 'error', 'the run failed');
|
|
197
|
+
expect(runs(host, task.id)[0].error).toContain('/gone');
|
|
198
|
+
const done = await scheduler.get(task.id);
|
|
199
|
+
expect(done).toMatchObject({ enabled: false, lastStatus: 'error', failCount: 1 });
|
|
200
|
+
expect(done.nextRunAt).toBeUndefined();
|
|
201
|
+
expect(host.data.get(`${NAME}:${Keys.LATEST}`)).toMatchObject({ notify: true });
|
|
202
|
+
await expect(scheduler.setEnabled(task.id, true)).rejects.toThrow('has passed');
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
it('on start, fails the runs left unfinished, misses a late reminder and catches up a repeating task once', async () => {
|
|
206
|
+
const host = new FakeHost();
|
|
207
|
+
const first = make(host);
|
|
208
|
+
await first.start();
|
|
209
|
+
const remind = await first.add({ prompt: 'Remind', schedule: { kind: 'once', at: new Date(clock + 60_000).toISOString() } });
|
|
210
|
+
const repeat = await first.add({ prompt: 'Repeat', schedule: { kind: 'interval', every: '10m' } });
|
|
211
|
+
await first.dispose();
|
|
212
|
+
// A run left as running by a service that stopped.
|
|
213
|
+
const tasks = host.data.get(`${NAME}:${Keys.TASKS}`) as Task[];
|
|
214
|
+
host.data.set(
|
|
215
|
+
`${NAME}:${Keys.TASKS}`,
|
|
216
|
+
tasks.map(task => (task.id === repeat.id ? { ...task, lastStatus: 'running' } : task)),
|
|
217
|
+
);
|
|
218
|
+
host.data.set(`${NAME}:${Keys.runs(repeat.id)}`, [
|
|
219
|
+
{ id: 'run_old', taskId: repeat.id, trigger: 'schedule', status: 'running', startedAt: new Date(clock).toISOString(), cwd: '/work' },
|
|
220
|
+
]);
|
|
221
|
+
|
|
222
|
+
clock += 2 * 60 * 60_000;
|
|
223
|
+
const second = make(host);
|
|
224
|
+
await second.start();
|
|
225
|
+
expect(runs(host, remind.id)[0]).toMatchObject({ status: 'missed' });
|
|
226
|
+
expect(await second.get(remind.id)).toMatchObject({ enabled: false, lastStatus: 'missed' });
|
|
227
|
+
await until(() => runs(host, repeat.id)[0]?.status === 'success', 'the catch-up run ended');
|
|
228
|
+
const repeatRuns = runs(host, repeat.id);
|
|
229
|
+
expect(repeatRuns.map(run => run.status)).toEqual(['success', 'error']);
|
|
230
|
+
expect(repeatRuns[1]).toMatchObject({ id: 'run_old', reason: 'interrupted' });
|
|
231
|
+
// Twelve periods were missed: one run, then the next time from now.
|
|
232
|
+
await new Promise(resolve => setTimeout(resolve, 60));
|
|
233
|
+
expect(runs(host, repeat.id)).toHaveLength(2);
|
|
234
|
+
expect((await second.get(repeat.id)).nextRunAt).toBe(new Date(clock + 10 * 60_000).toISOString());
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
it('finds tasks by id, prefix or name, and removes them with their runs', async () => {
|
|
238
|
+
const host = new FakeHost();
|
|
239
|
+
const scheduler = make(host);
|
|
240
|
+
await scheduler.start();
|
|
241
|
+
const a = await scheduler.add({ prompt: 'A', name: 'alpha', schedule: { kind: 'interval', every: '1h' }, cwd: '/one' });
|
|
242
|
+
const b = await scheduler.add({ prompt: 'B', schedule: { kind: 'interval', every: '1h' }, cwd: '/two' });
|
|
243
|
+
expect((await scheduler.get('alpha')).id).toBe(a.id);
|
|
244
|
+
expect((await scheduler.get(b.id.slice(0, 9))).id).toBe(b.id);
|
|
245
|
+
await expect(scheduler.get('nope')).rejects.toThrow('alpha');
|
|
246
|
+
const updated = await scheduler.update('alpha', { model: 'x/y', notify: 'never' });
|
|
247
|
+
expect(updated).toMatchObject({ model: 'x/y', notify: 'never' });
|
|
248
|
+
expect(await scheduler.update('alpha', { model: '', notify: '' })).not.toHaveProperty('model');
|
|
249
|
+
expect((await scheduler.clear('/one')).map(task => task.id)).toEqual([a.id]);
|
|
250
|
+
expect((await scheduler.list()).map(task => task.id)).toEqual([b.id]);
|
|
251
|
+
await scheduler.remove(b.id);
|
|
252
|
+
expect(await scheduler.list()).toEqual([]);
|
|
253
|
+
});
|
|
254
|
+
});
|