feat(dashboard): create and edit scheduled tasks
This commit is contained in:
@@ -526,6 +526,7 @@ async function main(): Promise<void> {
|
||||
getRoomBindings: runtimeState.getRoomBindings,
|
||||
enqueueMessageCheck: (chatJid, groupFolder) =>
|
||||
queue.enqueueMessageCheck(chatJid, resolveGroupIpcPath(groupFolder)),
|
||||
nudgeScheduler: nudgeSchedulerLoop,
|
||||
});
|
||||
|
||||
leaseRecoveryTimer = setInterval(() => {
|
||||
|
||||
@@ -349,6 +349,198 @@ describe('web dashboard server handler', () => {
|
||||
expect(wrongMethod.status).toBe(405);
|
||||
});
|
||||
|
||||
it('creates and edits scheduled tasks through web endpoints', async () => {
|
||||
const tasks = new Map<string, ScheduledTask>();
|
||||
const rooms: Record<string, RegisteredGroup> = {
|
||||
'dc:ops': {
|
||||
name: '#ops',
|
||||
folder: 'ops-room',
|
||||
added_at: '2026-04-26T05:00:00.000Z',
|
||||
agentType: 'codex',
|
||||
},
|
||||
};
|
||||
const nudges: string[] = [];
|
||||
const handler = createWebDashboardHandler({
|
||||
readStatusSnapshots: () => [],
|
||||
getTasks: () => [...tasks.values()],
|
||||
getTaskById: (id) => tasks.get(id),
|
||||
createTask: (task) => {
|
||||
tasks.set(task.id, {
|
||||
...task,
|
||||
agent_type: task.agent_type ?? null,
|
||||
ci_provider: null,
|
||||
ci_metadata: null,
|
||||
max_duration_ms: null,
|
||||
status_message_id: null,
|
||||
status_started_at: null,
|
||||
last_run: null,
|
||||
last_result: null,
|
||||
suspended_until: null,
|
||||
});
|
||||
},
|
||||
updateTask: (id, updates) => {
|
||||
const task = tasks.get(id);
|
||||
if (task) tasks.set(id, { ...task, ...updates });
|
||||
},
|
||||
getPairedTasks: () => [],
|
||||
getRoomBindings: () => rooms,
|
||||
nudgeScheduler: () => {
|
||||
nudges.push('nudge');
|
||||
},
|
||||
now: () => '2026-04-26T05:10:00.000Z',
|
||||
});
|
||||
|
||||
const create = await handler(
|
||||
new Request('http://localhost/api/tasks', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
roomJid: 'dc:ops',
|
||||
prompt: ' run hourly dashboard audit ',
|
||||
scheduleType: 'once',
|
||||
scheduleValue: '2026-04-26T05:20:00.000Z',
|
||||
contextMode: 'group',
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(create.status).toBe(200);
|
||||
const created = (await create.json()) as {
|
||||
task: { id: string; groupFolder: string; scheduleType: string };
|
||||
};
|
||||
expect(created.task.groupFolder).toBe('ops-room');
|
||||
expect(created.task.scheduleType).toBe('once');
|
||||
const createdTask = tasks.get(created.task.id);
|
||||
expect(createdTask).toMatchObject({
|
||||
agent_type: 'codex',
|
||||
chat_jid: 'dc:ops',
|
||||
context_mode: 'group',
|
||||
group_folder: 'ops-room',
|
||||
next_run: '2026-04-26T05:20:00.000Z',
|
||||
prompt: 'run hourly dashboard audit',
|
||||
schedule_type: 'once',
|
||||
status: 'active',
|
||||
});
|
||||
|
||||
const update = await handler(
|
||||
new Request(`http://localhost/api/tasks/${created.task.id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
prompt: 'watch dashboard every minute',
|
||||
scheduleType: 'interval',
|
||||
scheduleValue: '60000',
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(update.status).toBe(200);
|
||||
expect(tasks.get(created.task.id)).toMatchObject({
|
||||
next_run: '2026-04-26T05:11:00.000Z',
|
||||
prompt: 'watch dashboard every minute',
|
||||
schedule_type: 'interval',
|
||||
schedule_value: '60000',
|
||||
suspended_until: null,
|
||||
});
|
||||
expect(nudges).toEqual([]);
|
||||
});
|
||||
|
||||
it('rejects invalid scheduled task create and edit requests', async () => {
|
||||
const completed = makeTask({
|
||||
id: 'completed-task',
|
||||
status: 'completed',
|
||||
});
|
||||
const watch = makeTask({
|
||||
id: 'watch-task',
|
||||
prompt: '[BACKGROUND CI WATCH]\nwatch',
|
||||
});
|
||||
const handler = createWebDashboardHandler({
|
||||
readStatusSnapshots: () => [],
|
||||
getTasks: () => [completed, watch],
|
||||
getTaskById: (id) =>
|
||||
id === completed.id ? completed : id === watch.id ? watch : undefined,
|
||||
createTask: () => {
|
||||
throw new Error('createTask should not be called');
|
||||
},
|
||||
updateTask: () => {
|
||||
throw new Error('updateTask should not be called');
|
||||
},
|
||||
getPairedTasks: () => [],
|
||||
getRoomBindings: () => ({
|
||||
'dc:ops': {
|
||||
name: '#ops',
|
||||
folder: 'ops-room',
|
||||
added_at: '2026-04-26T05:00:00.000Z',
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
const missingBody = await handler(
|
||||
new Request('http://localhost/api/tasks', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ prompt: 'run' }),
|
||||
}),
|
||||
);
|
||||
expect(missingBody.status).toBe(400);
|
||||
|
||||
const missingRoom = await handler(
|
||||
new Request('http://localhost/api/tasks', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
roomJid: 'dc:missing',
|
||||
prompt: 'run',
|
||||
scheduleType: 'once',
|
||||
scheduleValue: '2026-04-26T05:20:00.000Z',
|
||||
contextMode: 'isolated',
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(missingRoom.status).toBe(404);
|
||||
|
||||
const invalidCron = await handler(
|
||||
new Request('http://localhost/api/tasks', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
roomJid: 'dc:ops',
|
||||
prompt: 'run',
|
||||
scheduleType: 'cron',
|
||||
scheduleValue: 'not cron',
|
||||
contextMode: 'isolated',
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(invalidCron.status).toBe(400);
|
||||
|
||||
const completedEdit = await handler(
|
||||
new Request('http://localhost/api/tasks/completed-task', {
|
||||
method: 'PATCH',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
prompt: 'run again',
|
||||
scheduleType: 'once',
|
||||
scheduleValue: '2026-04-26T05:20:00.000Z',
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(completedEdit.status).toBe(409);
|
||||
|
||||
const watcherEdit = await handler(
|
||||
new Request('http://localhost/api/tasks/watch-task', {
|
||||
method: 'PATCH',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
prompt: 'run again',
|
||||
scheduleType: 'interval',
|
||||
scheduleValue: '60000',
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(watcherEdit.status).toBe(409);
|
||||
});
|
||||
|
||||
it('queues paired inbox actions through the paired follow-up scheduler', async () => {
|
||||
const pairedTasks = new Map<string, PairedTask>([
|
||||
[
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
import { WEB_DASHBOARD } from './config.js';
|
||||
import { CronExpressionParser } from 'cron-parser';
|
||||
|
||||
import { TIMEZONE, WEB_DASHBOARD } from './config.js';
|
||||
import {
|
||||
createTask,
|
||||
deleteTask,
|
||||
getAllOpenPairedTasks,
|
||||
getAllTasks,
|
||||
@@ -21,11 +24,13 @@ import {
|
||||
type StatusSnapshot,
|
||||
} from './status-dashboard.js';
|
||||
import type {
|
||||
AgentType,
|
||||
NewMessage,
|
||||
PairedTask,
|
||||
RegisteredGroup,
|
||||
ScheduledTask,
|
||||
} from './types.js';
|
||||
import { isWatchCiTask } from './task-watch-status.js';
|
||||
import {
|
||||
buildWebDashboardOverview,
|
||||
sanitizeScheduledTask,
|
||||
@@ -55,8 +60,31 @@ export interface WebDashboardHandlerOptions {
|
||||
getTaskById?: (id: string) => ScheduledTask | undefined;
|
||||
updateTask?: (
|
||||
id: string,
|
||||
updates: Partial<Pick<ScheduledTask, 'status' | 'suspended_until'>>,
|
||||
updates: Partial<
|
||||
Pick<
|
||||
ScheduledTask,
|
||||
| 'prompt'
|
||||
| 'schedule_type'
|
||||
| 'schedule_value'
|
||||
| 'next_run'
|
||||
| 'status'
|
||||
| 'suspended_until'
|
||||
>
|
||||
>,
|
||||
) => void;
|
||||
createTask?: (task: {
|
||||
id: string;
|
||||
group_folder: string;
|
||||
chat_jid: string;
|
||||
agent_type?: AgentType | null;
|
||||
prompt: string;
|
||||
schedule_type: ScheduledTask['schedule_type'];
|
||||
schedule_value: string;
|
||||
context_mode: ScheduledTask['context_mode'];
|
||||
next_run: string | null;
|
||||
status: ScheduledTask['status'];
|
||||
created_at: string;
|
||||
}) => void;
|
||||
deleteTask?: (id: string) => void;
|
||||
getPairedTasks?: () => PairedTask[];
|
||||
getPairedTaskById?: (id: string) => PairedTask | undefined;
|
||||
@@ -72,6 +100,7 @@ export interface WebDashboardHandlerOptions {
|
||||
storeMessage?: (message: NewMessage) => void;
|
||||
hasMessage?: (chatJid: string, id: string) => boolean;
|
||||
enqueueMessageCheck?: (chatJid: string, groupFolder: string) => void;
|
||||
nudgeScheduler?: () => void;
|
||||
now?: () => string;
|
||||
}
|
||||
|
||||
@@ -154,6 +183,16 @@ function serveStaticFile(staticDir: string, pathname: string): Response {
|
||||
type TaskAction = 'pause' | 'resume' | 'cancel';
|
||||
type InboxAction = 'run';
|
||||
|
||||
function parseTaskPath(pathname: string): string | null {
|
||||
const match = pathname.match(/^\/api\/tasks\/([^/]+)$/);
|
||||
if (!match) return null;
|
||||
try {
|
||||
return decodeURIComponent(match[1]);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function parseTaskActionPath(pathname: string): string | null {
|
||||
const match = pathname.match(/^\/api\/tasks\/([^/]+)\/actions$/);
|
||||
if (!match) return null;
|
||||
@@ -203,6 +242,20 @@ function isTaskAction(value: unknown): value is TaskAction {
|
||||
return value === 'pause' || value === 'resume' || value === 'cancel';
|
||||
}
|
||||
|
||||
function isScheduleType(
|
||||
value: unknown,
|
||||
): value is ScheduledTask['schedule_type'] {
|
||||
return value === 'cron' || value === 'interval' || value === 'once';
|
||||
}
|
||||
|
||||
function isContextMode(value: unknown): value is ScheduledTask['context_mode'] {
|
||||
return value === 'group' || value === 'isolated';
|
||||
}
|
||||
|
||||
function isAgentType(value: unknown): value is AgentType {
|
||||
return value === 'claude-code' || value === 'codex';
|
||||
}
|
||||
|
||||
function isInboxAction(value: unknown): value is InboxAction {
|
||||
return value === 'run';
|
||||
}
|
||||
@@ -237,6 +290,87 @@ async function readInboxAction(request: Request): Promise<InboxAction | null> {
|
||||
}
|
||||
}
|
||||
|
||||
interface ScheduledTaskMutationBody {
|
||||
roomJid?: unknown;
|
||||
groupFolder?: unknown;
|
||||
prompt?: unknown;
|
||||
scheduleType?: unknown;
|
||||
scheduleValue?: unknown;
|
||||
contextMode?: unknown;
|
||||
agentType?: unknown;
|
||||
}
|
||||
|
||||
async function readScheduledTaskMutationBody(
|
||||
request: Request,
|
||||
): Promise<ScheduledTaskMutationBody | null> {
|
||||
try {
|
||||
return (await request.json()) as ScheduledTaskMutationBody;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeNonEmptyString(value: unknown): string | null {
|
||||
if (typeof value !== 'string') return null;
|
||||
const trimmed = value.trim();
|
||||
return trimmed ? trimmed : null;
|
||||
}
|
||||
|
||||
function computeInitialNextRun(
|
||||
scheduleType: ScheduledTask['schedule_type'],
|
||||
scheduleValue: string,
|
||||
nowIso: string,
|
||||
): { nextRun: string | null; error?: string } {
|
||||
if (scheduleType === 'cron') {
|
||||
try {
|
||||
const interval = CronExpressionParser.parse(scheduleValue, {
|
||||
tz: TIMEZONE,
|
||||
});
|
||||
return { nextRun: interval.next().toISOString() };
|
||||
} catch {
|
||||
return { nextRun: null, error: 'Invalid cron schedule' };
|
||||
}
|
||||
}
|
||||
|
||||
if (scheduleType === 'interval') {
|
||||
const ms = Number.parseInt(scheduleValue, 10);
|
||||
if (!Number.isFinite(ms) || ms <= 0) {
|
||||
return { nextRun: null, error: 'Invalid interval schedule' };
|
||||
}
|
||||
return {
|
||||
nextRun: new Date(new Date(nowIso).getTime() + ms).toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
const date = new Date(scheduleValue);
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
return { nextRun: null, error: 'Invalid timestamp schedule' };
|
||||
}
|
||||
return { nextRun: date.toISOString() };
|
||||
}
|
||||
|
||||
function resolveTaskRoom(
|
||||
body: ScheduledTaskMutationBody,
|
||||
roomBindings: Record<string, RegisteredGroup>,
|
||||
): { chatJid: string; group: RegisteredGroup } | null {
|
||||
const roomJid = normalizeNonEmptyString(body.roomJid);
|
||||
const groupFolder = normalizeNonEmptyString(body.groupFolder);
|
||||
if (roomJid && roomBindings[roomJid]) {
|
||||
return { chatJid: roomJid, group: roomBindings[roomJid] };
|
||||
}
|
||||
if (groupFolder) {
|
||||
const match = Object.entries(roomBindings).find(
|
||||
([, group]) => group.folder === groupFolder,
|
||||
);
|
||||
if (match) return { chatJid: match[0], group: match[1] };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function makeWebTaskId(): string {
|
||||
return `web-task-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
}
|
||||
|
||||
function sanitizeRoomMessageRequestId(value: unknown): string | null {
|
||||
if (typeof value !== 'string') return null;
|
||||
const trimmed = value.trim();
|
||||
@@ -299,6 +433,7 @@ export function createWebDashboardHandler(
|
||||
const loadTasks = opts.getTasks ?? getAllTasks;
|
||||
const loadTaskById = opts.getTaskById ?? getTaskById;
|
||||
const mutateTask = opts.updateTask ?? updateTask;
|
||||
const createScheduledTask = opts.createTask ?? createTask;
|
||||
const removeTask = opts.deleteTask ?? deleteTask;
|
||||
const loadPairedTasks = opts.getPairedTasks ?? getAllOpenPairedTasks;
|
||||
const loadPairedTaskById = opts.getPairedTaskById ?? getPairedTaskById;
|
||||
@@ -309,6 +444,7 @@ export function createWebDashboardHandler(
|
||||
const writeMessage = opts.storeMessage ?? storeMessage;
|
||||
const messageExists = opts.hasMessage ?? hasMessage;
|
||||
const enqueueMessageCheck = opts.enqueueMessageCheck;
|
||||
const nudgeScheduler = opts.nudgeScheduler;
|
||||
const statusMaxAgeMs = opts.statusMaxAgeMs ?? DEFAULT_STATUS_MAX_AGE_MS;
|
||||
const seenRoomMessageIds: string[] = [];
|
||||
const seenRoomMessageIdSet = new Set<string>();
|
||||
@@ -327,6 +463,7 @@ export function createWebDashboardHandler(
|
||||
return async (request: Request): Promise<Response> => {
|
||||
const url = new URL(request.url);
|
||||
const actionTaskId = parseTaskActionPath(url.pathname);
|
||||
const taskId = parseTaskPath(url.pathname);
|
||||
const actionInboxId = parseInboxActionPath(url.pathname);
|
||||
const messageRoomJid = parseRoomMessagePath(url.pathname);
|
||||
|
||||
@@ -495,6 +632,138 @@ export function createWebDashboardHandler(
|
||||
return jsonResponse({ ok: true, id, queued: true });
|
||||
}
|
||||
|
||||
if (url.pathname === '/api/tasks' && request.method === 'POST') {
|
||||
if (!loadRoomBindings) {
|
||||
return jsonResponse(
|
||||
{ error: 'Task creation is not configured' },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
const body = await readScheduledTaskMutationBody(request);
|
||||
const prompt = normalizeNonEmptyString(body?.prompt);
|
||||
const scheduleType =
|
||||
body && isScheduleType(body.scheduleType) ? body.scheduleType : null;
|
||||
const scheduleValue = normalizeNonEmptyString(body?.scheduleValue);
|
||||
if (!body || !prompt || !scheduleType || !scheduleValue) {
|
||||
return jsonResponse(
|
||||
{
|
||||
error:
|
||||
'Task prompt, schedule type, and schedule value are required',
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const room = resolveTaskRoom(body, loadRoomBindings());
|
||||
if (!room) {
|
||||
return jsonResponse({ error: 'Room not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
const nowIso = opts.now?.() ?? new Date().toISOString();
|
||||
const next = computeInitialNextRun(scheduleType, scheduleValue, nowIso);
|
||||
if (next.error) {
|
||||
return jsonResponse({ error: next.error }, { status: 400 });
|
||||
}
|
||||
|
||||
const contextMode = isContextMode(body.contextMode)
|
||||
? body.contextMode
|
||||
: 'isolated';
|
||||
const agentType = isAgentType(body.agentType)
|
||||
? body.agentType
|
||||
: (room.group.agentType ?? 'claude-code');
|
||||
const id = makeWebTaskId();
|
||||
createScheduledTask({
|
||||
id,
|
||||
group_folder: room.group.folder,
|
||||
chat_jid: room.chatJid,
|
||||
agent_type: agentType,
|
||||
prompt,
|
||||
schedule_type: scheduleType,
|
||||
schedule_value: scheduleValue,
|
||||
context_mode: contextMode,
|
||||
next_run: next.nextRun,
|
||||
status: 'active',
|
||||
created_at: nowIso,
|
||||
});
|
||||
|
||||
const created = loadTaskById(id);
|
||||
if (
|
||||
next.nextRun &&
|
||||
new Date(next.nextRun).getTime() <= new Date(nowIso).getTime()
|
||||
) {
|
||||
nudgeScheduler?.();
|
||||
}
|
||||
return jsonResponse({
|
||||
ok: true,
|
||||
task: created ? sanitizeScheduledTask(created) : null,
|
||||
});
|
||||
}
|
||||
|
||||
if (taskId && request.method === 'PATCH') {
|
||||
const task = loadTaskById(taskId);
|
||||
if (!task) {
|
||||
return jsonResponse({ error: 'Task not found' }, { status: 404 });
|
||||
}
|
||||
if (task.status === 'completed') {
|
||||
return jsonResponse(
|
||||
{ error: 'Completed tasks cannot be edited' },
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
if (isWatchCiTask(task)) {
|
||||
return jsonResponse(
|
||||
{ error: 'CI watchers cannot be edited here' },
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
|
||||
const body = await readScheduledTaskMutationBody(request);
|
||||
if (!body) {
|
||||
return jsonResponse({ error: 'Invalid task update' }, { status: 400 });
|
||||
}
|
||||
|
||||
const prompt =
|
||||
body.prompt === undefined
|
||||
? task.prompt
|
||||
: normalizeNonEmptyString(body.prompt);
|
||||
const scheduleType =
|
||||
body.scheduleType === undefined
|
||||
? task.schedule_type
|
||||
: isScheduleType(body.scheduleType)
|
||||
? body.scheduleType
|
||||
: null;
|
||||
const scheduleValue =
|
||||
body.scheduleValue === undefined
|
||||
? task.schedule_value
|
||||
: normalizeNonEmptyString(body.scheduleValue);
|
||||
if (!prompt || !scheduleType || !scheduleValue) {
|
||||
return jsonResponse({ error: 'Invalid task update' }, { status: 400 });
|
||||
}
|
||||
|
||||
const next = computeInitialNextRun(
|
||||
scheduleType,
|
||||
scheduleValue,
|
||||
opts.now?.() ?? new Date().toISOString(),
|
||||
);
|
||||
if (next.error) {
|
||||
return jsonResponse({ error: next.error }, { status: 400 });
|
||||
}
|
||||
|
||||
mutateTask(taskId, {
|
||||
prompt,
|
||||
schedule_type: scheduleType,
|
||||
schedule_value: scheduleValue,
|
||||
next_run: next.nextRun,
|
||||
suspended_until: null,
|
||||
});
|
||||
const updatedTask = loadTaskById(taskId);
|
||||
return jsonResponse({
|
||||
ok: true,
|
||||
task: updatedTask ? sanitizeScheduledTask(updatedTask) : null,
|
||||
});
|
||||
}
|
||||
|
||||
if (request.method !== 'GET' && request.method !== 'HEAD') {
|
||||
return jsonResponse({ error: 'Method not allowed' }, { status: 405 });
|
||||
}
|
||||
@@ -547,6 +816,7 @@ export function startWebDashboardServer(
|
||||
staticDir?: string;
|
||||
getRoomBindings?: () => Record<string, RegisteredGroup>;
|
||||
enqueueMessageCheck?: (chatJid: string, groupFolder: string) => void;
|
||||
nudgeScheduler?: () => void;
|
||||
} = {},
|
||||
): StartedWebDashboardServer | null {
|
||||
const enabled = opts.enabled ?? WEB_DASHBOARD.enabled;
|
||||
@@ -562,6 +832,7 @@ export function startWebDashboardServer(
|
||||
staticDir,
|
||||
getRoomBindings: opts.getRoomBindings,
|
||||
enqueueMessageCheck: opts.enqueueMessageCheck,
|
||||
nudgeScheduler: opts.nudgeScheduler,
|
||||
}),
|
||||
});
|
||||
const url = `http://${host}:${server.port}`;
|
||||
|
||||
Reference in New Issue
Block a user