feat(dashboard): create and edit scheduled tasks

This commit is contained in:
Eyejoker
2026-04-27 03:05:04 +09:00
committed by GitHub
parent 16aeb0449d
commit 92e4e22e4d
7 changed files with 987 additions and 7 deletions

View File

@@ -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}`;