From 475bb51afabdfca144fd79a63964fdca1c827111 Mon Sep 17 00:00:00 2001 From: Samarth Rajesh Lad <142334685+samyyy2311@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:58:37 +0530 Subject: [PATCH 1/2] routines: set retryAt when holding a queued interval run outside its window When a scheduled interval run with a window or weekday restriction is held because the current time is outside its allowed window or before the next aligned occurrence, set run.retryAt to the next allowed occurrence so hasActiveRuns(), wakeHold(), and schedulerDueOf() do not keep Cloud or desktop awake or spin the scheduler every 10 seconds. Clear that parked retryAt if the routine's schedule is edited so a wider window dispatches promptly. --- server/routines.test.ts | 56 ++++++++++++++++++++++++++++++++++++++--- server/routines.ts | 33 +++++++++++++++++++----- 2 files changed, 79 insertions(+), 10 deletions(-) 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..c0a06b3772 100644 --- a/server/routines.ts +++ b/server/routines.ts @@ -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); } @@ -1077,21 +1084,35 @@ export class RoutineManager { : undefined; if (definition?.schedule.type === "interval") { const latest = latestIntervalOccurrence(definition.schedule, now); + let changed = false; if (latest !== null && latest > run.scheduledFor) { run.scheduledFor = latest; - this.saveLater(); - this.emitRun(run); + changed = true; } 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) { + const next = nextOccurrence(definition.schedule, now); + if (next === null) { this.failRun(run, "The routine ended before this scheduled run could start", "missed", undefined, "missed"); + continue; + } + if (run.retryAt !== next) { + run.retryAt = next; + changed = true; + } + if (changed) { + this.saveLater(); + this.emitRun(run); } continue; } + if (changed) { + this.saveLater(); + this.emitRun(run); + } } const checked = triggerSource === "webhook" || run.checkKey ? undefined : this.routines.find((routine) => routine.id === run.routineId && routine.checks); if (checked) { From 4586d5e0cb0ba45adc4dfe4054e09f9b11e838e2 Mon Sep 17 00:00:00 2001 From: Samarth Rajesh Lad <142334685+samyyy2311@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:56:00 +0530 Subject: [PATCH 2/2] routines: move interval dispatch decision into routine-schedules --- server/routine-schedules.ts | 17 +++++++++++++++- server/routines.ts | 39 ++++++++----------------------------- 2 files changed, 24 insertions(+), 32 deletions(-) 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.ts b/server/routines.ts index c0a06b3772..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, @@ -1083,36 +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); + const decision = intervalDispatch(definition.schedule, now); let changed = false; - if (latest !== null && latest > run.scheduledFor) { - run.scheduledFor = latest; - changed = true; - } - const requiresCurrentDayOccurrence = - definition.schedule.weekdays !== undefined || definition.schedule.window !== undefined; - const mayDispatch = intervalAllowsOccurrence(definition.schedule, now) && - (!requiresCurrentDayOccurrence || (latest !== null && isSameLocalDay(latest, now))); - if (!mayDispatch) { - const next = nextOccurrence(definition.schedule, now); - if (next === null) { - this.failRun(run, "The routine ended before this scheduled run could start", "missed", undefined, "missed"); - continue; - } - if (run.retryAt !== next) { - run.retryAt = next; - changed = true; - } - if (changed) { - this.saveLater(); - this.emitRun(run); - } - continue; - } - if (changed) { - this.saveLater(); - this.emitRun(run); - } + 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) {