Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs/API-SURFACE.md
Original file line number Diff line number Diff line change
Expand Up @@ -598,7 +598,9 @@ Both require view.
`reason`; upsert includes `name`, `script_id`, `script_sha256`, `args`, explicit
`targets`, `cron`, and `enabled`. `catch_up` must be false.
Preview and apply return a `ScheduleResult` object with `schedule`,
`preview_digest`, and `replayed`.
`preview_digest`, `replayed`, and `upcoming_runs`: the next five run times in UTC,
computed in the schedule's `tz`, starting at `schedule.next_run_at`. A disabled
schedule returns `[]`. A replayed apply returns the runs recorded with the receipt.
`POST /v1/operator/schedule-jobs/{id}/cancel` requires admin (or an allowlisted
`operator-admin` service token), `Idempotency-Key`, and `{"reason":"..."}`. It
cancels one scheduled job only while it is `not_started` and has never been
Expand Down
2 changes: 1 addition & 1 deletion docs/FEATURE-INVENTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,7 @@ resolver 在 `cmd/clawctl-hub/verifier_api.go`。
| 252 | `POST /v1/operator/script-runs` | JSON | Mutation | Matching preview digest, idempotency key; atomic catalog job fanout and audit |
| 253 | `GET /v1/operator/schedules` | JSON | Read | `view`; bounded schedule list with revision, next run, pause reason and last jobs |
| 254 | `GET /v1/operator/schedules/{id}` | JSON | Read | `view`; stored schedule configuration and run metadata |
| 255 | `POST /v1/operator/schedules/{operation}/{phase}` | JSON | Preview / Mutation | `operate` for read scripts, `admin` for write scripts; `upsert` / `set-enabled`, `preview` / `apply`; apply binds preview digest, expected revision and idempotency key |
| 255 | `POST /v1/operator/schedules/{operation}/{phase}` | JSON | Preview / Mutation | `operate` for read scripts, `admin` for write scripts; `upsert` / `set-enabled`, `preview` / `apply`; apply binds preview digest, expected revision and idempotency key; returns the next five runs |
| 256 | `POST /v1/operator/schedules/{id}/run-now` | JSON | Mutation | `operate` for read scripts, `admin` for write scripts; required Idempotency-Key, saved job-ID replay, approved hash and overlap guard |
| 257 | `GET /v1/operator/jobs-summary` | JSON | 讀取 | `view`; bounded supervision counts, latency and Hub threshold flags |
| 258 | `GET /v1/operator/approvals-summary` | JSON | 讀取 | `view`; observed approvals; disk_ops ledger counts/oldest pending age; legacy unpersisted preview metrics remain null |
Expand Down
21 changes: 21 additions & 0 deletions internal/operatorclient/schedules.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"github.com/teddashh/AI-Intune/internal/store"
"net/http"
"net/url"
"time"
)

func (c *Client) ScheduleRead(ctx context.Context, id string) (any, error) {
Expand Down Expand Up @@ -68,6 +69,9 @@ func (c *Client) ScheduleManage(ctx context.Context, body store.ScheduleRequest,
if e == nil && (!validSHA256Digest(out.PreviewDigest) || out.Replayed != replayed || (apply && out.PreviewDigest != body.PreviewDigest)) {
e = errors.New("schedule receipt mismatch")
}
if e == nil && !validScheduleUpcomingRuns(out) {
e = errors.New("schedule upcoming runs mismatch")
}
return out, e
}
func (c *Client) ScheduleJobCancel(ctx context.Context, jobID, reason, key string) (any, error) {
Expand Down Expand Up @@ -120,3 +124,20 @@ func (c *Client) ScheduleRunNow(ctx context.Context, id, key string) (any, error
}
return out, e
}

// validScheduleUpcomingRuns accepts runs only when they are UTC, strictly
// increasing, bounded, and start at next_run_at. A disabled schedule lists
// none. An empty list is also what a receipt recorded before this field
// replays as.
func validScheduleUpcomingRuns(out store.ScheduleResult) bool {
runs := out.UpcomingRuns
if runs == nil || len(runs) > store.ScheduleUpcomingRuns || (!out.Schedule.Enabled && len(runs) != 0) {
return false
}
for i, run := range runs {
if run.IsZero() || run.Location() != time.UTC || (i > 0 && !run.After(runs[i-1])) {
return false
}
}
return len(runs) == 0 || runs[0].Equal(out.Schedule.NextRunAt)
}
29 changes: 27 additions & 2 deletions internal/operatorclient/schedules_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"net/url"
"strings"
"testing"
"time"

"github.com/teddashh/AI-Intune/internal/store"
)
Expand Down Expand Up @@ -52,13 +53,13 @@ func testScheduleClient(t *testing.T, makeClient func(http.HandlerFunc) *Client)
if r.Header.Get("Idempotency-Key") != "" {
t.Error("preview idempotency")
}
json.NewEncoder(w).Encode(store.ScheduleResult{PreviewDigest: digest, Schedule: schedule})
json.NewEncoder(w).Encode(store.ScheduleResult{PreviewDigest: digest, Schedule: schedule, UpcomingRuns: []time.Time{}})
case strings.HasSuffix(r.URL.Path, "/apply"):
if r.Header.Get("Idempotency-Key") != "schedule-key" {
t.Error("apply key")
}
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(store.ScheduleResult{PreviewDigest: digest, Schedule: schedule})
json.NewEncoder(w).Encode(store.ScheduleResult{PreviewDigest: digest, Schedule: schedule, UpcomingRuns: []time.Time{}})
case r.URL.Path == "/v1/operator/schedules/s-1/run-now":
key := r.Header.Get("Idempotency-Key")
if key == "" {
Expand Down Expand Up @@ -129,3 +130,27 @@ func TestScheduleListEnvelopeIsStrict(t *testing.T) {
}
}
}

func TestScheduleClientRejectsInconsistentUpcomingRuns(t *testing.T) {
next := time.Date(2026, 11, 23, 0, 0, 0, 0, time.UTC)
enabled := store.Schedule{Enabled: true, NextRunAt: next}
taipei := time.FixedZone("Asia/Taipei", 8*60*60)
for _, test := range []struct {
name string
out store.ScheduleResult
ok bool
}{
{"enabled", store.ScheduleResult{Schedule: enabled, UpcomingRuns: []time.Time{next, next.AddDate(0, 0, 1)}}, true},
{"disabled none", store.ScheduleResult{UpcomingRuns: []time.Time{}}, true},
{"null", store.ScheduleResult{Schedule: enabled}, false},
{"disabled with runs", store.ScheduleResult{UpcomingRuns: []time.Time{next}}, false},
{"not next_run_at", store.ScheduleResult{Schedule: enabled, UpcomingRuns: []time.Time{next.Add(time.Hour)}}, false},
{"not increasing", store.ScheduleResult{Schedule: enabled, UpcomingRuns: []time.Time{next, next}}, false},
{"not utc", store.ScheduleResult{Schedule: enabled, UpcomingRuns: []time.Time{next.In(taipei)}}, false},
{"too many", store.ScheduleResult{Schedule: enabled, UpcomingRuns: []time.Time{next, next.Add(1), next.Add(2), next.Add(3), next.Add(4), next.Add(5)}}, false},
} {
if got := validScheduleUpcomingRuns(test.out); got != test.ok {
t.Errorf("%s: valid=%t want %t", test.name, got, test.ok)
}
}
}
34 changes: 30 additions & 4 deletions internal/store/schedules.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,16 @@ type ScheduleRequest struct {
type ScheduleResult struct {
Schedule Schedule `json:"schedule"`
PreviewDigest string `json:"preview_digest"`
JobIDs []string `json:"job_ids,omitempty"`
Replayed bool `json:"replayed"`
// UpcomingRuns are the next ScheduleUpcomingRuns slots, in UTC, computed at
// the Hub evaluation time. Empty when the schedule is disabled.
UpcomingRuns []time.Time `json:"upcoming_runs"`
JobIDs []string `json:"job_ids,omitempty"`
Replayed bool `json:"replayed"`
}

// ScheduleUpcomingRuns is how many future slots a schedule preview lists.
const ScheduleUpcomingRuns = 5

const scheduleColumns = `id,name,script_id,script_sha256,args,targets,cron,enabled,catch_up,created_by,created_at,updated_at,revision,last_run_at,last_job_ids,next_run_at,paused_reason,execution_mode,tz`

func scanSchedule(row jobReadScanner) (v Schedule, err error) {
Expand Down Expand Up @@ -165,6 +171,9 @@ func (s *Store) ScheduleManage(req ScheduleRequest, operation string, apply bool
if err = json.Unmarshal([]byte(response), &out); err != nil {
return
}
if out.UpcomingRuns == nil {
out.UpcomingRuns = []time.Time{} // receipt recorded before upcoming runs existed
}
if entry, ok := scriptcatalog.Lookup(out.Schedule.ScriptID); !ok {
return out, scriptBad("unknown script")
} else if e := scheduleScope(entry, a); e != nil {
Expand Down Expand Up @@ -302,13 +311,17 @@ func (s *Store) ScheduleManage(req ScheduleRequest, operation string, apply bool
if v.LastJobIDs == nil {
v.LastJobIDs = []string{}
}
cron, cronErr := schedulecron.Parse(v.Cron)
if cronErr != nil {
return out, scriptBad(cronErr.Error())
}
v.NextRunAt = scheduleNext(cron, a.At, v.TZ)
out.UpcomingRuns = scheduleUpcoming(cron, a.At, v.TZ, v.Enabled)
out.Schedule = v
if apply {
if req.PreviewDigest != out.PreviewDigest {
return out, scriptBad("preview digest mismatch")
}
cron, _ := schedulecron.Parse(v.Cron)
v.NextRunAt = scheduleNext(cron, a.At, v.TZ)
v.UpdatedAt = a.At
v.Revision++
if v.ID == "" {
Expand Down Expand Up @@ -790,6 +803,19 @@ func scheduleStaleNotStartedCutoff(v Schedule, now time.Time) time.Time {
return now.Add(-interval - scheduleStaleGrace)
}

// scheduleUpcoming lists the next ScheduleUpcomingRuns slots after the given
// time. A disabled schedule has none.
func scheduleUpcoming(c *schedulecron.Cron, after time.Time, tz string, enabled bool) []time.Time {
runs := make([]time.Time, 0, ScheduleUpcomingRuns)
for next := after; enabled && len(runs) < ScheduleUpcomingRuns; {
if next = scheduleNext(c, next, tz); next.IsZero() {
break
}
runs = append(runs, next)
}
return runs
}

func scheduleNext(c *schedulecron.Cron, after time.Time, tz string) time.Time {
loc, err := time.LoadLocation(tz)
if err != nil {
Expand Down
49 changes: 49 additions & 0 deletions internal/store/schedules_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -995,3 +995,52 @@ func TestScheduleJobCancelRefusesClaimedJob(t *testing.T) {
t.Fatal("leased not_started job cancelled")
}
}

// A cron that fires every five minutes of one hour and one that fires once at
// the top of that hour share the same next run; only the following runs tell
// them apart.
func TestSchedulePreviewListsUpcomingRunsInTheScheduleTimezone(t *testing.T) {
s, r, a, _ := scriptFixture(t)
at := time.Date(2026, 11, 20, 23, 30, 0, 0, time.UTC) // 2026-11-21 07:30 Asia/Taipei, Saturday
s.nowFn = func() time.Time { return at }
req := ScheduleRequest{Name: "morning-check", ScriptID: r.ScriptID, ScriptSHA256: r.ScriptSHA256, Args: r.Args,
Targets: r.Targets, Cron: "*/5 8 * * *", TZ: "Asia/Taipei", Enabled: true, Reason: r.Reason}
everyFive, err := s.ScheduleManage(req, "upsert", false, "", a)
if err != nil {
t.Fatal(err)
}
first := time.Date(2026, 11, 21, 0, 0, 0, 0, time.UTC)
want := []time.Time{first, first.Add(5 * time.Minute), first.Add(10 * time.Minute), first.Add(15 * time.Minute), first.Add(20 * time.Minute)}
if fmt.Sprint(everyFive.UpcomingRuns) != fmt.Sprint(want) || !everyFive.Schedule.NextRunAt.Equal(first) {
t.Fatalf("every five minutes: next=%s runs=%v", everyFive.Schedule.NextRunAt, everyFive.UpcomingRuns)
}

req.Cron = "0 8 * * 1-5"
weekdays, err := s.ScheduleManage(req, "upsert", false, "", a)
if err != nil {
t.Fatal(err)
}
monday := time.Date(2026, 11, 23, 0, 0, 0, 0, time.UTC)
want = []time.Time{monday, monday.AddDate(0, 0, 1), monday.AddDate(0, 0, 2), monday.AddDate(0, 0, 3), monday.AddDate(0, 0, 4)}
if fmt.Sprint(weekdays.UpcomingRuns) != fmt.Sprint(want) || !weekdays.Schedule.NextRunAt.Equal(monday) {
t.Fatalf("weekdays: next=%s runs=%v", weekdays.Schedule.NextRunAt, weekdays.UpcomingRuns)
}

req.PreviewDigest = weekdays.PreviewDigest
applied, err := s.ScheduleManage(req, "upsert", true, "upcoming-apply", a)
if err != nil || fmt.Sprint(applied.UpcomingRuns) != fmt.Sprint(want) {
t.Fatalf("apply runs=%v err=%v", applied.UpcomingRuns, err)
}
if _, err = s.DB().Exec(`UPDATE operator_idempotency SET response_json=json_remove(response_json,'$.upcoming_runs') WHERE idempotency_key=?`, "upcoming-apply"); err != nil {
t.Fatal(err)
}
legacy, err := s.ScheduleManage(req, "upsert", true, "upcoming-apply", a)
if err != nil || !legacy.Replayed || legacy.UpcomingRuns == nil || len(legacy.UpcomingRuns) != 0 {
t.Fatalf("legacy receipt replay runs=%v replayed=%t err=%v", legacy.UpcomingRuns, legacy.Replayed, err)
}
disable := ScheduleRequest{ID: applied.Schedule.ID, ExpectedRevision: applied.Schedule.Revision, Enabled: false, Reason: "pause"}
disabled, err := s.ScheduleManage(disable, "set-enabled", false, "", a)
if err != nil || disabled.UpcomingRuns == nil || len(disabled.UpcomingRuns) != 0 {
t.Fatalf("disabled runs=%v err=%v", disabled.UpcomingRuns, err)
}
}
11 changes: 5 additions & 6 deletions internal/web/schedules.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import (

"github.com/teddashh/AI-Intune/internal/operator"
"github.com/teddashh/AI-Intune/internal/operatorauth"
"github.com/teddashh/AI-Intune/internal/schedulecron"
"github.com/teddashh/AI-Intune/internal/scriptcatalog"
"github.com/teddashh/AI-Intune/internal/store"
)
Expand Down Expand Up @@ -342,11 +341,11 @@ func (s *Server) schedulePreview(w http.ResponseWriter, r *http.Request) {
raw, _ := json.Marshal(req)
canonical, _ := json.MarshalIndent(out.Schedule, "", " ")
v := &schedulePage{Confirm: true, Body: string(raw), Canonical: string(canonical), Operation: op, Digest: out.PreviewDigest, Key: key, Edit: req}
cron, _ := schedulecron.Parse(out.Schedule.Cron)
loc, _ := time.LoadLocation(out.Schedule.TZ)
next := time.Now().UTC()
for i := 0; i < 3; i++ {
next = cron.NextIn(next, loc)
loc, err := time.LoadLocation(out.Schedule.TZ)
if err != nil {
loc = time.UTC
}
for _, next := range out.UpcomingRuns {
v.Times = append(v.Times, next.In(loc).Format("2006-01-02 15:04 MST")+" · "+next.Format(time.RFC3339))
}
s.scheduleRender(w, r, "schedule_preview.html", v)
Expand Down
25 changes: 24 additions & 1 deletion internal/web/schedules_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func TestScheduleWebPreviewApplyAndRunNow(t *testing.T) {
}
p := scheduleWebPrincipal()
w := diskWebRequest(t, s, "POST", schedulesBack+"/preview", scheduleTestForm(machine), p, false)
if w.Code != 200 || !strings.Contains(w.Body.String(), "</html>") || !strings.Contains(w.Body.String(), "Next 3 runs") {
if w.Code != 200 || !strings.Contains(w.Body.String(), "</html>") || !strings.Contains(w.Body.String(), "Upcoming runs") {
t.Fatal(w.Code, w.Body.String())
}
apply := diskWebHidden(t, w.Body.String(), "request", "operation", "preview_digest", "idempotency_key", "expected_revision", "confirm")
Expand Down Expand Up @@ -248,3 +248,26 @@ func TestScheduleWebSwitchFleetProbeV2(t *testing.T) {
}
}
}

func TestSchedulePreviewPageListsTheStoresUpcomingRuns(t *testing.T) {
s, st := newServer(t)
machine := onlineMachine(t, st, "Probe machine")
enabled := true
now := time.Now().UTC()
if err := st.RecordCheckin(machine, model.Checkin{SchemaVersion: model.SchemaVersion, SentAt: now, JobsEnabled: &enabled, ScriptV1: true}, now); err != nil {
t.Fatal(err)
}
p := scheduleWebPrincipal()
w := diskWebRequest(t, s, "POST", schedulesBack+"/preview", scheduleTestForm(machine), p, false)
body := w.Body.String()
if w.Code != 200 || strings.Count(body, "EST · ")+strings.Count(body, "EDT · ") != store.ScheduleUpcomingRuns || strings.Contains(body, "Disabled · 不會執行") {
t.Fatal(w.Code, body)
}
form := scheduleTestForm(machine)
form.Set("enabled", "false")
w = diskWebRequest(t, s, "POST", schedulesBack+"/preview", form, p, false)
body = w.Body.String()
if w.Code != 200 || !strings.Contains(body, "Disabled · 不會執行") || strings.Contains(body, "EST · ") || strings.Contains(body, "EDT · ") {
t.Fatal(w.Code, body)
}
}
2 changes: 1 addition & 1 deletion internal/web/templates/schedule_preview.html
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{{define "schedule_preview.html"}}{{template "head" .}}{{$v := .Schedules}}
<div class="page-heading"><div><h1>{{if $v.RunNow}}Run now · 確認立即執行{{else}}Review schedule · 確認排程{{end}}</h1><p>{{if $v.RunNow}}執行 {{$v.Edit.Name}}。確認時重新檢查 catalog、安全條件與權限。{{else}}檢查完整正規化定義與 digest,再確認套用。{{end}}</p></div></div>
<div class="panel">{{if not $v.RunNow}}<h2>Normalized definition</h2><pre class="copy">{{$v.Canonical}}</pre><p class="mono small" style="overflow-wrap:anywhere">{{$v.Digest}}</p><h2>Next 3 runs · 時區 / UTC</h2><ul>{{range $v.Times}}<li>{{.}}</li>{{end}}</ul><p>Reason:{{$v.Edit.Reason}}</p>{{end}}
<div class="panel">{{if not $v.RunNow}}<h2>Normalized definition</h2><pre class="copy">{{$v.Canonical}}</pre><p class="mono small" style="overflow-wrap:anywhere">{{$v.Digest}}</p><h2>Upcoming runs · 時區 / UTC</h2>{{if $v.Times}}<ul>{{range $v.Times}}<li>{{.}}</li>{{end}}</ul>{{else}}<p>Disabled · 不會執行</p>{{end}}<p>Reason:{{$v.Edit.Reason}}</p>{{end}}
<form class="disk-form" method="post" action="{{if $v.RunNow}}/tenant/schedules/{{$v.Edit.ID}}/run-now{{else}}/tenant/schedules/apply{{end}}">
<input type="hidden" name="idempotency_key" value="{{$v.Key}}"><input type="hidden" name="confirm" value="yes">
{{if not $v.RunNow}}<input type="hidden" name="request" value="{{$v.Body}}"><input type="hidden" name="operation" value="{{$v.Operation}}"><input type="hidden" name="preview_digest" value="{{$v.Digest}}"><input type="hidden" name="expected_revision" value="{{$v.Edit.ExpectedRevision}}">{{end}}
Expand Down
Loading