Skip to content

Commit 7b3b96b

Browse files
pjmullerclaude
andcommitted
feat(scheduled-tasks): fixed-time tasks can run once when a missed time comes back
A fixed-time run more than 10 minutes late (environment off or asleep) is skipped until the next occurrence, so a weekly task can lose a whole week. Fixed-time schedules get an optional `missedRun: "skip" | "run_once"`. `run_once` runs the task once when the environment is back; several missed slots coalesce into one run because completion schedules from now. Absent keeps today's skip, and an upsert that omits the field keeps the stored value so older clients do not clear it. Web and mobile editors get a "Run once if missed" switch in the "At a time" mode; the MCP trigger text names the field. Refs #22204, #6748 Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent e5f2e5d commit 7b3b96b

13 files changed

Lines changed: 195 additions & 6 deletions

‎apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1047,6 +1047,18 @@ function TaskForm({
10471047
setDraft({ ...draft, schedule: { ...draft.schedule, weekdays } });
10481048
}}
10491049
/>
1050+
<View className="min-h-14 flex-row items-center gap-3 border-t border-border-subtle px-4 py-3">
1051+
<Text textRole="body" className="min-w-0 flex-1 text-foreground">
1052+
Run once if missed
1053+
</Text>
1054+
<ThemedSwitch
1055+
accessibilityLabel="Run once if missed"
1056+
value={draft.schedule.runMissedOnce}
1057+
onValueChange={(runMissedOnce) =>
1058+
setDraft({ ...draft, schedule: { ...draft.schedule, runMissedOnce } })
1059+
}
1060+
/>
1061+
</View>
10501062
</>
10511063
) : draft.schedule.mode === "webhook" ? (
10521064
<>
@@ -1153,7 +1165,8 @@ function TaskForm({
11531165
</SettingsSection>
11541166
{draft.schedule.mode === "fixed_time" ? (
11551167
<Text className="px-2 text-sm text-foreground-muted">
1156-
Time uses the environment's time zone, which may differ from your phone's.
1168+
Time uses the environment's time zone, which may differ from your phone's. Run once if
1169+
missed catches up when the environment was off or asleep at that time.
11571170
</Text>
11581171
) : null}
11591172
</View>

‎apps/mobile/src/features/settings/scheduledTaskDraft.test.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,17 @@ describe("scheduleFromDraft", () => {
8787
expect(scheduleFromDraft({ ...DEFAULT_SCHEDULE, weekdays: [] })).toBeNull();
8888
});
8989

90+
it("round-trips run once if missed and sends an explicit skip when it is off", () => {
91+
const draft = scheduleDraftForTask({
92+
schedule: { type: "fixed_time", timeOfDay: "07:30", weekdays: [1], missedRun: "run_once" },
93+
});
94+
expect(scheduleFromDraft(draft)).toMatchObject({ missedRun: "run_once" });
95+
// The server keeps a stored value when the field is omitted.
96+
expect(scheduleFromDraft({ ...draft, runMissedOnce: false })).toMatchObject({
97+
missedRun: "skip",
98+
});
99+
});
100+
90101
it.each([
91102
["1.5", 90_000],
92103
[String(60_001 / 60_000), 60_001],

‎apps/mobile/src/features/settings/scheduledTaskDraft.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ export type ScheduleDraft = {
5454
readonly mode: "fixed_time" | "interval" | "webhook";
5555
readonly timeOfDay: string;
5656
readonly weekdays: ReadonlyArray<number>;
57+
readonly runMissedOnce: boolean;
5758
readonly intervalMinutes: string;
5859
readonly signature: ScheduledTaskWebhookSignature | null;
5960
readonly maxDeliveryAgeMinutes: string;
@@ -69,6 +70,7 @@ export const DEFAULT_SCHEDULE: ScheduleDraft = {
6970
mode: "fixed_time",
7071
timeOfDay: "09:00",
7172
weekdays: [1, 2, 3, 4, 5],
73+
runMissedOnce: false,
7274
intervalMinutes: "15",
7375
signature: null,
7476
maxDeliveryAgeMinutes: "",
@@ -88,6 +90,7 @@ export function scheduleDraftForTask(task: Pick<ScheduledTask, "schedule">): Sch
8890
weekdays: task.schedule.weekdays?.length
8991
? [...new Set(task.schedule.weekdays)].sort((a, b) => a - b)
9092
: [0, 1, 2, 3, 4, 5, 6],
93+
runMissedOnce: task.schedule.missedRun === "run_once",
9194
};
9295
case "interval":
9396
return {
@@ -179,6 +182,7 @@ export function scheduleFromDraft(draft: ScheduleDraft): ScheduledTaskUpsertSche
179182
type: "fixed_time",
180183
timeOfDay: draft.timeOfDay,
181184
...(weekdays.length === 7 ? {} : { weekdays }),
185+
missedRun: draft.runMissedOnce ? "run_once" : "skip",
182186
};
183187
}
184188

‎apps/server/src/scheduledTasks/Schedule.test.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { describe, expect, it } from "@effect/vitest";
22
import * as DateTime from "effect/DateTime";
33

4-
import { isSameSchedule, nextScheduledRunAt } from "./Schedule.ts";
4+
import { isMissedFixedTimeRun, isSameSchedule, nextScheduledRunAt } from "./Schedule.ts";
55

66
describe("scheduled task schedule calculation", () => {
77
it("skips to the next matching fixed-time weekday", () => {
@@ -75,5 +75,22 @@ describe("scheduled task schedule calculation", () => {
7575
{ type: "fixed_time", timeOfDay: "09:00" },
7676
),
7777
).toBe(false);
78+
expect(
79+
isSameSchedule(
80+
{ type: "fixed_time", timeOfDay: "09:00", missedRun: "run_once" },
81+
{ type: "fixed_time", timeOfDay: "09:00" },
82+
),
83+
).toBe(true);
84+
});
85+
86+
it("skips late fixed-time runs unless the task runs missed times once", () => {
87+
const dueAt = DateTime.makeUnsafe("2026-07-01T09:00:00.000Z");
88+
const late = DateTime.makeUnsafe("2026-07-03T12:00:00.000Z");
89+
const onTime = DateTime.makeUnsafe("2026-07-01T09:05:00.000Z");
90+
const schedule = { type: "fixed_time", timeOfDay: "09:00" } as const;
91+
expect(isMissedFixedTimeRun(schedule, dueAt, late)).toBe(true);
92+
expect(isMissedFixedTimeRun({ ...schedule, missedRun: "skip" }, dueAt, late)).toBe(true);
93+
expect(isMissedFixedTimeRun(schedule, dueAt, onTime)).toBe(false);
94+
expect(isMissedFixedTimeRun({ ...schedule, missedRun: "run_once" }, dueAt, late)).toBe(false);
7895
});
7996
});

‎apps/server/src/scheduledTasks/Schedule.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,6 @@ export function isMissedFixedTimeRun(
6868
dueAt: DateTime.DateTime,
6969
now: DateTime.DateTime,
7070
): boolean {
71-
if (schedule.type !== "fixed_time") return false;
71+
if (schedule.type !== "fixed_time" || schedule.missedRun === "run_once") return false;
7272
return DateTime.toEpochMillis(now) - DateTime.toEpochMillis(dueAt) > MISSED_FIXED_TIME_GRACE_MS;
7373
}

‎apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,22 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
33
import { expect, it } from "@effect/vitest";
44
import { ScheduledTaskUpsertInput } from "@t3tools/contracts";
55
import * as DateTime from "effect/DateTime";
6+
import * as Deferred from "effect/Deferred";
67
import * as Effect from "effect/Effect";
8+
import * as Fiber from "effect/Fiber";
79
import * as Layer from "effect/Layer";
10+
import * as Option from "effect/Option";
11+
import * as Ref from "effect/Ref";
812
import * as Schema from "effect/Schema";
13+
import * as Stream from "effect/Stream";
914
import * as TestClock from "effect/testing/TestClock";
1015

1116
import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts";
1217
import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
1318
import * as SecretRequests from "../secrets/SecretRequests.ts";
1419
import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
1520
import * as SqlitePersistence from "../persistence/Sqlite.ts";
21+
import { ServerActivation } from "../serverActivation.ts";
1622
import * as ScheduledTaskService from "./ScheduledTaskService.ts";
1723

1824
const decodeUpsertInput = Schema.decodeUnknownEffect(ScheduledTaskUpsertInput);
@@ -167,3 +173,85 @@ it.effect("keeps the task list order when a toggle or edit rewrites updated_at",
167173
}).pipe(Effect.provide(ScheduledTaskService.layer.pipe(Layer.provide(layerDependencies))));
168174
}).pipe(Effect.provide(SqlitePersistence.layerMemory)),
169175
);
176+
177+
it.effect("runs a fixed-time slot missed during sleep once only when the task asks for it", () =>
178+
Effect.gen(function* () {
179+
const dueAt = DateTime.makeZonedUnsafe(
180+
{ year: 2026, month: 7, day: 1, hour: 7, minute: 30, second: 0, millisecond: 0 },
181+
{ timeZone: DateTime.zoneMakeLocal(), adjustForTimeZone: true },
182+
);
183+
const dueIso = DateTime.formatIso(DateTime.toUtc(dueAt));
184+
const nextWeekIso = DateTime.formatIso(DateTime.toUtc(DateTime.add(dueAt, { days: 7 })));
185+
yield* TestClock.setTime(DateTime.toEpochMillis(dueAt) - 1_000);
186+
187+
const launches = yield* Ref.make(0);
188+
const activate = yield* Deferred.make<void>();
189+
const layerDependencies = Layer.mergeAll(
190+
NodeCrypto.layer,
191+
Scheduler.layer,
192+
Layer.mock(ThreadLaunchService.ThreadLaunchService)({
193+
launch: () =>
194+
Ref.update(launches, (n) => n + 1).pipe(
195+
Effect.andThen(Effect.die("synthetic dispatch failure")),
196+
),
197+
}),
198+
Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
199+
namedProjectsRoot: "/projects",
200+
isScratchProject: () => Effect.succeed(false),
201+
}),
202+
Layer.mock(ThreadManagementService.ThreadManagementService)({}),
203+
Layer.mock(SecretRequests.SecretRequests)({}),
204+
);
205+
yield* Effect.gen(function* () {
206+
const service = yield* ScheduledTaskService.ScheduledTaskService;
207+
const save = (commandId: string, schedule: Record<string, unknown>) =>
208+
decodeUpsertInput({
209+
commandId,
210+
title: "Weekly review",
211+
prompt: "Review the open pull requests.",
212+
enabled: true,
213+
schedule: {
214+
type: "fixed_time",
215+
timeOfDay: "07:30",
216+
weekdays: [DateTime.toParts(dueAt).weekDay],
217+
...schedule,
218+
},
219+
projectId: "project-missed-run",
220+
workspaceStrategy: { type: "root" },
221+
modelSelection: { instanceId: "codex", model: "gpt-5.4" },
222+
runtimeMode: "full-access",
223+
interactionMode: "default",
224+
}).pipe(Effect.flatMap(service.upsert));
225+
226+
const catchUp = yield* save("catch-up", { missedRun: "run_once" });
227+
// A client that predates missedRun re-saves without it.
228+
const resaved = yield* save("catch-up", {});
229+
expect(resaved.task.schedule).toMatchObject({ missedRun: "run_once" });
230+
expect(resaved.task.nextRunAt).toBe(dueIso);
231+
yield* save("skip", { missedRun: "run_once" });
232+
const skipped = yield* save("skip", { missedRun: "skip" });
233+
expect(skipped.task.schedule).toMatchObject({ missedRun: "skip" });
234+
235+
// Asleep through the slot: the scheduler first polls two days later.
236+
yield* TestClock.setTime(DateTime.toEpochMillis(dueAt) + 2 * 24 * 60 * 60_000);
237+
const settled = yield* service.subscribeList().pipe(
238+
Stream.map(({ tasks }) => tasks),
239+
Stream.filter((tasks) =>
240+
tasks.every((task) => task.lastRunStatus !== "running" && task.nextRunAt !== dueIso),
241+
),
242+
Stream.runHead,
243+
Effect.forkChild,
244+
);
245+
yield* Deferred.succeed(activate, undefined);
246+
const tasks = Option.getOrThrow(yield* Fiber.join(settled));
247+
const byId = new Map(tasks.map((task) => [task.id, task]));
248+
249+
expect(yield* Ref.get(launches)).toBe(1);
250+
expect(byId.get(catchUp.task.id)).toMatchObject({ runCount: 1, nextRunAt: nextWeekIso });
251+
expect(byId.get(skipped.task.id)).toMatchObject({ runCount: 0, nextRunAt: nextWeekIso });
252+
}).pipe(
253+
Effect.provide(ScheduledTaskService.layer.pipe(Layer.provide(layerDependencies))),
254+
Effect.provideService(ServerActivation, Deferred.await(activate)),
255+
);
256+
}).pipe(Effect.provide(SqlitePersistence.layerMemory)),
257+
);

‎apps/server/src/scheduledTasks/ScheduledTaskService.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1090,7 +1090,14 @@ export const layer = Layer.effect(
10901090
: undefined),
10911091
),
10921092
}
1093-
: input.schedule;
1093+
: input.schedule.type === "fixed_time" &&
1094+
input.schedule.missedRun === undefined &&
1095+
existingTask?.schedule.type === "fixed_time" &&
1096+
existingTask.schedule.missedRun !== undefined
1097+
? // Omitted keeps the stored choice, so a client that predates missedRun
1098+
// can re-save a task without clearing it.
1099+
{ ...input.schedule, missedRun: existingTask.schedule.missedRun }
1100+
: input.schedule;
10941101
const webhook =
10951102
input.schedule.type === "webhook"
10961103
? yield* Effect.gen(function* () {

‎apps/web/src/components/settings/ScheduledTasksSettings.tsx‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,7 @@ const EMPTY_DRAFT: DraftState = {
139139
intervalMinutes: "15",
140140
timeOfDay: "09:00",
141141
weekdays: new Set([1, 2, 3, 4, 5]),
142+
runMissedOnce: false,
142143
projectId: "",
143144
threadId: "",
144145
workspaceMode: "worktree",
@@ -1752,6 +1753,28 @@ function ScheduledTaskEditorForm({
17521753
<span className="text-xs text-muted-foreground">minutes</span>
17531754
</div>
17541755
)}
1756+
{draft.scheduleMode === "fixed" ? (
1757+
<div className="flex items-center justify-between gap-4">
1758+
<div className="min-w-0 space-y-1">
1759+
<Label htmlFor="scheduled-task-missed-run">Run once if missed</Label>
1760+
<p
1761+
id="scheduled-task-missed-run-description"
1762+
className="text-sm text-muted-foreground"
1763+
>
1764+
If T3 Code was off or asleep at that time, run once when it is back instead of
1765+
waiting for the next time.
1766+
</p>
1767+
</div>
1768+
<Switch
1769+
id="scheduled-task-missed-run"
1770+
aria-describedby="scheduled-task-missed-run-description"
1771+
checked={draft.runMissedOnce}
1772+
onCheckedChange={(runMissedOnce) =>
1773+
setDraft((current) => ({ ...current, runMissedOnce }))
1774+
}
1775+
/>
1776+
</div>
1777+
) : null}
17551778
</div>
17561779

17571780
<div className="flex items-center justify-between gap-4">

‎apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,21 @@ describe("editing scheduled task branch settings", () => {
151151
});
152152
});
153153

154+
describe("fixed-time scheduled tasks", () => {
155+
it("round-trips run once if missed and sends an explicit skip when it is off", () => {
156+
const draft = taskToDraft({
157+
...legacyTask,
158+
schedule: { type: "fixed_time", timeOfDay: "07:30", weekdays: [1], missedRun: "run_once" },
159+
});
160+
expect(draft.runMissedOnce).toBe(true);
161+
expect(scheduleFromDraft(draft)).toMatchObject({ missedRun: "run_once" });
162+
// The server keeps a stored value when the field is omitted.
163+
expect(scheduleFromDraft({ ...draft, runMissedOnce: false })).toMatchObject({
164+
missedRun: "skip",
165+
});
166+
});
167+
});
168+
154169
describe("webhook scheduled tasks", () => {
155170
const signature = { header: "x-signature", encoding: "base64", prefix: "" } as const;
156171
const webhookTask: ScheduledTask = {

‎apps/web/src/components/settings/scheduledTasksSettings.logic.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ export interface DraftState {
6464
readonly intervalMinutes: string;
6565
readonly timeOfDay: string;
6666
readonly weekdays: ReadonlySet<number>;
67+
readonly runMissedOnce: boolean;
6768
readonly projectId: string;
6869
readonly threadId: string;
6970
readonly workspaceMode: WorkspaceMode;
@@ -191,6 +192,7 @@ export function scheduleFromDraft(draft: DraftState): ScheduledTaskUpsertSchedul
191192
type: "fixed_time",
192193
timeOfDay: draft.timeOfDay || "09:00",
193194
...(selectedEveryDay ? {} : { weekdays: [...draft.weekdays].toSorted() }),
195+
missedRun: draft.runMissedOnce ? "run_once" : "skip",
194196
};
195197
}
196198

@@ -212,6 +214,7 @@ export function taskToDraft(task: ScheduledTask): DraftState {
212214
schedule.type === "interval" ? String(Math.max(1, schedule.everyMs / 60_000)) : "15",
213215
timeOfDay: schedule.type === "fixed_time" ? schedule.timeOfDay : "09:00",
214216
weekdays,
217+
runMissedOnce: schedule.type === "fixed_time" && schedule.missedRun === "run_once",
215218
projectId: task.projectId,
216219
threadId: task.threadId ?? "",
217220
workspaceMode: task.workspaceStrategy.type,

0 commit comments

Comments
 (0)