feat(schedules,chat): redesign schedules as interactive calendar with server clock and chat tools

- Expose top-level server_time, server_timezone, and server_utc_offset_minutes on GET /api/schedules
- Add list_task_schedules, create_task_schedule, update_task_schedule, and delete_task_schedule chat agent tools
- Redesign /function/schedules into a calendar workspace (mini month, status filters, Up next, Day/Week/Month/Agenda views, server-time red indicator, TZ/date switcher, drag-move/resize, rich detail popover)
- Add schedule-calendar math unit tests and Postgres integration tests for chat schedule tools
This commit is contained in:
ji ruo committed 2026-12-03 00:28:01 +08:00
1 parent 778e49317d
commit 8568c41528
10 files changed
+2527 -26

No files matched your search

+9 -2
View File
@@ -85,6 +85,10 @@ func (s *Server) orchestrationTools() []actool.CoreTool {
s.toolBindFindingTraffic(),
s.toolListProxyPool(),
s.toolSetTaskProxy(),
s.toolListTaskSchedules(),
s.toolCreateTaskSchedule(),
s.toolUpdateTaskSchedule(),
s.toolDeleteTaskSchedule(),
}, s.findingCaseTools()...)
}
@@ -668,7 +672,9 @@ func defaultOrchestrationToolBindings(name string) json.RawMessage {
switch {
case name == "resume_task":
return json.RawMessage(`["auto","mainagent"]`)
case name == "list_proxy_pool" || name == "set_task_proxy":
case name == "list_proxy_pool" || name == "set_task_proxy" ||
name == "list_task_schedules" || name == "create_task_schedule" ||
name == "update_task_schedule" || name == "delete_task_schedule":
return json.RawMessage(`["auto","mainagent","pentest"]`)
case name == "bind_finding_traffic" || strings.Contains(name, "finding_case") || name == "search_finding_duplicates" || name == "get_finding_record" || name == "merge_finding_records":
return json.RawMessage(`["reporter"]`)
@@ -693,6 +699,7 @@ func (s *Server) seedOrchestrationTools() {
s.seedAutoDefaultBindings()
s.seedTaskReopenBindings()
s.seedProxyToolBindings()
s.seedScheduleToolBindings()
s.seedPlannerDefaultBindings()
s.seedPlannerListAssetsBinding()
s.seedCompanyScopeRebind()
@@ -784,7 +791,7 @@ func (s *Server) migrateReporterWorkflow() {
// reaches an old DB otherwise. Preserves each tool's agent binding + enabled flag.
// Bump the flag whenever these tools' schemas/descriptions change in code.
func (s *Server) refreshBuiltinToolSchemas() {
const flag = "tool_schema_refresh_v10_proxy_tools"
const flag = "tool_schema_refresh_v11_schedule_tools"
if v, _, _ := s.m.pg.GetSetting(flag); v == "true" {
return
}
+343
View File
@@ -0,0 +1,343 @@
package server
import (
"context"
"encoding/json"
"fmt"
"log"
"strconv"
"strings"
"time"
actool "github.com/Autumn-27/norma/tool"
)
func parseInt64Flexible(raw json.RawMessage) (int64, bool) {
if len(raw) == 0 {
return 0, false
}
var n int64
if json.Unmarshal(raw, &n) == nil && n > 0 {
return n, true
}
var s string
if json.Unmarshal(raw, &s) == nil {
s = strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(s), "#"))
if v, err := strconv.ParseInt(s, 10, 64); err == nil && v > 0 {
return v, true
}
}
return 0, false
}
func parseInt64SliceFlexible(raws []json.RawMessage) ([]int64, error) {
out := make([]int64, 0, len(raws))
seen := map[int64]bool{}
for _, r := range raws {
id, ok := parseInt64Flexible(r)
if !ok {
return nil, fmt.Errorf("无效的任务 ID: %s", string(r))
}
if !seen[id] {
seen[id] = true
out = append(out, id)
}
}
return out, nil
}
func serverClockMeta(now time.Time) (string, string, int) {
_, offsetSec := now.Zone()
return now.Format(time.RFC3339), time.Local.String(), offsetSec / 60
}
func (s *Server) toolListTaskSchedules() actool.CoreTool {
return roTool("list_task_schedules",
"查看所有定时日历计划任务(包含当前服务器时间与时区、规则类型、起止时间、关联任务、代理配置、状态与下次触发时间)。",
objSchema(map[string]any{}),
func(context.Context, json.RawMessage) (actool.Result, error) {
if s.m.pg == nil {
return actool.Errorf("数据库未初始化"), nil
}
items, err := s.m.pg.ListTaskSchedules()
if err != nil {
return actool.Errorf("查询计划任务失败: " + err.Error()), nil
}
dtos := make([]map[string]any, 0, len(items))
for _, item := range items {
dtos = append(dtos, s.scheduleDTO(item))
}
srvTime, srvTZ, srvOffset := serverClockMeta(time.Now())
return jsonResult(map[string]any{
"server_time": srvTime,
"server_timezone": srvTZ,
"server_utc_offset_minutes": srvOffset,
"schedules": dtos,
})
})
}
func (s *Server) toolCreateTaskSchedule() actool.CoreTool {
return wrTool("create_task_schedule",
"创建一个定时日历计划任务,按指定日历时间窗口自动控制一个或多个任务的运行与暂停(并可选绑定出口代理/代理池)。\n"+
"- schedule_type=weekly:按周重复,weekdays 填 1-7(1=周一…7=周日),start_time 必填(HH:MM),end_time 可选(留空表示开始后持续运行;早于 start_time 表示跨午夜到次日)。\n"+
"- schedule_type=once:一次性或跨多天区间,run_date 必填(YYYY-MM-DD),end_date 可选(YYYY-MM-DD),start_time 必填,end_time 可选。\n"+
"- 创建前可先用 list_task_schedules 查看当前 server_time,或用 list_tasks 查看任务 ID。",
objSchema(map[string]any{
"name": strParam("计划名称(必填)"),
"schedule_type": map[string]any{"type": "string", "enum": []string{"once", "weekly"}, "description": "规则类型:once=一次性,weekly=按周重复"},
"start_time": strParam("开始时间,格式 HH:MM(如 18:00)"),
"end_time": strParam("结束时间,格式 HH:MM(可选;留空=持续运行,小于 start_time=次日结束)"),
"run_date": strParam("开始日期 YYYY-MM-DD(schedule_type=once 时必填)"),
"end_date": strParam("结束日期 YYYY-MM-DD(可选,仅 schedule_type=once 跨多天时使用)"),
"weekdays": map[string]any{"type": "array", "items": map[string]any{"type": "integer"}, "description": "按周重复的星期列表 1-7(1=周一…7=周日;schedule_type=weekly 时必填)"},
"timezone_mode": map[string]any{"type": "string", "enum": []string{"beijing", "system"}, "description": "时区模式:beijing=北京时间(默认),system=服务器当前时区"},
"enabled": map[string]any{"type": "boolean", "description": "是否启用,默认 true"},
"start_immediately": map[string]any{"type": "boolean", "description": "保存后是否立即运行关联任务,默认 false"},
"task_ids": map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": "关联的任务 ID 列表(可传数字或字符串)"},
"proxy_mode": map[string]any{"type": "string", "enum": []string{"inherit", "direct", "pool", "proxy"}, "description": "可选:计划触发时应用到关联任务的代理模式"},
"proxy_pool_id": strParam("可选(proxy_mode=proxy 时):代理池节点 ID 或名称"),
"proxy_url": strParam("可选(proxy_mode=proxy 且未指定 proxy_pool_id 时):自定义代理 URL"),
}, "name", "schedule_type", "start_time"),
func(_ context.Context, in json.RawMessage) (actool.Result, error) {
if s.m.pg == nil {
return actool.Errorf("数据库未初始化"), nil
}
var a struct {
Name string `json:"name"`
Enabled *bool `json:"enabled"`
TimezoneMode string `json:"timezone_mode"`
ScheduleType string `json:"schedule_type"`
RunDate string `json:"run_date"`
EndDate string `json:"end_date"`
Weekdays []int `json:"weekdays"`
StartTime string `json:"start_time"`
EndTime string `json:"end_time"`
StartImmediately bool `json:"start_immediately"`
TaskIDs []json.RawMessage `json:"task_ids"`
ProxyMode string `json:"proxy_mode"`
ProxyPoolID string `json:"proxy_pool_id"`
ProxyURL string `json:"proxy_url"`
}
if err := json.Unmarshal(in, &a); err != nil {
return actool.Errorf("参数无效: " + err.Error()), nil
}
taskIDs, err := parseInt64SliceFlexible(a.TaskIDs)
if err != nil {
return actool.Errorf(err.Error()), nil
}
enabled := true
if a.Enabled != nil {
enabled = *a.Enabled
}
req := scheduleRequest{
Name: a.Name,
Enabled: &enabled,
TimezoneMode: a.TimezoneMode,
ScheduleType: a.ScheduleType,
RunDate: a.RunDate,
EndDate: a.EndDate,
Weekdays: a.Weekdays,
StartTime: a.StartTime,
EndTime: a.EndTime,
StartImmediately: a.StartImmediately,
ProxyMode: a.ProxyMode,
ProxyPoolID: a.ProxyPoolID,
ProxyURL: a.ProxyURL,
TaskIDs: taskIDs,
}
input := s.scheduleInput(req, nil)
if err := s.validateScheduleProxy(&input, nil); err != nil {
return actool.Errorf("代理配置无效: " + err.Error()), nil
}
item, err := s.m.pg.CreateTaskSchedule(input)
if err != nil {
return actool.Errorf("创建计划任务失败: " + err.Error()), nil
}
s.applyScheduleProxyToTasks(item)
if req.StartImmediately && item.Enabled {
s.runScheduleTasks(item)
}
return jsonResult(s.scheduleDTO(item))
})
}
func (s *Server) toolUpdateTaskSchedule() actool.CoreTool {
return wrTool("update_task_schedule",
"修改已有定时日历计划任务(仅需传要变更的字段,未传字段保持原值)。可修改时间窗、星期、关联任务、启停状态或代理/代理池配置。",
objSchema(map[string]any{
"schedule_id": strParam("要修改的计划任务 ID(必填)"),
"name": strParam("可选:新名称"),
"enabled": map[string]any{"type": "boolean", "description": "可选:启用或暂停该计划"},
"schedule_type": map[string]any{"type": "string", "enum": []string{"once", "weekly"}, "description": "可选:规则类型"},
"timezone_mode": map[string]any{"type": "string", "enum": []string{"beijing", "system"}, "description": "可选:时区模式"},
"run_date": strParam("可选:开始日期 YYYY-MM-DD"),
"end_date": strParam("可选:结束日期 YYYY-MM-DD(传空字符串清除)"),
"weekdays": map[string]any{"type": "array", "items": map[string]any{"type": "integer"}, "description": "可选:星期列表 1-7"},
"start_time": strParam("可选:开始时间 HH:MM"),
"end_time": strParam("可选:结束时间 HH:MM(传空字符串表示持续运行)"),
"start_immediately": map[string]any{"type": "boolean", "description": "可选:是否立即运行"},
"task_ids": map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": "可选:替换关联任务 ID 列表"},
"proxy_mode": map[string]any{"type": "string", "enum": []string{"inherit", "direct", "pool", "proxy"}, "description": "可选:代理模式"},
"proxy_pool_id": strParam("可选:代理池节点 ID 或名称"),
"proxy_url": strParam("可选:自定义代理 URL"),
}, "schedule_id"),
func(_ context.Context, in json.RawMessage) (actool.Result, error) {
if s.m.pg == nil {
return actool.Errorf("数据库未初始化"), nil
}
var a struct {
ScheduleID json.RawMessage `json:"schedule_id"`
Name *string `json:"name"`
Enabled *bool `json:"enabled"`
TimezoneMode *string `json:"timezone_mode"`
ScheduleType *string `json:"schedule_type"`
RunDate *string `json:"run_date"`
EndDate *string `json:"end_date"`
Weekdays *[]int `json:"weekdays"`
StartTime *string `json:"start_time"`
EndTime *string `json:"end_time"`
StartImmediately *bool `json:"start_immediately"`
TaskIDs *[]json.RawMessage `json:"task_ids"`
ProxyMode *string `json:"proxy_mode"`
ProxyPoolID *string `json:"proxy_pool_id"`
ProxyURL *string `json:"proxy_url"`
}
if err := json.Unmarshal(in, &a); err != nil {
return actool.Errorf("参数无效: " + err.Error()), nil
}
id, ok := parseInt64Flexible(a.ScheduleID)
if !ok {
return actool.Errorf("schedule_id 无效"), nil
}
old, err := s.m.pg.GetTaskSchedule(id)
if err != nil {
return actool.Errorf(fmt.Sprintf("计划任务 #%d 不存在", id)), nil
}
trimClock := func(v string) string {
if len(v) >= 5 {
return v[:5]
}
return v
}
req := scheduleRequest{
Name: old.Name,
Enabled: &old.Enabled,
TimezoneMode: old.TimezoneMode,
ScheduleType: old.ScheduleType,
RunDate: old.RunDate,
EndDate: old.EndDate,
Weekdays: old.Weekdays,
StartTime: trimClock(old.StartTime),
EndTime: trimClock(old.EndTime),
StartImmediately: old.StartImmediately,
ProxyMode: old.ProxyMode,
ProxyPoolID: old.ProxyPoolID,
ProxyURL: old.ProxyURL,
TaskIDs: old.TaskIDs,
}
if a.Name != nil {
req.Name = *a.Name
}
if a.Enabled != nil {
req.Enabled = a.Enabled
}
if a.TimezoneMode != nil {
req.TimezoneMode = *a.TimezoneMode
}
if a.ScheduleType != nil {
req.ScheduleType = *a.ScheduleType
}
if a.RunDate != nil {
req.RunDate = *a.RunDate
}
if a.EndDate != nil {
req.EndDate = *a.EndDate
}
if a.Weekdays != nil {
req.Weekdays = *a.Weekdays
}
if a.StartTime != nil {
req.StartTime = *a.StartTime
}
if a.EndTime != nil {
req.EndTime = *a.EndTime
}
if a.StartImmediately != nil {
req.StartImmediately = *a.StartImmediately
}
if a.TaskIDs != nil {
ids, perr := parseInt64SliceFlexible(*a.TaskIDs)
if perr != nil {
return actool.Errorf(perr.Error()), nil
}
req.TaskIDs = ids
}
if a.ProxyMode != nil {
req.ProxyMode = *a.ProxyMode
}
if a.ProxyPoolID != nil {
req.ProxyPoolID = *a.ProxyPoolID
}
if a.ProxyURL != nil {
req.ProxyURL = *a.ProxyURL
}
input := s.scheduleInput(req, old)
if err := s.validateScheduleProxy(&input, old); err != nil {
return actool.Errorf("代理配置无效: " + err.Error()), nil
}
item, err := s.m.pg.UpdateTaskSchedule(id, input)
if err != nil {
return actool.Errorf("更新计划任务失败: " + err.Error()), nil
}
s.applyScheduleProxyToTasks(item)
return jsonResult(s.scheduleDTO(item))
})
}
func (s *Server) toolDeleteTaskSchedule() actool.CoreTool {
return wrTool("delete_task_schedule",
"删除指定的定时日历计划任务(不会删除其关联的任务本身)。",
objSchema(map[string]any{
"schedule_id": strParam("要删除的计划任务 ID(必填)"),
}, "schedule_id"),
func(_ context.Context, in json.RawMessage) (actool.Result, error) {
if s.m.pg == nil {
return actool.Errorf("数据库未初始化"), nil
}
var a struct {
ScheduleID json.RawMessage `json:"schedule_id"`
}
if err := json.Unmarshal(in, &a); err != nil {
return actool.Errorf("参数无效: " + err.Error()), nil
}
id, ok := parseInt64Flexible(a.ScheduleID)
if !ok {
return actool.Errorf("schedule_id 无效"), nil
}
if _, err := s.m.pg.GetTaskSchedule(id); err != nil {
return actool.Errorf(fmt.Sprintf("计划任务 #%d 不存在", id)), nil
}
if err := s.m.pg.DeleteTaskSchedule(id); err != nil {
return actool.Errorf("删除计划任务失败: " + err.Error()), nil
}
return jsonResult(map[string]any{"deleted": true, "schedule_id": id})
})
}
// seedScheduleToolBindings binds calendar schedule tools to chat agents ONCE
// on existing DBs so users can create/manage calendar schedules from chat.
func (s *Server) seedScheduleToolBindings() {
const flag = "schedule_tool_bindings_v1"
if v, _, _ := s.m.pg.GetSetting(flag); v == "true" {
return
}
keys := []string{"list_task_schedules", "create_task_schedule", "update_task_schedule", "delete_task_schedule"}
for _, agentKey := range []string{"auto", "mainagent", "pentest"} {
if err := s.m.pg.AddAgentToToolBinding(agentKey, keys); err != nil {
log.Printf("[%s] 日历计划工具默认绑定失败: %v", agentKey, err)
return
}
}
_ = s.m.pg.SetSetting(flag, "true")
}
+125
View File
@@ -0,0 +1,125 @@
package server
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/Autumn-27/artex/db"
)
func TestChatScheduleToolsAndServerClock(t *testing.T) {
dsn := strings.TrimSpace(os.Getenv("ARTEX_PG_DSN"))
if dsn == "" {
t.Skip("requires ARTEX_PG_DSN")
}
pg, err := db.Open(dsn)
if err != nil {
t.Fatalf("open pg: %v", err)
}
defer pg.Close()
m := &Manager{
pg: pg,
dir: t.TempDir(),
tasks: map[string]*Task{},
proxyPool: &proxyPoolState{
active: "pool-1",
entries: []proxyPoolEntry{
{
ProxyPoolEntry: ProxyPoolEntry{ID: "pool-1", Name: "Node1", URL: "http://127.0.0.1:19801", Enabled: true, Health: "healthy"},
RawURL: "http://127.0.0.1:19801",
},
},
},
globalProxy: "http://127.0.0.1:19801",
}
s := &Server{m: m}
s.initProxyRoutesAndGateway()
task, err := m.CreateTask("calendar-chat-task", "test calendar creation from chat", nil, 0, 0)
if err != nil {
t.Fatalf("CreateTask: %v", err)
}
// 1. Create schedule from chat tool with proxy_mode=pool.
createTool := s.toolCreateTaskSchedule()
in := fmt.Sprintf(`{"name":"工作日夜间扫描","schedule_type":"weekly","weekdays":[1,2,3,4,5],"start_time":"18:00","end_time":"23:00","task_ids":[%q],"proxy_mode":"pool"}`, task.ID)
res, err := createTool.Call(context.Background(), json.RawMessage(in), nil)
if err != nil || res.IsError {
t.Fatalf("create_task_schedule failed: err=%v res=%+v", err, res)
}
text := ""
for _, b := range res.Content {
text += b.Text
}
var created map[string]any
if err := json.Unmarshal([]byte(text), &created); err != nil {
t.Fatalf("decode create_task_schedule: %v (%s)", err, text)
}
schedID := int64(created["id"].(float64))
if created["proxy_mode"] != "pool" {
t.Fatalf("expected proxy_mode=pool, got %+v", created)
}
// Verify bound task inherited proxy_mode=pool immediately.
view, _ := s.containerProxyRouteView("task", task.ID)
if view.Mode != "pool" {
t.Fatalf("expected task route mode=pool after create_task_schedule, got %+v", view)
}
// 2. List schedules via HTTP GET /api/schedules -> verify top-level server_time & offset.
rec := httptest.NewRecorder()
s.listSchedules(rec, httptest.NewRequest(http.MethodGet, "/api/schedules", nil))
if rec.Code != http.StatusOK {
t.Fatalf("listSchedules: %d %s", rec.Code, rec.Body.String())
}
var listResp map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &listResp); err != nil {
t.Fatalf("decode listSchedules: %v", err)
}
if listResp["server_time"] == "" || listResp["server_timezone"] == "" || listResp["server_utc_offset_minutes"] == nil {
t.Fatalf("expected server clock metadata in /api/schedules, got %+v", listResp)
}
// 3. Update schedule via chat tool (partial update).
updTool := s.toolUpdateTaskSchedule()
updIn := fmt.Sprintf(`{"schedule_id":%d,"end_time":"23:45"}`, schedID)
updRes, err := updTool.Call(context.Background(), json.RawMessage(updIn), nil)
if err != nil || updRes.IsError {
t.Fatalf("update_task_schedule failed: err=%v res=%+v", err, updRes)
}
updText := ""
for _, b := range updRes.Content {
updText += b.Text
}
if !strings.Contains(updText, "23:45") || !strings.Contains(updText, "工作日夜间扫描") {
t.Fatalf("unexpected update_task_schedule output: %s", updText)
}
// 4. List via chat tool.
listTool := s.toolListTaskSchedules()
listRes, err := listTool.Call(context.Background(), json.RawMessage(`{}`), nil)
if err != nil || listRes.IsError {
t.Fatalf("list_task_schedules failed: err=%v res=%+v", err, listRes)
}
listText := ""
for _, b := range listRes.Content {
listText += b.Text
}
if !strings.Contains(listText, `"server_time"`) || !strings.Contains(listText, "工作日夜间扫描") {
t.Fatalf("unexpected list_task_schedules output: %s", listText)
}
// 5. Delete via chat tool.
delTool := s.toolDeleteTaskSchedule()
delRes, err := delTool.Call(context.Background(), json.RawMessage(fmt.Sprintf(`{"schedule_id":%d}`, schedID)), nil)
if err != nil || delRes.IsError {
t.Fatalf("delete_task_schedule failed: err=%v res=%+v", err, delRes)
}
}
+7 -1
View File
@@ -147,7 +147,13 @@ func (s *Server) listSchedules(w http.ResponseWriter, r *http.Request) {
for _, item := range items {
dtos = append(dtos, s.scheduleDTO(item))
}
writeJSON(w, 200, map[string]any{"schedules": dtos})
srvTime, srvTZ, srvOffset := serverClockMeta(time.Now())
writeJSON(w, 200, map[string]any{
"schedules": dtos,
"server_time": srvTime,
"server_timezone": srvTZ,
"server_utc_offset_minutes": srvOffset,
})
}
func (s *Server) getSchedule(w http.ResponseWriter, r *http.Request) {
File diff suppressed because it is too large. Load diff
+114 -23
View File
@@ -29,6 +29,7 @@ import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
@@ -36,7 +37,9 @@ import { localizedError } from "@/i18n/errors";
import { useLiveTranslation } from "@/i18n/use-live-translation";
import { api, type ScheduleInput } from "@/lib/api";
import { scheduleDisplay } from "@/lib/schedule-display";
import { formatMinutesAsClock, weekdayOfDateKey } from "@/lib/schedule-calendar";
import type { ProxyPoolEntry, Task, TaskSchedule } from "@/lib/types";
import { ScheduleCalendarWorkspace } from "./_components/schedule-calendar-workspace";
const blank: ScheduleInput = {
name: "",
@@ -381,6 +384,8 @@ export default function SchedulesPage() {
const [items, setItems] = React.useState<TaskSchedule[]>([]);
const [tasks, setTasks] = React.useState<Task[]>([]);
const [proxyPool, setProxyPool] = React.useState<ProxyPoolEntry[]>([]);
const [serverTimeISO, setServerTimeISO] = React.useState<string | undefined>(undefined);
const [serverUtcOffsetMinutes, setServerUtcOffsetMinutes] = React.useState<number | undefined>(undefined);
const [loading, setLoading] = React.useState(true);
const [editing, setEditing] = React.useState<{ id?: number; value: ScheduleInput } | null>(null);
const [saving, setSaving] = React.useState(false);
@@ -394,12 +399,14 @@ export default function SchedulesPage() {
const load = React.useCallback(async () => {
setLoading(true);
try {
const [s, t, pool] = await Promise.all([
api.schedules(),
const [sRes, t, pool] = await Promise.all([
api.schedulesWithMeta(),
api.tasks(),
api.proxyPool().catch(() => ({ entries: [] as ProxyPoolEntry[], active_id: "", switch_log: [] })),
]);
setItems(s);
setItems(sRes.schedules);
setServerTimeISO(sRes.server_time);
setServerUtcOffsetMinutes(sRes.server_utc_offset_minutes);
setTasks(t.tasks);
setProxyPool(pool.entries ?? []);
} catch (e) {
@@ -468,6 +475,71 @@ export default function SchedulesPage() {
setTimelineLoadingId(null);
}
};
const openEdit = (item: TaskSchedule) => {
setEditing({
id: item.id,
value: {
name: item.name,
enabled: item.enabled,
timezone_mode: item.timezone_mode,
schedule_type: item.schedule_type,
run_date: item.run_date,
end_date: item.end_date,
weekdays: item.weekdays,
start_time: item.start_time.slice(0, 5),
end_time: item.end_time?.slice(0, 5),
start_immediately: item.start_immediately,
proxy_mode: item.proxy_mode ?? "inherit",
proxy_pool_id: item.proxy_pool_id ?? "",
proxy_url: item.proxy_url ?? "",
task_ids: item.task_ids,
},
});
};
const openDuplicate = (item: TaskSchedule) => {
setEditing({
value: {
name: `${item.name}${translate("schedule.calendar.duplicateSuffix")}`,
enabled: item.enabled,
timezone_mode: item.timezone_mode,
schedule_type: item.schedule_type,
run_date: item.run_date,
end_date: item.end_date,
weekdays: item.weekdays,
start_time: item.start_time.slice(0, 5),
end_time: item.end_time?.slice(0, 5),
start_immediately: false,
proxy_mode: item.proxy_mode ?? "inherit",
proxy_pool_id: item.proxy_pool_id ?? "",
proxy_url: item.proxy_url ?? "",
task_ids: item.task_ids,
},
});
};
const openCreateAtSlot = (dateKey: string, startMin: number, endMin: number) => {
setEditing({
value: {
...blank,
schedule_type: "once",
run_date: dateKey,
end_date: "",
weekdays: [weekdayOfDateKey(dateKey)],
start_time: formatMinutesAsClock(startMin),
end_time: formatMinutesAsClock(endMin),
task_ids: [],
},
});
};
const quickUpdateSchedule = async (id: number, input: ScheduleInput) => {
try {
await api.updateSchedule(id, input);
await invalidateTimeline(id);
await load();
toast.success(translate("schedule.calendar.dragUpdated"));
} catch (e) {
toast.error(scheduleErrorText(localizedError(e, translate)));
}
};
const invalidateTimeline = async (id: number) => {
setTimelineById((current) => {
if (!current[id]) return current;
@@ -909,28 +981,48 @@ export default function SchedulesPage() {
);
}
return (
<div className="flex flex-1 flex-col gap-5 p-5">
<div className="flex items-center justify-between">
<div className="flex flex-1 flex-col gap-3 p-4">
<div className="flex items-center justify-between gap-3">
<div>
<h1 className="flex items-center gap-2 font-semibold text-xl">
<CalendarClock />
<h1 className="flex items-center gap-2 font-semibold text-lg">
<CalendarClock className="size-5" />
{translate("schedule.title")}
</h1>
<p className="mt-1 text-muted-foreground text-sm">{translate("schedule.description")}</p>
<p className="text-muted-foreground text-xs">{translate("schedule.description")}</p>
</div>
<Button onClick={() => setEditing({ value: { ...blank, task_ids: [] } })}>
<Plus data-icon="inline-start" />
{translate("schedule.create")}
</Button>
</div>
{editing && (
<Card>
<CardHeader>
<CardTitle>{editing.id ? translate("schedule.editSchedule") : translate("schedule.create")}</CardTitle>
<CardDescription>{translate("schedule.pauseHelp")}</CardDescription>
</CardHeader>
<CardContent>
<ScheduleCalendarWorkspace
schedules={items}
tasks={tasks}
proxyPool={proxyPool}
serverTimeISO={serverTimeISO}
serverUtcOffsetMinutes={serverUtcOffsetMinutes}
query={query}
onQueryChange={updateQuery}
onCreateNew={() => setEditing({ value: { ...blank, task_ids: [] } })}
onCreateAtSlot={openCreateAtSlot}
onEdit={openEdit}
onDuplicate={openDuplicate}
onAction={action}
onDelete={remove}
onQuickUpdateSchedule={quickUpdateSchedule}
onLoadTimeline={async (id) => {
if (!timelineById[id]) await refreshTimeline(id);
}}
renderTimeline={(id) => <ScheduleTimeline schedule={timelineById[id]} loading={timelineLoadingId === id} />}
listViewContent={scheduleContent}
/>
<Dialog open={!!editing} onOpenChange={(open) => !open && setEditing(null)}>
<DialogContent className="max-h-[90vh] max-w-2xl overflow-y-auto">
<DialogHeader>
<DialogTitle>{editing?.id ? translate("schedule.editSchedule") : translate("schedule.create")}</DialogTitle>
<DialogDescription>{translate("schedule.pauseHelp")}</DialogDescription>
</DialogHeader>
{editing ? (
<ScheduleForm
key={editing.id ?? `new-${editing.value.run_date ?? ""}-${editing.value.start_time}`}
value={editing.value}
tasks={tasks}
proxyPool={proxyPool}
@@ -938,10 +1030,9 @@ export default function SchedulesPage() {
onCancel={() => setEditing(null)}
onSave={save}
/>
</CardContent>
</Card>
)}
{scheduleContent}
) : null}
</DialogContent>
</Dialog>
</div>
);
}
+45
View File
@@ -211,4 +211,49 @@ export const scheduleMessages = {
"设为直连、代理池或指定代理后,保存与计划触发时会自动应用到所有关联任务的容器。",
"When set to direct, proxy pool, or specific proxy, bound tasks automatically apply this route on save and when the schedule runs.",
],
"schedule.calendar.searchEvents": ["搜索计划、备注或任务 ID…", "Search schedules, remarks, or task IDs…"],
"schedule.calendar.today": ["今天", "Today"],
"schedule.calendar.view.day": ["日", "Day"],
"schedule.calendar.view.week": ["周", "Week"],
"schedule.calendar.view.month": ["月", "Month"],
"schedule.calendar.view.list": ["列表", "Agenda"],
"schedule.calendar.allDay": ["全天 / 持续", "All day"],
"schedule.calendar.filters": ["计划状态", "Calendars"],
"schedule.calendar.upNext": ["即将执行", "Up next"],
"schedule.calendar.noUpcoming": ["暂无待触发计划", "No upcoming schedules"],
"schedule.calendar.clockMode": ["日历时间基准", "Calendar clock"],
"schedule.calendar.clockServer": ["服务器时间", "Server time"],
"schedule.calendar.clockBeijing": ["北京时间", "Beijing (GMT+8)"],
"schedule.calendar.clockLocal": ["本地时间", "Local time"],
"schedule.calendar.jumpDate": ["跳转日期", "Jump to date"],
"schedule.calendar.duplicate": ["复制计划", "Duplicate"],
"schedule.calendar.duplicateSuffix": ["(副本)", " (copy)"],
"schedule.calendar.boundTasksCount": ["{{count}} 个关联任务", "{{count}} linked tasks"],
"schedule.calendar.boundTasksCount_one": ["1 个关联任务", "1 linked task"],
"schedule.calendar.boundTasksCount_other": ["{{count}} 个关联任务", "{{count}} linked tasks"],
"schedule.calendar.noBoundTasks": ["未绑定任务", "No linked tasks"],
"schedule.calendar.moreEvents": ["还有 {{count}} 项", "+{{count}} more"],
"schedule.calendar.inMinutes": ["{{count}} 分钟后", "in {{count}}m"],
"schedule.calendar.inHours": ["{{count}} 小时后", "in {{count}}h"],
"schedule.calendar.inDays": ["{{count}} 天后", "in {{count}}d"],
"schedule.calendar.nowRunning": ["进行中", "Now"],
"schedule.calendar.dragUpdated": ["已更新计划时间窗", "Schedule window updated"],
"schedule.calendar.dragHint": ["拖动调整时段 · 拖底边改时长", "Drag to move · drag bottom edge to resize"],
"schedule.calendar.durationHours": ["{{hours}}小时", "{{hours}}h"],
"schedule.calendar.durationHoursMinutes": ["{{hours}}小时{{minutes}}分", "{{hours}}h {{minutes}}m"],
"schedule.calendar.durationMinutes": ["{{minutes}}分钟", "{{minutes}}m"],
"schedule.calendar.timelineToggle": ["运行记录", "Run timeline"],
"schedule.calendar.prevMonth": ["上个月", "Previous month"],
"schedule.calendar.nextMonth": ["下个月", "Next month"],
"schedule.calendar.prevPeriod": ["上一周期", "Previous period"],
"schedule.calendar.nextPeriod": ["下一周期", "Next period"],
"schedule.calendar.selectAll": ["全选", "All"],
"schedule.calendar.continuousTag": ["持续运行", "Continuous"],
"schedule.calendar.weekdayShort.1": ["一", "M"],
"schedule.calendar.weekdayShort.2": ["二", "T"],
"schedule.calendar.weekdayShort.3": ["三", "W"],
"schedule.calendar.weekdayShort.4": ["四", "T"],
"schedule.calendar.weekdayShort.5": ["五", "F"],
"schedule.calendar.weekdayShort.6": ["六", "S"],
"schedule.calendar.weekdayShort.7": ["日", "S"],
} as const;
+12
View File
@@ -530,6 +530,18 @@ export const api = {
schedule: input.schedule ? schedulePayload(input.schedule) : undefined,
proxy_route: input.proxyRoute && input.proxyRoute.mode !== "inherit" ? input.proxyRoute : undefined,
}),
schedulesWithMeta: () =>
get<{
schedules: TaskSchedule[];
server_time?: string;
server_timezone?: string;
server_utc_offset_minutes?: number;
}>("/schedules").then((r) => ({
schedules: arr(r.schedules),
server_time: r.server_time,
server_timezone: r.server_timezone,
server_utc_offset_minutes: r.server_utc_offset_minutes,
})),
schedules: () => get<{ schedules: TaskSchedule[] }>("/schedules").then((r) => arr(r.schedules)),
renameSchedule: (id: number, name: string) => patch<TaskSchedule>(`/schedules/${id}/metadata`, { name }),
updateScheduleRemark: (id: number, remark: string) => patch<TaskSchedule>(`/schedules/${id}/remark`, { remark }),
+109
View File
@@ -0,0 +1,109 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
buildScheduleInputFromDrag,
buildWeekDateKeys,
expandSchedulesForDateKeys,
formatGMTOffset,
layoutDayTimedEvents,
toZonedParts,
} from "./schedule-calendar.ts";
test("server timezone offset formatting and zoned parts stay deterministic", () => {
assert.equal(formatGMTOffset(480), "GMT+8");
assert.equal(formatGMTOffset(330), "GMT+5:30");
assert.equal(formatGMTOffset(0), "UTC");
const utcMs = Date.UTC(2026, 11, 2, 16, 15, 0); // 2026-12-02T16:15:00Z -> 2026-12-03 00:15 GMT+8
const bj = toZonedParts(utcMs, 480);
assert.equal(bj.dateKey, "2026-12-03");
assert.equal(bj.hour, 0);
assert.equal(bj.minute, 15);
assert.equal(bj.weekday, 4); // Thursday
});
test("weekly, cross-midnight, open-ended, and timezone shift expansion work accurately", () => {
const weekKeys = buildWeekDateKeys("2026-12-02"); // Mon 2026-11-30 .. Sun 2026-12-06
assert.equal(weekKeys[0], "2026-11-30");
assert.equal(weekKeys[6], "2026-12-06");
const schedules = [
{
id: 1,
name: "Nightly cross-midnight",
enabled: true,
timezone_mode: "beijing",
schedule_type: "weekly",
weekdays: [1], // Monday
start_time: "22:00:00",
end_time: "02:00:00",
start_immediately: false,
status: "waiting",
task_ids: [10],
},
{
id: 2,
name: "Open continuous",
enabled: true,
timezone_mode: "beijing",
schedule_type: "weekly",
weekdays: [3], // Wednesday
start_time: "09:00:00",
end_time: "",
start_immediately: false,
status: "running",
task_ids: [11],
},
];
const occs = expandSchedulesForDateKeys(schedules, weekKeys, 480, 480);
const seg1 = occs.filter((o) => o.scheduleId === 1);
assert.equal(seg1.length, 2);
assert.equal(seg1[0].dateKey, "2026-11-30");
assert.equal(seg1[0].startMin, 22 * 60);
assert.equal(seg1[0].endMin, 24 * 60);
assert.equal(seg1[1].dateKey, "2026-12-01");
assert.equal(seg1[1].startMin, 0);
assert.equal(seg1[1].endMin, 2 * 60);
const openOcc = occs.filter((o) => o.scheduleId === 2);
assert.equal(openOcc.length, 1);
assert.equal(openOcc[0].allDay, true);
assert.equal(openOcc[0].dateKey, "2026-12-02");
});
test("overlap layout and drag/resize schedule update preserve timezone and weekday", () => {
const baseSchedule = {
id: 7,
name: "Design crit",
enabled: true,
timezone_mode: "beijing",
schedule_type: "weekly",
weekdays: [3],
start_time: "16:00:00",
end_time: "17:00:00",
start_immediately: false,
status: "waiting",
proxy_mode: "pool",
task_ids: [5],
};
const occs = expandSchedulesForDateKeys(
[
baseSchedule,
{ ...baseSchedule, id: 8, name: "Overlap", start_time: "16:30:00", end_time: "17:30:00" },
],
["2026-12-02"],
480,
480,
);
const laid = layoutDayTimedEvents(occs);
assert.equal(laid.length, 2);
assert.equal(laid[0].colCount, 2);
assert.notEqual(laid[0].col, laid[1].col);
// Resize from 16:00-17:00 to 16:00-17:45 and move to Thursday 2026-12-03
const updated = buildScheduleInputFromDrag(occs[0], "2026-12-03", 16 * 60, 17 * 60 + 45, 480, 480);
assert.equal(updated.start_time, "16:00");
assert.equal(updated.end_time, "17:45");
assert.deepEqual(updated.weekdays, [4]);
assert.equal(updated.proxy_mode, "pool");
});
+398
View File
@@ -0,0 +1,398 @@
import type { ScheduleInput } from "./api";
import type { TaskSchedule } from "./types";
export type CalendarViewMode = "day" | "week" | "month" | "list";
export type CalendarClockMode = "server" | "beijing" | "local";
export interface ZonedDateParts {
year: number;
month: number; // 1..12
day: number; // 1..31
weekday: number; // 1=Mon .. 7=Sun
hour: number; // 0..23
minute: number; // 0..59
dateKey: string; // YYYY-MM-DD
}
export interface CalendarEventOccurrence {
id: string;
scheduleId: number;
schedule: TaskSchedule;
dateKey: string; // YYYY-MM-DD in displayed timezone
startMin: number; // 0..1440
endMin: number; // 0..1440
allDay: boolean;
isContinuedFromPrev?: boolean;
isContinuesToNext?: boolean;
sourceWeekday?: number; // original weekday (1..7) for weekly drag updates
displayTimeRange: string;
}
export interface PositionedCalendarEvent extends CalendarEventOccurrence {
col: number;
colCount: number;
}
export function pad2(n: number): string {
return String(Math.floor(Math.abs(n))).padStart(2, "0");
}
export function makeDateKey(year: number, month: number, day: number): string {
return `${year}-${pad2(month)}-${pad2(day)}`;
}
export function parseDateKey(dateKey: string): { year: number; month: number; day: number } | null {
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(dateKey.trim());
if (!m) return null;
return { year: Number(m[1]), month: Number(m[2]), day: Number(m[3]) };
}
export function addDaysToDateKey(dateKey: string, deltaDays: number): string {
const p = parseDateKey(dateKey);
if (!p) return dateKey;
const d = new Date(Date.UTC(p.year, p.month - 1, p.day + deltaDays));
return makeDateKey(d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate());
}
export function weekdayOfDateKey(dateKey: string): number {
const p = parseDateKey(dateKey);
if (!p) return 1;
const day = new Date(Date.UTC(p.year, p.month - 1, p.day)).getUTCDay();
return day === 0 ? 7 : day;
}
export function toZonedParts(utcMs: number, offsetMinutes: number): ZonedDateParts {
const d = new Date(utcMs + offsetMinutes * 60_000);
const year = d.getUTCFullYear();
const month = d.getUTCMonth() + 1;
const day = d.getUTCDate();
const rawWd = d.getUTCDay();
const weekday = rawWd === 0 ? 7 : rawWd;
const hour = d.getUTCHours();
const minute = d.getUTCMinutes();
return {
year,
month,
day,
weekday,
hour,
minute,
dateKey: makeDateKey(year, month, day),
};
}
export function formatGMTOffset(offsetMinutes: number): string {
if (offsetMinutes === 0) return "UTC";
const sign = offsetMinutes > 0 ? "+" : "-";
const abs = Math.abs(offsetMinutes);
const h = Math.floor(abs / 60);
const m = abs % 60;
return m === 0 ? `GMT${sign}${h}` : `GMT${sign}${h}:${pad2(m)}`;
}
export function resolveDisplayOffsetMinutes(
clockMode: CalendarClockMode,
serverOffsetMinutes: number | null,
): number {
const localOffset = -new Date().getTimezoneOffset();
if (clockMode === "beijing") return 480;
if (clockMode === "local") return localOffset;
return serverOffsetMinutes ?? localOffset;
}
export function parseClockMinutes(clock?: string): number | null {
if (!clock) return null;
const trimmed = clock.trim();
if (trimmed === "24:00" || trimmed === "24:00:00") return 1440;
const m = /^(\d{1,2}):(\d{2})/.exec(trimmed);
if (!m) return null;
const h = Number(m[1]);
const min = Number(m[2]);
if (Number.isNaN(h) || Number.isNaN(min) || h < 0 || h > 24 || min < 0 || min > 59) return null;
return Math.min(1440, h * 60 + min);
}
export function formatMinutesAsClock(totalMinutes: number): string {
const clamped = Math.max(0, Math.min(1440, Math.round(totalMinutes)));
if (clamped === 1440) return "24:00";
const h = Math.floor(clamped / 60);
const m = clamped % 60;
return `${pad2(h)}:${pad2(m)}`;
}
export function startOfWeekDateKey(dateKey: string): string {
const wd = weekdayOfDateKey(dateKey);
return addDaysToDateKey(dateKey, -(wd - 1));
}
export function buildWeekDateKeys(anchorDateKey: string): string[] {
const monday = startOfWeekDateKey(anchorDateKey);
return Array.from({ length: 7 }, (_, i) => addDaysToDateKey(monday, i));
}
export function buildMonthGridDateKeys(year: number, month: number): string[] {
const firstOfMonth = makeDateKey(year, month, 1);
const firstMonday = startOfWeekDateKey(firstOfMonth);
return Array.from({ length: 42 }, (_, i) => addDaysToDateKey(firstMonday, i));
}
function scheduleOwnOffsetMinutes(item: TaskSchedule, serverOffsetMinutes: number): number {
if (item.timezone_mode === "beijing") return 480;
return serverOffsetMinutes;
}
function emitShiftedTimedInterval(
out: CalendarEventOccurrence[],
schedule: TaskSchedule,
baseDateKey: string,
startMinInScheduleTZ: number,
endMinInScheduleTZ: number, // may exceed 1440 for cross-midnight
shiftMinutes: number,
visibleSet: Set<string>,
sourceWeekday?: number,
) {
const absStart = startMinInScheduleTZ + shiftMinutes;
const absEnd = endMinInScheduleTZ + shiftMinutes;
const startDayShift = Math.floor(absStart / 1440);
const endDayShift = Math.floor((absEnd - 1) / 1440);
const labelStart = formatMinutesAsClock(((absStart % 1440) + 1440) % 1440);
const rawEndMod = ((absEnd % 1440) + 1440) % 1440;
const labelEnd = rawEndMod === 0 ? "24:00" : formatMinutesAsClock(rawEndMod);
const displayTimeRange = `${labelStart} - ${labelEnd}`;
for (let dShift = startDayShift; dShift <= endDayShift; dShift++) {
const dk = addDaysToDateKey(baseDateKey, dShift);
if (!visibleSet.has(dk)) continue;
const segStart = Math.max(dShift * 1440, absStart) - dShift * 1440;
const segEnd = Math.min((dShift + 1) * 1440, absEnd) - dShift * 1440;
if (segEnd <= segStart) continue;
out.push({
id: `${schedule.id}:${dk}:${segStart}:${segEnd}`,
scheduleId: schedule.id,
schedule,
dateKey: dk,
startMin: segStart,
endMin: segEnd,
allDay: false,
isContinuedFromPrev: dShift > startDayShift,
isContinuesToNext: dShift < endDayShift,
sourceWeekday,
displayTimeRange,
});
}
}
/**
* Expands TaskSchedule rules (weekly / once / cross-midnight / open-ended) into
* concrete occurrences for the requested visible date keys in the chosen display timezone.
*/
export function expandSchedulesForDateKeys(
schedules: TaskSchedule[],
visibleDateKeys: string[],
displayOffsetMinutes: number,
serverOffsetMinutes: number,
): CalendarEventOccurrence[] {
if (!visibleDateKeys.length || !schedules.length) return [];
const visibleSet = new Set(visibleDateKeys);
const sorted = [...visibleDateKeys].sort();
const minDate = addDaysToDateKey(sorted[0], -1);
const maxDate = addDaysToDateKey(sorted[sorted.length - 1], 1);
const scanDays: string[] = [];
let cur = minDate;
for (let guard = 0; guard < 60 && cur <= maxDate; guard++) {
scanDays.push(cur);
cur = addDaysToDateKey(cur, 1);
}
const out: CalendarEventOccurrence[] = [];
for (const item of schedules) {
const startMin = parseClockMinutes(item.start_time) ?? 0;
const endMin = parseClockMinutes(item.end_time);
const ownOffset = scheduleOwnOffsetMinutes(item, serverOffsetMinutes);
const shiftMin = displayOffsetMinutes - ownOffset;
if (item.schedule_type === "weekly") {
const wdSet = new Set(item.weekdays ?? []);
if (wdSet.size === 0) continue;
for (const dk of scanDays) {
const wd = weekdayOfDateKey(dk);
if (!wdSet.has(wd)) continue;
if (endMin === null) {
// Open-ended continuous schedule -> render in All day strip on each scheduled weekday.
const shiftedStart = startMin + shiftMin;
const dayShift = Math.floor(shiftedStart / 1440);
const targetDK = addDaysToDateKey(dk, dayShift);
if (!visibleSet.has(targetDK)) continue;
const clock = formatMinutesAsClock(((shiftedStart % 1440) + 1440) % 1440);
out.push({
id: `${item.id}:${targetDK}:allday`,
scheduleId: item.id,
schedule: item,
dateKey: targetDK,
startMin: 0,
endMin: 1440,
allDay: true,
sourceWeekday: wd,
displayTimeRange: `${clock} →`,
});
} else {
const effEnd = endMin <= startMin ? endMin + 1440 : endMin;
emitShiftedTimedInterval(out, item, dk, startMin, effEnd, shiftMin, visibleSet, wd);
}
}
continue;
}
// schedule_type === "once"
if (!item.run_date) continue;
if (item.end_date && item.end_date > item.run_date) {
// Multi-day once schedule -> render in All day strip across run_date..end_date.
let d = item.run_date;
for (let guard = 0; guard < 120 && d <= item.end_date; guard++) {
if (visibleSet.has(d)) {
const startClock = formatMinutesAsClock(startMin);
const endClock = endMin !== null ? formatMinutesAsClock(endMin) : "24:00";
out.push({
id: `${item.id}:${d}:multiday`,
scheduleId: item.id,
schedule: item,
dateKey: d,
startMin: 0,
endMin: 1440,
allDay: true,
isContinuedFromPrev: d > item.run_date,
isContinuesToNext: d < item.end_date,
displayTimeRange: `${startClock} - ${endClock}`,
});
}
d = addDaysToDateKey(d, 1);
}
continue;
}
if (endMin === null) {
const shiftedStart = startMin + shiftMin;
const dayShift = Math.floor(shiftedStart / 1440);
const targetDK = addDaysToDateKey(item.run_date, dayShift);
if (visibleSet.has(targetDK)) {
const clock = formatMinutesAsClock(((shiftedStart % 1440) + 1440) % 1440);
out.push({
id: `${item.id}:${targetDK}:once-open`,
scheduleId: item.id,
schedule: item,
dateKey: targetDK,
startMin: 0,
endMin: 1440,
allDay: true,
displayTimeRange: `${clock} →`,
});
}
} else {
const effEnd = endMin <= startMin ? endMin + 1440 : endMin;
emitShiftedTimedInterval(out, item, item.run_date, startMin, effEnd, shiftMin, visibleSet);
}
}
return out;
}
/**
* Assigns side-by-side column indices for overlapping timed events within a single day.
*/
export function layoutDayTimedEvents(events: CalendarEventOccurrence[]): PositionedCalendarEvent[] {
const timed = events
.filter((e) => !e.allDay)
.sort((a, b) => a.startMin - b.startMin || b.endMin - a.endMin || a.scheduleId - b.scheduleId);
if (timed.length === 0) return [];
// Group into connected overlap clusters so column counts stay local.
const clusters: CalendarEventOccurrence[][] = [];
let currentCluster: CalendarEventOccurrence[] = [];
let clusterEnd = -1;
for (const ev of timed) {
if (currentCluster.length === 0 || ev.startMin < clusterEnd) {
currentCluster.push(ev);
clusterEnd = Math.max(clusterEnd, ev.endMin);
} else {
clusters.push(currentCluster);
currentCluster = [ev];
clusterEnd = ev.endMin;
}
}
if (currentCluster.length > 0) clusters.push(currentCluster);
const result: PositionedCalendarEvent[] = [];
for (const cluster of clusters) {
const colEnds: number[] = [];
const placed: Array<{ ev: CalendarEventOccurrence; col: number }> = [];
for (const ev of cluster) {
let col = colEnds.findIndex((end) => end <= ev.startMin);
if (col === -1) {
col = colEnds.length;
colEnds.push(ev.endMin);
} else {
colEnds[col] = ev.endMin;
}
placed.push({ ev, col });
}
const colCount = Math.max(1, colEnds.length);
for (const p of placed) {
result.push({ ...p.ev, col: p.col, colCount });
}
}
return result;
}
/**
* Builds an updated ScheduleInput after dragging/resizing a timed occurrence in the UI.
*/
export function buildScheduleInputFromDrag(
occurrence: CalendarEventOccurrence,
newDateKey: string,
newStartMinInDisplayTZ: number,
newEndMinInDisplayTZ: number,
displayOffsetMinutes: number,
serverOffsetMinutes: number,
): ScheduleInput {
const item = occurrence.schedule;
const ownOffset = scheduleOwnOffsetMinutes(item, serverOffsetMinutes);
const reverseShift = ownOffset - displayOffsetMinutes;
const clampedStart = Math.max(0, Math.min(1425, Math.round(newStartMinInDisplayTZ / 15) * 15));
const clampedEnd = Math.max(clampedStart + 15, Math.min(1440, Math.round(newEndMinInDisplayTZ / 15) * 15));
const ownStartAbs = clampedStart + reverseShift;
const ownEndAbs = clampedEnd + reverseShift;
const dayShift = Math.floor(ownStartAbs / 1440);
const ownStartMod = ((ownStartAbs % 1440) + 1440) % 1440;
const ownEndRel = ownEndAbs - dayShift * 1440;
const ownEndClock = ownEndRel === 1440 ? "24:00" : formatMinutesAsClock(((ownEndRel % 1440) + 1440) % 1440);
const targetDateKey = addDaysToDateKey(newDateKey, dayShift);
let weekdays = [...(item.weekdays ?? [])];
if (item.schedule_type === "weekly" && newDateKey !== occurrence.dateKey && occurrence.sourceWeekday) {
const newWd = weekdayOfDateKey(targetDateKey);
const filtered = weekdays.filter((w) => w !== occurrence.sourceWeekday);
if (!filtered.includes(newWd)) filtered.push(newWd);
weekdays = filtered.sort((a, b) => a - b);
}
return {
name: item.name,
enabled: item.enabled,
timezone_mode: item.timezone_mode,
schedule_type: item.schedule_type,
run_date: item.schedule_type === "once" ? targetDateKey : item.run_date,
end_date: item.schedule_type === "once" ? "" : item.end_date,
weekdays: item.schedule_type === "weekly" ? weekdays : [],
start_time: formatMinutesAsClock(ownStartMod),
end_time: ownEndClock,
start_immediately: item.start_immediately,
proxy_mode: item.proxy_mode ?? "inherit",
proxy_pool_id: item.proxy_pool_id ?? "",
proxy_url: item.proxy_url ?? "",
task_ids: item.task_ids,
};
}