This commit is contained in:
lpf
2026-02-26 12:26:04 +08:00
parent 2615a6b196
commit dea7f361f2
9 changed files with 321 additions and 268 deletions

View File

@@ -237,42 +237,38 @@ func gatewayCmd() {
if name == "" {
name = "webui-cron"
}
kind := getStr("kind")
if kind == "" {
kind = "cron"
}
if kind == "once" {
kind = "at"
}
msg := getStr("message")
if msg == "" {
return nil, fmt.Errorf("message required")
}
schedule := cron.CronSchedule{Kind: kind}
if kind == "every" {
everyMS, ok := args["everyMs"].(float64)
if !ok || int64(everyMS) <= 0 {
return nil, fmt.Errorf("everyMs required for kind=every")
}
ev := int64(everyMS)
schedule.EveryMS = &ev
}
if kind == "at" {
atMS, ok := args["atMs"].(float64)
var at int64
if !ok || int64(atMS) <= 0 {
at = time.Now().Add(1 * time.Minute).UnixMilli()
} else {
at = int64(atMS)
}
schedule.AtMS = &at
}
if kind == "cron" {
expr := getStr("expr")
if expr == "" {
expr = "*/10 * * * *"
}
schedule := cron.CronSchedule{}
if expr := getStr("expr"); expr != "" {
schedule.Expr = expr
} else {
// Backward compatibility for older clients.
kind := strings.ToLower(getStr("kind"))
switch kind {
case "every":
everyMS, ok := args["everyMs"].(float64)
if !ok || int64(everyMS) <= 0 {
return nil, fmt.Errorf("expr required")
}
ev := int64(everyMS)
schedule.Kind = "every"
schedule.EveryMS = &ev
case "once", "at":
atMS, ok := args["atMs"].(float64)
var at int64
if !ok || int64(atMS) <= 0 {
at = time.Now().Add(1 * time.Minute).UnixMilli()
} else {
at = int64(atMS)
}
schedule.Kind = "at"
schedule.AtMS = &at
default:
return nil, fmt.Errorf("expr required")
}
}
deliver := false
if v, ok := args["deliver"].(bool); ok {
@@ -303,18 +299,22 @@ func gatewayCmd() {
if v := getStr("to"); v != "" {
in.To = &v
}
if kind := getStr("kind"); kind != "" {
if kind == "once" {
kind = "at"
}
if expr := getStr("expr"); expr != "" {
s := cron.CronSchedule{Expr: expr}
in.Schedule = &s
} else if kind := strings.ToLower(getStr("kind")); kind != "" {
// Backward compatibility for older clients.
s := cron.CronSchedule{Kind: kind}
if kind == "every" {
switch kind {
case "every":
if everyMS, ok := args["everyMs"].(float64); ok && int64(everyMS) > 0 {
ev := int64(everyMS)
s.EveryMS = &ev
} else {
return nil, fmt.Errorf("expr required")
}
}
if kind == "at" {
case "once", "at":
s.Kind = "at"
if atMS, ok := args["atMs"].(float64); ok && int64(atMS) > 0 {
at := int64(atMS)
s.AtMS = &at
@@ -322,13 +322,8 @@ func gatewayCmd() {
at := time.Now().Add(1 * time.Minute).UnixMilli()
s.AtMS = &at
}
}
if kind == "cron" {
expr := getStr("expr")
if expr == "" {
return nil, fmt.Errorf("expr required for kind=cron")
}
s.Expr = expr
default:
return nil, fmt.Errorf("expr required")
}
in.Schedule = &s
}
@@ -990,22 +985,22 @@ func buildHeartbeatService(cfg *config.Config, msgBus *bus.MessageBus) *heartbea
func buildAutonomyEngine(cfg *config.Config, msgBus *bus.MessageBus) *autonomy.Engine {
a := cfg.Agents.Defaults.Autonomy
return autonomy.NewEngine(autonomy.Options{
Enabled: a.Enabled,
TickIntervalSec: a.TickIntervalSec,
MinRunIntervalSec: a.MinRunIntervalSec,
MaxPendingDurationSec: a.MaxPendingDurationSec,
MaxConsecutiveStalls: a.MaxConsecutiveStalls,
MaxDispatchPerTick: a.MaxDispatchPerTick,
NotifyCooldownSec: a.NotifyCooldownSec,
Enabled: a.Enabled,
TickIntervalSec: a.TickIntervalSec,
MinRunIntervalSec: a.MinRunIntervalSec,
MaxPendingDurationSec: a.MaxPendingDurationSec,
MaxConsecutiveStalls: a.MaxConsecutiveStalls,
MaxDispatchPerTick: a.MaxDispatchPerTick,
NotifyCooldownSec: a.NotifyCooldownSec,
NotifySameReasonCooldownSec: a.NotifySameReasonCooldownSec,
QuietHours: a.QuietHours,
UserIdleResumeSec: a.UserIdleResumeSec,
WaitingResumeDebounceSec: a.WaitingResumeDebounceSec,
ImportantKeywords: cfg.Agents.Defaults.Texts.AutonomyImportantKeywords,
CompletionTemplate: cfg.Agents.Defaults.Texts.AutonomyCompletionTemplate,
BlockedTemplate: cfg.Agents.Defaults.Texts.AutonomyBlockedTemplate,
Workspace: cfg.WorkspacePath(),
DefaultNotifyChannel: a.NotifyChannel,
DefaultNotifyChatID: a.NotifyChatID,
QuietHours: a.QuietHours,
UserIdleResumeSec: a.UserIdleResumeSec,
WaitingResumeDebounceSec: a.WaitingResumeDebounceSec,
ImportantKeywords: cfg.Agents.Defaults.Texts.AutonomyImportantKeywords,
CompletionTemplate: cfg.Agents.Defaults.Texts.AutonomyCompletionTemplate,
BlockedTemplate: cfg.Agents.Defaults.Texts.AutonomyBlockedTemplate,
Workspace: cfg.WorkspacePath(),
DefaultNotifyChannel: a.NotifyChannel,
DefaultNotifyChatID: a.NotifyChatID,
}, msgBus)
}

1
go.mod
View File

@@ -10,6 +10,7 @@ require (
github.com/larksuite/oapi-sdk-go/v3 v3.5.3
github.com/mymmrac/telego v1.6.0
github.com/open-dingtalk/dingtalk-stream-sdk-go v0.9.1
github.com/robfig/cron/v3 v3.0.1
github.com/tencent-connect/botgo v0.2.1
golang.org/x/oauth2 v0.35.0
golang.org/x/sync v0.19.0

2
go.sum
View File

@@ -89,6 +89,8 @@ github.com/open-dingtalk/dingtalk-stream-sdk-go v0.9.1/go.mod h1:ln3IqPYYocZbYvl
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=

View File

@@ -1,53 +0,0 @@
package cron
import (
"fmt"
"strings"
"time"
)
// SimpleCronParser is a minimal cron expression parser (minute hour day month dayOfWeek).
// It approximates standard cron behavior to provide missing Expr scheduling support.
type SimpleCronParser struct {
expr string
}
func NewSimpleCronParser(expr string) *SimpleCronParser {
return &SimpleCronParser{expr: expr}
}
func (p *SimpleCronParser) Next(from time.Time) time.Time {
fields := strings.Fields(p.expr)
if len(fields) != 5 {
return time.Time{} // Invalid format
}
// This minimal implementation only supports "*" and exact numbers.
// For production, use github.com/robfig/cron/v3.
next := from.Add(1 * time.Minute).Truncate(time.Minute)
// Simplified logic: if it is not "*" and does not match, keep incrementing until matched
// (up to one year of search).
for i := 0; i < 525600; i++ {
if p.match(next, fields) {
return next
}
next = next.Add(1 * time.Minute)
}
return time.Time{}
}
func (p *SimpleCronParser) match(t time.Time, fields []string) bool {
return matchField(fmt.Sprintf("%d", t.Minute()), fields[0]) &&
matchField(fmt.Sprintf("%d", t.Hour()), fields[1]) &&
matchField(fmt.Sprintf("%d", t.Day()), fields[2]) &&
matchField(fmt.Sprintf("%d", int(t.Month())), fields[3]) &&
matchField(fmt.Sprintf("%d", int(t.Weekday())), fields[4])
}
func matchField(val, field string) bool {
if field == "*" {
return true
}
return val == field
}

View File

@@ -6,10 +6,12 @@ import (
"math"
"os"
"path/filepath"
"strings"
"sync"
"time"
"clawgo/pkg/lifecycle"
robcron "github.com/robfig/cron/v3"
)
const (
@@ -342,6 +344,10 @@ func (cs *CronService) computeNextRun(schedule *CronSchedule, nowMS int64) *int6
}
func (cs *CronService) computeNextRunAfter(schedule *CronSchedule, baseMS int64, nowMS int64) *int64 {
if schedule == nil {
return nil
}
if schedule.Kind == "at" {
if schedule.AtMS != nil && *schedule.AtMS > nowMS {
return schedule.AtMS
@@ -349,26 +355,126 @@ func (cs *CronService) computeNextRunAfter(schedule *CronSchedule, baseMS int64,
return nil
}
if schedule.Kind == "every" {
if schedule.EveryMS == nil || *schedule.EveryMS <= 0 {
return nil
}
next := computeAlignedEveryNext(baseMS, nowMS, *schedule.EveryMS)
return &next
expr, ok := cronExprFromSchedule(schedule)
if !ok {
return nil
}
compiled, err := parseCronSchedule(expr, strings.TrimSpace(schedule.TZ))
if err != nil {
return nil
}
if schedule.Kind == "cron" && schedule.Expr != "" {
parser := NewSimpleCronParser(schedule.Expr)
next := parser.Next(time.UnixMilli(nowMS))
if !next.IsZero() {
ms := next.UnixMilli()
return &ms
}
base := time.UnixMilli(baseMS)
now := time.UnixMilli(nowMS)
next := compiled.Next(base)
for i := 0; i < 1024 && !next.After(now); i++ {
next = compiled.Next(next)
}
if next.After(now) {
ms := next.UnixMilli()
return &ms
}
return nil
}
func cronExprFromSchedule(schedule *CronSchedule) (string, bool) {
if schedule == nil {
return "", false
}
if expr := strings.TrimSpace(schedule.Expr); expr != "" {
return expr, true
}
if schedule.Kind == "every" && schedule.EveryMS != nil && *schedule.EveryMS > 0 {
d := time.Duration(*schedule.EveryMS) * time.Millisecond
return "@every " + d.String(), true
}
return "", false
}
func parseCronSchedule(expr, tz string) (robcron.Schedule, error) {
spec := strings.TrimSpace(expr)
if spec == "" {
return nil, fmt.Errorf("empty cron expression")
}
tz = strings.TrimSpace(tz)
if tz != "" && !strings.HasPrefix(spec, "CRON_TZ=") && !strings.HasPrefix(spec, "TZ=") {
spec = "CRON_TZ=" + tz + " " + spec
}
parser := robcron.NewParser(
robcron.Minute |
robcron.Hour |
robcron.Dom |
robcron.Month |
robcron.Dow |
robcron.Descriptor,
)
return parser.Parse(spec)
}
func normalizeSchedule(schedule CronSchedule) CronSchedule {
schedule.Kind = strings.ToLower(strings.TrimSpace(schedule.Kind))
schedule.Expr = strings.TrimSpace(schedule.Expr)
schedule.TZ = strings.TrimSpace(schedule.TZ)
if schedule.Expr != "" {
schedule.Kind = "cron"
schedule.AtMS = nil
schedule.EveryMS = nil
return schedule
}
if schedule.Kind == "every" && schedule.EveryMS != nil && *schedule.EveryMS > 0 {
d := time.Duration(*schedule.EveryMS) * time.Millisecond
schedule.Expr = "@every " + d.String()
schedule.Kind = "cron"
schedule.EveryMS = nil
return schedule
}
if schedule.Kind == "at" {
schedule.EveryMS = nil
return schedule
}
if schedule.AtMS != nil {
schedule.Kind = "at"
return schedule
}
if schedule.EveryMS != nil && *schedule.EveryMS > 0 {
d := time.Duration(*schedule.EveryMS) * time.Millisecond
schedule.Expr = "@every " + d.String()
schedule.Kind = "cron"
schedule.EveryMS = nil
return schedule
}
if schedule.Expr != "" {
schedule.Kind = "cron"
}
return schedule
}
func validateSchedule(schedule CronSchedule) error {
if schedule.Kind == "at" {
if schedule.AtMS == nil || *schedule.AtMS <= time.Now().UnixMilli() {
return fmt.Errorf("invalid one-time schedule")
}
return nil
}
expr, ok := cronExprFromSchedule(&schedule)
if !ok {
return fmt.Errorf("cron expression is required")
}
_, err := parseCronSchedule(expr, schedule.TZ)
if err != nil {
return fmt.Errorf("invalid cron expression: %w", err)
}
return nil
}
func (cs *CronService) recomputeNextRuns() bool {
changed := false
now := time.Now().UnixMilli()
@@ -427,7 +533,13 @@ func (cs *CronService) loadStore() error {
return err
}
return json.Unmarshal(data, cs.store)
if err := json.Unmarshal(data, cs.store); err != nil {
return err
}
for i := range cs.store.Jobs {
cs.store.Jobs[i].Schedule = normalizeSchedule(cs.store.Jobs[i].Schedule)
}
return nil
}
func (cs *CronService) saveStore() error {
@@ -479,6 +591,11 @@ func (cs *CronService) AddJob(name string, schedule CronSchedule, message string
cs.mu.Lock()
defer cs.mu.Unlock()
schedule = normalizeSchedule(schedule)
if err := validateSchedule(schedule); err != nil {
return nil, err
}
now := time.Now().UnixMilli()
job := CronJob{
@@ -589,18 +706,6 @@ func (cs *CronService) unmarkJobRunning(jobID string) {
delete(cs.running, jobID)
}
func computeAlignedEveryNext(baseMS, nowMS, intervalMS int64) int64 {
if intervalMS <= 0 {
return nowMS
}
next := baseMS + intervalMS
if next > nowMS {
return next
}
miss := (nowMS-next)/intervalMS + 1
return next + miss*intervalMS
}
func computeRetryBackoff(consecutiveFailures int64, base, max time.Duration) time.Duration {
if base <= 0 {
base = defaultRetryBackoffBase
@@ -688,7 +793,11 @@ func (cs *CronService) UpdateJob(jobID string, in UpdateJobInput) (*CronJob, err
job.Name = *in.Name
}
if in.Schedule != nil {
job.Schedule = *in.Schedule
nextSchedule := normalizeSchedule(*in.Schedule)
if err := validateSchedule(nextSchedule); err != nil {
return nil, err
}
job.Schedule = nextSchedule
if job.Enabled {
now := time.Now().UnixMilli()
job.State.NextRunAtMS = cs.computeNextRun(&job.Schedule, now)

View File

@@ -46,9 +46,9 @@ func NewRegistryServer(host string, port int, token string, mgr *Manager) *Regis
return &RegistryServer{addr: fmt.Sprintf("%s:%d", addr, port), token: strings.TrimSpace(token), mgr: mgr}
}
func (s *RegistryServer) SetConfigPath(path string) { s.configPath = strings.TrimSpace(path) }
func (s *RegistryServer) SetConfigPath(path string) { s.configPath = strings.TrimSpace(path) }
func (s *RegistryServer) SetWorkspacePath(path string) { s.workspacePath = strings.TrimSpace(path) }
func (s *RegistryServer) SetLogFilePath(path string) { s.logFilePath = strings.TrimSpace(path) }
func (s *RegistryServer) SetLogFilePath(path string) { s.logFilePath = strings.TrimSpace(path) }
func (s *RegistryServer) SetChatHandler(fn func(ctx context.Context, sessionKey, content string) (string, error)) {
s.onChat = fn
}
@@ -131,7 +131,9 @@ func (s *RegistryServer) handleHeartbeat(w http.ResponseWriter, r *http.Request)
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
var body struct{ ID string `json:"id"` }
var body struct {
ID string `json:"id"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil || strings.TrimSpace(body.ID) == "" {
http.Error(w, "id required", http.StatusBadRequest)
return
@@ -633,17 +635,27 @@ func (s *RegistryServer) handleWebUISkills(w http.ResponseWriter, r *http.Reques
desc, tools, sys := readSkillMeta(filepath.Join(dir, name, "SKILL.md"))
if desc == "" || len(tools) == 0 || sys == "" {
d2, t2, s2 := readSkillMeta(filepath.Join(dir, baseName, "SKILL.md"))
if desc == "" { desc = d2 }
if len(tools) == 0 { tools = t2 }
if sys == "" { sys = s2 }
if desc == "" {
desc = d2
}
if len(tools) == 0 {
tools = t2
}
if sys == "" {
sys = s2
}
}
if tools == nil {
tools = []string{}
}
if tools == nil { tools = []string{} }
it := skillItem{ID: baseName, Name: baseName, Description: desc, Tools: tools, SystemPrompt: sys, Enabled: enabled, UpdateChecked: checkUpdates, Source: dir}
if checkUpdates {
found, version, checkErr := queryClawHubSkillVersion(r.Context(), baseName)
it.RemoteFound = found
it.RemoteVersion = version
if checkErr != nil { it.CheckError = checkErr.Error() }
if checkErr != nil {
it.CheckError = checkErr.Error()
}
}
items = append(items, it)
}
@@ -660,7 +672,9 @@ func (s *RegistryServer) handleWebUISkills(w http.ResponseWriter, r *http.Reques
action = strings.ToLower(strings.TrimSpace(action))
id, _ := body["id"].(string)
name, _ := body["name"].(string)
if strings.TrimSpace(name) == "" { name = id }
if strings.TrimSpace(name) == "" {
name = id
}
name = strings.TrimSpace(name)
if name == "" {
http.Error(w, "name required", http.StatusBadRequest)
@@ -701,7 +715,9 @@ func (s *RegistryServer) handleWebUISkills(w http.ResponseWriter, r *http.Reques
var toolsList []string
if arr, ok := body["tools"].([]interface{}); ok {
for _, v := range arr {
if sv, ok := v.(string); ok && strings.TrimSpace(sv) != "" { toolsList = append(toolsList, strings.TrimSpace(sv)) }
if sv, ok := v.(string); ok && strings.TrimSpace(sv) != "" {
toolsList = append(toolsList, strings.TrimSpace(sv))
}
}
}
if action == "create" {
@@ -733,8 +749,12 @@ func (s *RegistryServer) handleWebUISkills(w http.ResponseWriter, r *http.Reques
pathA := filepath.Join(skillsDir, id)
pathB := pathA + ".disabled"
deleted := false
if err := os.RemoveAll(pathA); err == nil { deleted = true }
if err := os.RemoveAll(pathB); err == nil { deleted = true }
if err := os.RemoveAll(pathA); err == nil {
deleted = true
}
if err := os.RemoveAll(pathB); err == nil {
deleted = true
}
_ = json.NewEncoder(w).Encode(map[string]interface{}{"ok": true, "deleted": deleted, "id": id})
default:
@@ -742,7 +762,6 @@ func (s *RegistryServer) handleWebUISkills(w http.ResponseWriter, r *http.Reques
}
}
func buildSkillMarkdown(name, desc string, tools []string, systemPrompt string) string {
if strings.TrimSpace(desc) == "" {
desc = "No description provided."
@@ -913,16 +932,32 @@ func normalizeCronJob(v interface{}) map[string]interface{} {
out[k] = val
}
if sch, ok := m["schedule"].(map[string]interface{}); ok {
if kind, ok := sch["kind"]; ok { out["kind"] = kind }
if every, ok := sch["everyMs"]; ok { out["everyMs"] = every }
if expr, ok := sch["expr"]; ok { out["expr"] = expr }
if at, ok := sch["atMs"]; ok { out["atMs"] = at }
kind, _ := sch["kind"].(string)
if expr, ok := sch["expr"].(string); ok && strings.TrimSpace(expr) != "" {
out["expr"] = strings.TrimSpace(expr)
} else if strings.EqualFold(strings.TrimSpace(kind), "every") {
if every, ok := sch["everyMs"].(float64); ok && every > 0 {
out["expr"] = fmt.Sprintf("@every %s", (time.Duration(int64(every)) * time.Millisecond).String())
}
} else if strings.EqualFold(strings.TrimSpace(kind), "at") {
if at, ok := sch["atMs"].(float64); ok && at > 0 {
out["expr"] = time.UnixMilli(int64(at)).Format(time.RFC3339)
}
}
}
if payload, ok := m["payload"].(map[string]interface{}); ok {
if msg, ok := payload["message"]; ok { out["message"] = msg }
if d, ok := payload["deliver"]; ok { out["deliver"] = d }
if c, ok := payload["channel"]; ok { out["channel"] = c }
if to, ok := payload["to"]; ok { out["to"] = to }
if msg, ok := payload["message"]; ok {
out["message"] = msg
}
if d, ok := payload["deliver"]; ok {
out["deliver"] = d
}
if c, ok := payload["channel"]; ok {
out["channel"] = c
}
if to, ok := payload["to"]; ok {
out["to"] = to
}
}
return out
}

View File

@@ -60,17 +60,19 @@ app.get("/webui/api/cron", (req, res) => {
});
app.post("/webui/api/cron", (req, res) => {
const { action, id, ...rest } = req.body || {};
const { action, id, expr, ...rest } = req.body || {};
if (action === "create") {
if (!String(expr || "").trim()) return res.status(400).json({ error: "expr required" });
const newId = Math.random().toString(36).slice(2);
const job = { id: newId, enabled: true, ...rest };
const job = { id: newId, enabled: true, expr: String(expr).trim(), ...rest };
mem.cronJobs.push(job);
addLog("INFO", `Created cron job: ${job.name || newId}`);
return res.json({ id: newId, status: "ok" });
}
if (action === "update") {
if (expr !== undefined && !String(expr || "").trim()) return res.status(400).json({ error: "expr required" });
const idx = mem.cronJobs.findIndex((j) => j.id === id);
if (idx >= 0) mem.cronJobs[idx] = { ...mem.cronJobs[idx], ...rest };
if (idx >= 0) mem.cronJobs[idx] = { ...mem.cronJobs[idx], ...(expr !== undefined ? { expr: String(expr).trim() } : {}), ...rest };
addLog("INFO", `Updated cron job: ${id}`);
return res.json({ status: "ok" });
}

View File

@@ -7,15 +7,13 @@ import { CronJob } from '../types';
const initialCronForm = {
name: '',
kind: 'cron',
everyMs: 600000,
expr: '*/10 * * * *',
message: '',
deliver: false,
channel: 'telegram',
to: '',
enabled: true
}
enabled: true,
};
const Cron: React.FC = () => {
const { t } = useTranslation();
@@ -27,7 +25,9 @@ const Cron: React.FC = () => {
async function cronAction(action: 'delete' | 'enable' | 'disable', id: string) {
try {
await fetch(`/webui/api/cron${q}`, {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action, id }),
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action, id }),
});
await refreshCron();
} catch (e) {
@@ -44,18 +44,16 @@ const Cron: React.FC = () => {
setEditingCron(details.job);
setCronForm({
name: details.job.name || '',
kind: details.job.kind || 'cron',
everyMs: details.job.everyMs || 600000,
expr: details.job.expr || '',
message: details.job.message || '',
deliver: details.job.deliver || false,
channel: details.job.channel || 'telegram',
to: details.job.to || '',
enabled: details.job.enabled ?? true
enabled: details.job.enabled ?? true,
});
}
} catch (e) {
console.error("Failed to fetch job details", e);
console.error('Failed to fetch job details', e);
}
} else {
setEditingCron(null);
@@ -70,24 +68,24 @@ const Cron: React.FC = () => {
const payload = {
action,
...(editingCron && { id: editingCron.id }),
...cronForm
...cronForm,
};
const r = await fetch(`/webui/api/cron${q}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
body: JSON.stringify(payload),
});
if (r.ok) {
setIsCronModalOpen(false);
await refreshCron();
} else {
const err = await r.text();
alert("Action failed: " + err);
alert('Action failed: ' + err);
}
} catch (e) {
alert("Action failed: " + e);
alert('Action failed: ' + e);
}
}
@@ -106,56 +104,49 @@ const Cron: React.FC = () => {
</div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{cron.map(j => (
{cron.map((j) => (
<div key={j.id} className="bg-zinc-900/40 border border-zinc-800/80 rounded-2xl p-6 flex flex-col shadow-sm group hover:border-zinc-700/50 transition-colors">
<div className="flex items-start justify-between mb-4">
<div>
<h3 className="font-semibold text-zinc-100 mb-1">{j.name || j.id}</h3>
<div className="flex items-center gap-2">
<span className="text-[10px] font-mono text-zinc-500 uppercase tracking-wider bg-zinc-800/50 px-2 py-0.5 rounded">ID: {j.id.slice(-6)}</span>
<span className="text-[10px] font-mono text-zinc-500 uppercase tracking-wider bg-zinc-800/50 px-2 py-0.5 rounded">{j.kind}</span>
</div>
</div>
{j.enabled ? (
<span className="flex items-center gap-1.5 text-xs font-medium text-emerald-400 bg-emerald-400/10 px-2.5 py-1 rounded-full border border-emerald-500/20">
<CheckCircle2 className="w-3.5 h-3.5"/> {t('active')}
<CheckCircle2 className="w-3.5 h-3.5" /> {t('active')}
</span>
) : (
<span className="flex items-center gap-1.5 text-xs font-medium text-zinc-400 bg-zinc-800 px-2.5 py-1 rounded-full border border-zinc-700/50">
<Pause className="w-3.5 h-3.5"/> {t('paused')}
<Pause className="w-3.5 h-3.5" /> {t('paused')}
</span>
)}
</div>
<div className="flex-1 space-y-3 mb-6">
<div className="text-sm text-zinc-400 line-clamp-2 italic">"{j.message}"</div>
<div className="grid grid-cols-2 gap-2">
<div className="bg-zinc-950/50 rounded-lg p-2 border border-zinc-800/50">
<div className="text-[10px] text-zinc-500 uppercase mb-0.5">{t('kind')}</div>
<div className="text-xs text-zinc-300 font-medium">{j.kind}</div>
</div>
<div className="bg-zinc-950/50 rounded-lg p-2 border border-zinc-800/50">
<div className="text-[10px] text-zinc-500 uppercase mb-0.5">{j.kind === 'cron' ? t('cronExpression') : t('everyMs')}</div>
<div className="text-xs text-zinc-300 font-medium truncate">{j.kind === 'cron' ? j.expr : j.everyMs}</div>
</div>
<div className="bg-zinc-950/50 rounded-lg p-2 border border-zinc-800/50">
<div className="text-[10px] text-zinc-500 uppercase mb-0.5">{t('cronExpression')}</div>
<div className="text-xs text-zinc-300 font-medium break-all">{j.expr || '-'}</div>
</div>
</div>
<div className="flex items-center gap-2 pt-4 border-t border-zinc-800/50">
<button
<button
onClick={() => openCronModal(j)}
className="flex-1 flex items-center justify-center gap-2 py-2 bg-zinc-800 hover:bg-zinc-700 rounded-lg text-xs font-medium transition-colors text-zinc-300"
>
<Edit2 className="w-3.5 h-3.5" /> {t('editJob')}
</button>
<button
<button
onClick={() => cronAction(j.enabled ? 'disable' : 'enable', j.id)}
className={`p-2 rounded-lg transition-colors ${j.enabled ? 'bg-amber-500/10 text-amber-500 hover:bg-amber-500/20' : 'bg-emerald-500/10 text-emerald-500 hover:bg-emerald-500/20'}`}
title={j.enabled ? t('pauseJob') : t('startJob')}
>
{j.enabled ? <Pause className="w-4 h-4" /> : <Play className="w-4 h-4" />}
</button>
<button
<button
onClick={() => cronAction('delete', j.id)}
className="p-2 bg-red-500/10 text-red-500 hover:bg-red-500/20 rounded-lg transition-colors"
title={t('deleteJob')}
@@ -173,18 +164,17 @@ const Cron: React.FC = () => {
)}
</div>
{/* Cron Modal */}
<AnimatePresence>
{isCronModalOpen && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
<motion.div
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
onClick={() => setIsCronModalOpen(false)}
className="absolute inset-0 bg-black/60 backdrop-blur-sm"
/>
<motion.div
<motion.div
initial={{ opacity: 0, scale: 0.95, y: 20 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.95, y: 20 }}
@@ -196,103 +186,77 @@ const Cron: React.FC = () => {
<X className="w-5 h-5" />
</button>
</div>
<div className="p-6 space-y-4 max-h-[70vh] overflow-y-auto">
<div className="grid grid-cols-2 gap-4">
<label className="block">
<span className="text-sm font-medium text-zinc-400 mb-1.5 block">{t('jobName')}</span>
<input
type="text"
value={cronForm.name}
onChange={(e) => setCronForm({...cronForm, name: e.target.value})}
className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 transition-colors"
<input
type="text"
value={cronForm.name}
onChange={(e) => setCronForm({ ...cronForm, name: e.target.value })}
className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 transition-colors"
/>
</label>
<label className="block">
<span className="text-sm font-medium text-zinc-400 mb-1.5 block">{t('kind')}</span>
<select
value={cronForm.kind}
onChange={(e) => setCronForm({...cronForm, kind: e.target.value})}
<span className="text-sm font-medium text-zinc-400 mb-1.5 block">{t('cronExpression')}</span>
<input
type="text"
value={cronForm.expr}
onChange={(e) => setCronForm({ ...cronForm, expr: e.target.value })}
placeholder="*/5 * * * *"
className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 transition-colors"
>
<option value="cron">Cron</option>
<option value="every">Every</option>
<option value="once">Once</option>
</select>
</label>
<label className="block">
{cronForm.kind === 'cron' ? (
<>
<span className="text-sm font-medium text-zinc-400 mb-1.5 block">{t('cronExpression')}</span>
<input
type="text"
value={cronForm.expr}
onChange={(e) => setCronForm({...cronForm, expr: e.target.value})}
placeholder="*/5 * * * *"
className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 transition-colors"
/>
</>
) : (
<>
<span className="text-sm font-medium text-zinc-400 mb-1.5 block">{t('everyMs')}</span>
<input
type="number"
value={cronForm.everyMs}
onChange={(e) => setCronForm({...cronForm, everyMs: Number(e.target.value)})}
className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 transition-colors"
/>
</>
)}
/>
</label>
</div>
<label className="block">
<span className="text-sm font-medium text-zinc-400 mb-1.5 block">{t('message')}</span>
<textarea
value={cronForm.message}
onChange={(e) => setCronForm({...cronForm, message: e.target.value})}
<textarea
value={cronForm.message}
onChange={(e) => setCronForm({ ...cronForm, message: e.target.value })}
rows={3}
className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 transition-colors resize-none"
className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 transition-colors resize-none"
/>
</label>
<div className="grid grid-cols-2 gap-4">
<label className="block">
<span className="text-sm font-medium text-zinc-400 mb-1.5 block">{t('channel')}</span>
<input
type="text"
value={cronForm.channel}
onChange={(e) => setCronForm({...cronForm, channel: e.target.value})}
className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 transition-colors"
<input
type="text"
value={cronForm.channel}
onChange={(e) => setCronForm({ ...cronForm, channel: e.target.value })}
className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 transition-colors"
/>
</label>
<label className="block">
<span className="text-sm font-medium text-zinc-400 mb-1.5 block">{t('to')}</span>
<input
type="text"
value={cronForm.to}
onChange={(e) => setCronForm({...cronForm, to: e.target.value})}
className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 transition-colors"
<input
type="text"
value={cronForm.to}
onChange={(e) => setCronForm({ ...cronForm, to: e.target.value })}
className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 transition-colors"
/>
</label>
</div>
<div className="flex items-center gap-6 pt-2">
<label className="flex items-center gap-3 cursor-pointer group">
<input
type="checkbox"
checked={cronForm.deliver}
onChange={(e) => setCronForm({...cronForm, deliver: e.target.checked})}
className="w-4 h-4 rounded border-zinc-700 text-indigo-500 focus:ring-indigo-500 focus:ring-offset-zinc-900 bg-zinc-950"
<input
type="checkbox"
checked={cronForm.deliver}
onChange={(e) => setCronForm({ ...cronForm, deliver: e.target.checked })}
className="w-4 h-4 rounded border-zinc-700 text-indigo-500 focus:ring-indigo-500 focus:ring-offset-zinc-900 bg-zinc-950"
/>
<span className="text-sm font-medium text-zinc-400 group-hover:text-zinc-200 transition-colors">{t('deliver')}</span>
</label>
<label className="flex items-center gap-3 cursor-pointer group">
<input
type="checkbox"
checked={cronForm.enabled}
onChange={(e) => setCronForm({...cronForm, enabled: e.target.checked})}
className="w-4 h-4 rounded border-zinc-700 text-indigo-500 focus:ring-indigo-500 focus:ring-offset-zinc-900 bg-zinc-950"
<input
type="checkbox"
checked={cronForm.enabled}
onChange={(e) => setCronForm({ ...cronForm, enabled: e.target.checked })}
className="w-4 h-4 rounded border-zinc-700 text-indigo-500 focus:ring-indigo-500 focus:ring-offset-zinc-900 bg-zinc-950"
/>
<span className="text-sm font-medium text-zinc-400 group-hover:text-zinc-200 transition-colors">{t('active')}</span>
</label>
@@ -300,13 +264,13 @@ const Cron: React.FC = () => {
</div>
<div className="p-6 border-t border-zinc-800 bg-zinc-900/50 flex items-center justify-end gap-3">
<button
<button
onClick={() => setIsCronModalOpen(false)}
className="px-4 py-2 text-sm font-medium text-zinc-400 hover:text-zinc-200 transition-colors"
>
{t('cancel')}
</button>
<button
<button
onClick={handleCronSubmit}
className="px-6 py-2 bg-indigo-600 hover:bg-indigo-500 text-white rounded-xl text-sm font-medium transition-all shadow-lg shadow-indigo-600/20"
>

View File

@@ -5,8 +5,6 @@ export type CronJob = {
id: string;
name: string;
enabled: boolean;
kind?: string;
everyMs?: number;
expr?: string;
message?: string;
deliver?: boolean;