diff --git a/server/routine-schedules.ts b/server/routine-schedules.ts index 2ae7cb5795..d228d3db1e 100644 --- a/server/routine-schedules.ts +++ b/server/routine-schedules.ts @@ -2,7 +2,7 @@ import { AFTER_RESET_MS, type LimitResetSchedule, type LimitResetScheduleInput } from "../shared/limit-reset.ts"; import { normalizeCronSchedule, nextCronRuns, type RoutineCronSchedule } from "../shared/routine-schedule.ts"; import type { RoutineIntervalWindow } from "../shared/routines.ts"; -import { clockMinutes, INTERVAL_RESTRICTION_SEARCH_MS, intervalAllowsOccurrence, intervalHasRestrictions, MAX_DATE_MS, nextAlignedInterval } from "./routine-intervals.ts"; +import { clockMinutes, INTERVAL_RESTRICTION_SEARCH_MS, intervalAllowsOccurrence, intervalHasRestrictions, isSameLocalDay, latestIntervalOccurrence, MAX_DATE_MS, nextAlignedInterval } from "./routine-intervals.ts"; export interface RoutineIntervalSchedule { type: "interval"; @@ -249,3 +249,18 @@ export function limitResetOccurrence(resetsAt: number | null, lastRunFor?: numbe const at = resetsAt + AFTER_RESET_MS; return lastRunFor !== undefined && at <= lastRunFor ? null : at; } + +export type IntervalDispatch = + | { kind: "dispatch"; latest: number | null } + | { kind: "wait"; latest: number | null; retryAt: number } + | { kind: "ended"; latest: number | null }; + +export function intervalDispatch(schedule: RoutineIntervalSchedule, now: number): IntervalDispatch { + const latest = latestIntervalOccurrence(schedule, now); + const restricted = schedule.weekdays !== undefined || schedule.window !== undefined; + if (intervalAllowsOccurrence(schedule, now) && (!restricted || (latest !== null && isSameLocalDay(latest, now)))) { + return { kind: "dispatch", latest }; + } + const retryAt = nextOccurrence(schedule, now); + return retryAt === null ? { kind: "ended", latest } : { kind: "wait", latest, retryAt }; +} diff --git a/server/routines.test.ts b/server/routines.test.ts index a0da2b9add..6728d86421 100644 --- a/server/routines.test.ts +++ b/server/routines.test.ts @@ -2270,13 +2270,17 @@ describe("RoutineManager", () => { await h.manager.tick(); expect(h.manager.listRuns()[0]).toMatchObject({ status: "queued" }); - h.setNow(new Date(2026, 7, 17, 11, 0, 0).getTime()); + const mondayAtEleven = new Date(2026, 7, 17, 11, 0, 0).getTime(); + const nextMondayAtNine = new Date(2026, 7, 24, 9, 0, 0).getTime(); + h.setNow(mondayAtEleven); h.setBot("ready"); await h.manager.tick(); expect(h.started).toHaveLength(0); - expect(h.manager.listRuns()[0]).toMatchObject({ status: "queued" }); + expect(h.manager.listRuns()[0]).toMatchObject({ status: "queued", retryAt: nextMondayAtNine }); + expect(h.manager.hasActiveRuns()).toBe(false); + expect(h.manager.wakeHold()).toEqual({ hold: false }); + expect(schedulerDueOf(h.manager.listRoutines(), h.manager.listRuns(), mondayAtEleven, 0)).toBe(nextMondayAtNine); - const nextMondayAtNine = new Date(2026, 7, 24, 9, 0, 0).getTime(); h.setNow(nextMondayAtNine); await h.manager.tick(); expect(h.started).toEqual([{ @@ -2315,6 +2319,7 @@ describe("RoutineManager", () => { scheduledFor: firstMondayAtTenOhFive, }); + const nextMondayAtNineOhFive = new Date(2026, 7, 24, 9, 5, 0).getTime(); h.setBot("ready"); h.setNow(new Date(2026, 7, 24, 9, 1, 0).getTime()); await h.manager.tick(); @@ -2322,9 +2327,10 @@ describe("RoutineManager", () => { expect(h.manager.listRuns()[0]).toMatchObject({ status: "queued", scheduledFor: firstMondayAtTenOhFive, + retryAt: nextMondayAtNineOhFive, }); + expect(h.manager.hasActiveRuns()).toBe(false); - const nextMondayAtNineOhFive = new Date(2026, 7, 24, 9, 5, 0).getTime(); h.setNow(nextMondayAtNineOhFive); await h.manager.tick(); expect(h.started).toEqual([{ @@ -2338,6 +2344,48 @@ describe("RoutineManager", () => { }); }); + it("releases a window-held queued interval run when the schedule is widened", async () => { + const mondayAtEight = new Date(2026, 7, 17, 8, 0, 0).getTime(); + const h = harness(mondayAtEight); + h.setBot("busy"); + const routine = h.manager.create({ + name: "Business-hours check", + prompt: "Check at an allowed time", + botId: "maus-interval", + schedule: { + type: "interval", + everyMinutes: 30, + anchorAt: mondayAtEight, + weekdays: [1], + window: { start: "09:00", end: "10:30" }, + }, + }); + + h.setNow(new Date(2026, 7, 17, 10, 0, 0).getTime()); + await h.manager.tick(); + + const mondayAtEleven = new Date(2026, 7, 17, 11, 0, 0).getTime(); + const nextMondayAtNine = new Date(2026, 7, 24, 9, 0, 0).getTime(); + h.setNow(mondayAtEleven); + h.setBot("ready"); + await h.manager.tick(); + expect(h.manager.listRuns()[0]).toMatchObject({ + status: "queued", + retryAt: nextMondayAtNine, + }); + + h.manager.update(routine.id, { + schedule: { type: "interval", everyMinutes: 30, window: { start: "09:00", end: "18:00" } }, + }); + expect(h.manager.listRuns()[0].retryAt).toBeUndefined(); + + await h.manager.tick(); + expect(h.manager.listRuns()[0]).toMatchObject({ + status: "running", + scheduledFor: mondayAtEleven, + }); + }); + it("disables an exhausted interval and marks its still-queued final run missed", async () => { const start = new Date(2026, 7, 17, 8, 0, 0).getTime(); const finalOccurrence = start + 5 * 60_000; diff --git a/server/routines.ts b/server/routines.ts index c82a187c1e..3e3902f945 100644 --- a/server/routines.ts +++ b/server/routines.ts @@ -10,8 +10,8 @@ import { withoutEchoedPrompt } from "../shared/failed-turn.ts"; import type { Ro import { activeRunsOf, catchUpMsOf, enabledHereOf, missedError, nextDueOf, schedulerDueOf, upcomingOf, wakeHoldOf } from "./routine-due.ts"; import { dropQuietFields, nextTicks, quietPatch, stripOf } from "./routine-quiet.ts"; import { startDueTimer, type DueTimer } from "./due-timer.ts"; import type { GroupGoalRunStatus } from "../shared/group-goal-run.ts"; -import { intervalAllowsOccurrence, intervalHasRestrictions, isSameLocalDay, latestIntervalOccurrence } from "./routine-intervals.ts"; -import { initialOccurrence, limitResetOccurrence, mergeScheduleUpdate, nextOccurrence, RoutineScheduleError, type RoutineSchedule, type RoutineScheduleInput } from "./routine-schedules.ts"; +import { intervalHasRestrictions, latestIntervalOccurrence } from "./routine-intervals.ts"; +import { initialOccurrence, intervalDispatch, limitResetOccurrence, mergeScheduleUpdate, nextOccurrence, RoutineScheduleError, type RoutineSchedule, type RoutineScheduleInput } from "./routine-schedules.ts"; import { runsOnce } from "../shared/limit-reset.ts"; import { isRoutineProblemRun, type RoutineQuietFields, type RoutineQuietInput, type RoutineAccess, type RoutineChain, type RoutineCheck, type RoutineContextAttachment, type RoutineDelivery, type RoutineIntervalWindow, type RoutineRetryCause, @@ -592,7 +592,7 @@ export class RoutineManager { const destination = { ...routine, ...clean }; if (destination.botId !== routine.botId) delete destination.resultsThreadId; const discardResults = this.applyResultsInput(destination, patch.resultsThreadId); - const cancelledRuns: RoutineRun[] = []; + const changedRuns: RoutineRun[] = []; this.commitMutation(() => { Object.assign(routine, clean, { resultsThreadId: destination.resultsThreadId, @@ -616,12 +616,19 @@ export class RoutineManager { run.attention = undefined; run.finishedAt = this.now(); run.error = "The routine was paused before this run started"; - cancelledRuns.push(run); + changedRuns.push(run); + } + } else if (scheduleChanged) { + for (const run of this.runs) { + if (run.routineId !== routine.id || run.status !== "queued" || run.retryAt === undefined) continue; + if ((run.triggerSource ?? (run.manual ? "manual" : "schedule")) !== "schedule" || run.retried || run.attention) continue; + delete run.retryAt; + changedRuns.push(run); } } if (request) this.rememberRoutineRequest(request, routine.id, now); }, discardResults); - for (const run of cancelledRuns) this.emitRun(run); + for (const run of changedRuns) this.emitRun(run); this.emitRoutine(routine); return this.routineWithHealth(routine); } @@ -1076,22 +1083,13 @@ export class RoutineManager { ? this.routines.find((routine) => routine.id === run.routineId) : undefined; if (definition?.schedule.type === "interval") { - const latest = latestIntervalOccurrence(definition.schedule, now); - if (latest !== null && latest > run.scheduledFor) { - run.scheduledFor = latest; - this.saveLater(); - this.emitRun(run); - } - const requiresCurrentDayOccurrence = - definition.schedule.weekdays !== undefined || definition.schedule.window !== undefined; - const mayDispatch = intervalAllowsOccurrence(definition.schedule, now) && - (!requiresCurrentDayOccurrence || (latest !== null && isSameLocalDay(latest, now))); - if (!mayDispatch) { - if (nextOccurrence(definition.schedule, now) === null) { - this.failRun(run, "The routine ended before this scheduled run could start", "missed", undefined, "missed"); - } - continue; - } + const decision = intervalDispatch(definition.schedule, now); + let changed = false; + if (decision.latest !== null && decision.latest > run.scheduledFor) { run.scheduledFor = decision.latest; changed = true; } + if (decision.kind === "ended") { this.failRun(run, "The routine ended before this scheduled run could start", "missed", undefined, "missed"); continue; } + if (decision.kind === "wait" && run.retryAt !== decision.retryAt) { run.retryAt = decision.retryAt; changed = true; } + if (changed) { this.saveLater(); this.emitRun(run); } + if (decision.kind === "wait") continue; } const checked = triggerSource === "webhook" || run.checkKey ? undefined : this.routines.find((routine) => routine.id === run.routineId && routine.checks); if (checked) {