The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 08:15 UTC
feat(scheduler): run a scheduled task once at a specific date and time (#28104)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Theo Browne committed
Oct 31, 2026 at 22:30 UTC
4ac97be2b67d3ed9c53d9fe1cf42649b88d28e72
21 files changed
+671
-84
apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx
+83
-1
@@ -109,6 +109,10 @@ const DAYS = [
109
110
function describeSchedule(task: ScheduledTask): string {
111
if (task.schedule.type === "webhook") return "On webhook";
112
+ if (task.schedule.type === "once") {
113
+ const runAt = new Date(task.schedule.runAt);
114
+ return `Once, ${formatRunAtDate(runAt)} at ${formatRunAtTime(runAt)}`;
115
+ }
116
if (task.schedule.type === "interval") return formatScheduledTaskInterval(task.schedule.everyMs);
117
const days = task.schedule.weekdays?.length ? repeatLabel(task.schedule.weekdays) : "Every day";
118
return `${days} at ${formatTime(task.schedule.timeOfDay)}`;
@@ -122,6 +126,14 @@ function formatTime(value: string): string {
126
return time.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
127
}
128
129
+function formatRunAtDate(value: Date): string {
130
+ return value.toLocaleDateString([], { month: "short", day: "numeric", year: "numeric" });
131
+}
132
+
133
+function formatRunAtTime(value: Date): string {
134
+ return value.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
135
+}
136
+
137
function timePickerValue(value: string): Date {
138
const [hours, minutes] = value.split(":").map(Number);
139
const time = new Date();
@@ -687,6 +699,7 @@ function TaskForm({
699
});
700
const submissionPending = useRef(false);
701
const [timePickerOpen, setTimePickerOpen] = useState(false);
702
+ const [runAtPicker, setRunAtPicker] = useState<"date" | "time" | null>(null);
703
const taskMissing =
704
draft.task !== null &&
705
tasks.data !== null &&
@@ -701,6 +714,9 @@ function TaskForm({
714
}
715
};
716
717
+ const offersOnce =
718
+ config?.environment.capabilities.oneTimeSchedules === true ||
719
+ draft.task?.schedule.type === "once";
720
const save = async () => {
721
if (
722
!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
@@ -728,6 +744,13 @@ function TaskForm({
744
);
745
return;
746
}
747
+ if (draft.schedule.mode === "once" && !offersOnce) {
748
+ Dialog.alert(
749
+ "Once is not available here",
750
+ "This environment runs an older T3 Code. Update it to schedule a one-time task, or pick another schedule.",
751
+ );
752
+ return;
753
+ }
754
const parsedFilters = parseWebhookFilterDrafts(draft.schedule.filters);
755
if (draft.schedule.mode === "webhook" && "error" in parsedFilters) {
756
Dialog.alert("Invalid filter", parsedFilters.error);
@@ -964,19 +987,31 @@ function TaskForm({
987
variant="card"
988
options={[
989
{ value: "fixed_time", label: "At a time" },
990
+ // Older servers reject one-time schedules on save.
991
+ ...(offersOnce || draft.schedule.mode === "once"
992
+ ? [{ value: "once" as const, label: "Once" }]
993
+ : []),
994
{ value: "interval", label: "Interval" },
995
{ value: "webhook", label: "On webhook" },
996
]}
997
selected={draft.schedule.mode}
998
onSelect={(mode) => {
999
setTimePickerOpen(false);
1000
+ setRunAtPicker(null);
1001
setDraft({
1002
...draft,
1003
prompt:
1004
mode === "webhook" && !draft.prompt.trim()
1005
? DEFAULT_WEBHOOK_PROMPT
1006
: draft.prompt,
979
- schedule: { ...draft.schedule, mode },
1007
+ schedule: {
1008
+ ...draft.schedule,
1009
+ mode,
1010
+ runAt:
1011
+ mode === "once" && !draft.schedule.runAt
1012
+ ? new Date(Math.ceil(Date.now() / 3_600_000) * 3_600_000).toISOString()
1013
+ : draft.schedule.runAt,
1014
+ },
1015
});
1016
}}
1017
/>
@@ -1058,6 +1093,53 @@ function TaskForm({
1093
}}
1094
/>
1095
</>
1096
+ ) : draft.schedule.mode === "once" ? (
1097
+ (["date", "time"] as const).map((field) => {
1098
+ const runAt = new Date(draft.schedule.runAt);
1099
+ const label = field === "date" ? formatRunAtDate(runAt) : formatRunAtTime(runAt);
1100
+ return (
1101
+ <View key={field}>
1102
+ <Pressable
1103
+ accessibilityRole="button"
1104
+ accessibilityLabel={`${field === "date" ? "Date" : "Time"}, ${label}`}
1105
+ onPress={() => setRunAtPicker((open) => (open === field ? null : field))}
1106
+ className="min-h-14 flex-row items-center gap-3 border-t border-border-subtle px-4 py-3 active:opacity-70"
1107
+ >
1108
+ <Text textRole="body" className="text-foreground">
1109
+ {field === "date" ? "Date" : "Time"}
1110
+ </Text>
1111
+ <Text
1112
+ textRole="footnote"
1113
+ className="min-w-0 flex-1 text-right text-foreground-muted"
1114
+ >
1115
+ {label}
1116
+ </Text>
1117
+ <SymbolView
1118
+ name="chevron.right"
1119
+ size={14}
1120
+ tintColorClassName="accent-chevron"
1121
+ type="monochrome"
1122
+ />
1123
+ </Pressable>
1124
+ {runAtPicker === field ? (
1125
+ <DateTimePicker
1126
+ value={runAt}
1127
+ mode={field}
1128
+ display={Platform.OS === "ios" ? "spinner" : "default"}
1129
+ onDismiss={() => setRunAtPicker(null)}
1130
+ onValueChange={(_, selected) => {
1131
+ // Android shows a dialog that closes on pick; iOS stays inline.
1132
+ if (Platform.OS === "android") setRunAtPicker(null);
1133
+ setDraft({
1134
+ ...draft,
1135
+ schedule: { ...draft.schedule, runAt: selected.toISOString() },
1136
+ });
1137
+ }}
1138
+ />
1139
+ ) : null}
1140
+ </View>
1141
+ );
1142
+ })
1143
) : draft.schedule.mode === "webhook" ? (
1144
<>
1145
<WebhookScheduleDetails
apps/mobile/src/features/settings/scheduledTaskDraft.ts
+11
-1
@@ -51,8 +51,10 @@ export function scheduledTaskDefaultModel(
51
}
52
53
export type ScheduleDraft = {
54
- readonly mode: "fixed_time" | "interval" | "webhook";
54
+ readonly mode: "fixed_time" | "once" | "interval" | "webhook";
55
readonly timeOfDay: string;
56
+ /** ISO time for a one-time run. Empty until the user picks the "Once" mode. */
57
+ readonly runAt: string;
58
readonly weekdays: ReadonlyArray<number>;
59
readonly intervalMinutes: string;
60
readonly signature: ScheduledTaskWebhookSignature | null;
@@ -68,6 +70,7 @@ export type ScheduleDraft = {
70
export const DEFAULT_SCHEDULE: ScheduleDraft = {
71
mode: "fixed_time",
72
timeOfDay: "09:00",
73
+ runAt: "",
74
weekdays: [1, 2, 3, 4, 5],
75
intervalMinutes: "15",
76
signature: null,
@@ -89,6 +92,8 @@ export function scheduleDraftForTask(task: Pick<ScheduledTask, "schedule">): Sch
92
? [...new Set(task.schedule.weekdays)].sort((a, b) => a - b)
93
: [0, 1, 2, 3, 4, 5, 6],
94
};
95
+ case "once":
96
+ return { ...DEFAULT_SCHEDULE, mode: "once", runAt: task.schedule.runAt };
97
case "interval":
98
return {
99
...DEFAULT_SCHEDULE,
@@ -166,6 +171,10 @@ export function scheduleFromDraft(draft: ScheduleDraft): ScheduledTaskUpsertSche
171
: {}),
172
};
173
}
174
+ if (draft.mode === "once") {
175
+ const runAt = new Date(draft.runAt);
176
+ return Number.isNaN(runAt.getTime()) ? null : { type: "once", runAt: runAt.toISOString() };
177
+ }
178
if (draft.mode === "interval") {
179
const minutes = parseIntervalMinutes(draft.intervalMinutes);
180
const everyMs = Math.round(minutes * 60_000);
@@ -215,6 +224,7 @@ function draftSignature(draft: ScheduledTaskDraft): string {
224
.map((option) => [option.id, option.value]),
225
draft.schedule.mode,
226
draft.schedule.timeOfDay,
227
+ draft.schedule.runAt,
228
[...draft.schedule.weekdays].sort((a, b) => a - b),
229
draft.schedule.intervalMinutes,
230
draft.schedule.maxDeliveryAgeMinutes,
apps/server/src/environment/ServerEnvironment.ts
+1
@@ -267,6 +267,7 @@ export const make = Effect.gen(function* () {
267
projectOrganization: true,
268
ignoredFileListing: true,
269
triage: true,
270
+ oneTimeSchedules: true,
271
npmReleaseLookup: true,
272
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
273
...(serverInstallation === null ? {} : { serverInstallation }),
apps/server/src/mcp/toolkits/orchestrator/tools.ts
+1
-1
@@ -165,7 +165,7 @@ const ScheduleTaskTool = Tool.make("schedule_task", {
165
failureMode: "return",
166
dependencies,
167
})
168
- .annotate(Tool.Title, "Schedule a recurring task")
168
+ .annotate(Tool.Title, "Schedule a task")
169
.annotate(Tool.Destructive, true)
170
.annotate(Tool.OpenWorld, true);
171
apps/server/src/provider/agentContextBudget.json
+1
-1
@@ -1,5 +1,5 @@
1
{
2
"claudeSystemAppendBytes": 5153,
3
"codexAdditionalContextBytes": 6883,
4
- "mcpToolListJsonBytes": 47020
4
+ "mcpToolListJsonBytes": 47074
5
}
apps/server/src/scheduledTasks/Schedule.test.ts
+6
@@ -27,6 +27,12 @@ describe("scheduled task schedule calculation", () => {
27
});
28
29
it("compares schedules structurally", () => {
30
+ expect(
31
+ isSameSchedule(
32
+ { type: "once", runAt: "2026-11-01T03:00:00-05:00" },
33
+ { type: "once", runAt: "2026-11-01T08:00:00.000Z" },
34
+ ),
35
+ ).toBe(true);
36
expect(
37
isSameSchedule({ type: "interval", everyMs: 60_000 }, { type: "interval", everyMs: 60_000 }),
38
).toBe(true);
apps/server/src/scheduledTasks/Schedule.ts
+9
@@ -1,5 +1,6 @@
1
import { MIN_SCHEDULED_TASK_INTERVAL_MS, type ScheduledTaskSchedule } from "@t3tools/contracts";
2
import * as DateTime from "effect/DateTime";
3
+import * as Option from "effect/Option";
4
5
const MINUTE_MS = 60_000;
6
@@ -14,6 +15,13 @@ export function nextScheduledRunAt(
15
from: DateTime.DateTime,
16
): DateTime.DateTime | null {
17
if (schedule.type === "webhook") return null;
18
+ if (schedule.type === "once") {
19
+ const runAt = DateTime.make(schedule.runAt);
20
+ return Option.isSome(runAt) &&
21
+ DateTime.toEpochMillis(runAt.value) > DateTime.toEpochMillis(from)
22
+ ? runAt.value
23
+ : null;
24
+ }
25
if (schedule.type === "interval") {
26
// Intervals advance elapsed time, including across daylight-saving changes.
27
return DateTime.addDuration(from, Math.max(schedule.everyMs, MIN_SCHEDULED_TASK_INTERVAL_MS));
@@ -48,6 +56,7 @@ export function isSameSchedule(a: ScheduledTaskSchedule, b: ScheduledTaskSchedul
56
return b.type === "interval" && a.everyMs === b.everyMs;
57
}
58
if (a.type === "webhook") return b.type === "webhook";
59
+ if (a.type === "once") return b.type === "once" && Date.parse(a.runAt) === Date.parse(b.runAt);
60
if (b.type !== "fixed_time") return false;
61
// Compare parsed times so padded-hour edits do not reschedule pending runs.
62
const aTime = parseTimeOfDay(a.timeOfDay);
apps/server/src/scheduledTasks/ScheduledTaskService.interval.test.ts
+183
@@ -4,6 +4,7 @@ import { ScheduledTaskUpsertInput } from "@t3tools/contracts";
4
import * as Effect from "effect/Effect";
5
import * as Layer from "effect/Layer";
6
import * as Schema from "effect/Schema";
7
+import * as SqlClient from "effect/sql/SqlClient";
8
import * as TestClock from "effect/testing/TestClock";
9
import { afterEach, vi } from "vite-plus/test";
10
@@ -129,3 +130,185 @@ it.effect.each([
130
Effect.provide(SqlitePersistence.layerMemory),
131
),
132
);
133
+
134
+// Each launch takes two minutes, so a manual run can start before the run time and end after it.
135
+const slowLaunchLayer = ScheduledTaskService.layer.pipe(
136
+ Layer.provide(
137
+ Layer.merge(
138
+ dependencies,
139
+ Layer.mock(ThreadLaunchService.ThreadLaunchService)({
140
+ launch: () => TestClock.adjust("2 minutes").pipe(Effect.andThen(Effect.die("synthetic"))),
141
+ }),
142
+ ),
143
+ ),
144
+);
145
+
146
+it.effect("runs a one-time schedule once and rejects past times", () =>
147
+ Effect.gen(function* () {
148
+ yield* TestClock.setTime(Date.parse("2026-11-01T07:59:00.000Z"));
149
+ yield* Effect.gen(function* () {
150
+ const service = yield* ScheduledTaskService.ScheduledTaskService;
151
+ const decoded = yield* decodeInput({
152
+ ...input,
153
+ schedule: { type: "once", runAt: "2026-11-01T03:00:00-05:00" },
154
+ });
155
+ const created = yield* service.upsert(decoded);
156
+ expect(created.task.schedule).toEqual({ type: "once", runAt: "2026-11-01T08:00:00.000Z" });
157
+ expect(created.task.nextRunAt).toBe("2026-11-01T08:00:00.000Z");
158
+
159
+ // A manual run that starts before the time keeps the scheduled run, even if it ends after.
160
+ const early = yield* service.runNow({ id: created.task.id });
161
+ expect(early.task.nextRunAt).toBe("2026-11-01T08:00:00.000Z");
162
+
163
+ const due = yield* service.runNow({ id: created.task.id });
164
+ expect(due.task.nextRunAt).toBeNull();
165
+ expect((yield* service.list()).tasks[0]?.nextRunAt).toBeNull();
166
+
167
+ yield* service.setEnabled({ id: created.task.id, enabled: false });
168
+ const resumed = yield* service
169
+ .setEnabled({ id: created.task.id, enabled: true })
170
+ .pipe(Effect.flip);
171
+ expect(resumed.message).toBe("The run time has passed. Pick a time in the future.");
172
+
173
+ const past = yield* service
174
+ .upsert({ ...decoded, commandId: undefined, title: "Late" })
175
+ .pipe(Effect.flip);
176
+ expect(past.message).toBe("The run time has passed. Pick a time in the future.");
177
+ }).pipe(Effect.provide(slowLaunchLayer));
178
+ }).pipe(
179
+ Effect.provideService(ServerActivation, Effect.never),
180
+ Effect.provide(SqlitePersistence.layerMemory),
181
+ ),
182
+);
183
+
184
+const ONCE = { type: "once", runAt: "2026-11-01T08:00:00Z" } as const;
185
+/** A next run that only the simulated concurrent write produces. */
186
+const MOVED = "2030-01-01T00:00:00.000Z";
187
+
188
+const onceInput = {
189
+ ...input,
190
+ commandId: "once-race",
191
+ schedule: { type: "once", runAt: "2026-11-01T08:00:00Z" },
192
+};
193
+
194
+it.effect.each([
195
+ { change: "a run completes", saved: ONCE, edited: ONCE, pause: false, expected: MOVED },
196
+ {
197
+ change: "a run completes during a padded-time edit",
198
+ saved: { type: "fixed_time", timeOfDay: "9:00" },
199
+ edited: { type: "fixed_time", timeOfDay: "09:00" },
200
+ pause: false,
201
+ expected: MOVED,
202
+ },
203
+ {
204
+ change: "another client pauses the task",
205
+ saved: ONCE,
206
+ edited: ONCE,
207
+ pause: true,
208
+ expected: "2026-11-01T08:00:00.000Z",
209
+ },
210
+] as const)(
211
+ "a title save keeps the stored next run only while nothing else changed: $change",
212
+ ({ saved, edited, pause, expected }) =>
213
+ Effect.gen(function* () {
214
+ yield* TestClock.setTime(Date.parse("2026-11-01T07:00:00.000Z"));
215
+ // The project check runs between the save's read and write, so it stands in for
216
+ // a concurrent write in that gap.
217
+ const writeMidSave = Layer.unwrap(
218
+ Effect.gen(function* () {
219
+ const sql = yield* SqlClient.SqlClient;
220
+ return Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
221
+ namedProjectsRoot: "/projects",
222
+ isScratchProject: () =>
223
+ sql`UPDATE scheduled_tasks SET next_run_at = ${MOVED}, enabled = ${pause ? 0 : 1}`.pipe(
224
+ Effect.as(false),
225
+ Effect.orDie,
226
+ ),
227
+ });
228
+ }),
229
+ );
230
+ const layer = ScheduledTaskService.layer.pipe(
231
+ Layer.provide(Layer.merge(dependencies, writeMidSave)),
232
+ );
233
+ yield* Effect.gen(function* () {
234
+ const service = yield* ScheduledTaskService.ScheduledTaskService;
235
+ const worktree = { type: "worktree", baseRef: "main" };
236
+ yield* service.upsert(
237
+ yield* decodeInput({
238
+ ...onceInput,
239
+ schedule: saved,
240
+ workspaceStrategy: { type: "root" },
241
+ }),
242
+ );
243
+ const renamed = yield* service.upsert(
244
+ yield* decodeInput({
245
+ ...onceInput,
246
+ schedule: edited,
247
+ workspaceStrategy: worktree,
248
+ title: "Renamed",
249
+ }),
250
+ );
251
+ expect(renamed.task.enabled).toBe(true);
252
+ expect(renamed.task.nextRunAt).toBe(expected);
253
+ }).pipe(Effect.provide(layer));
254
+ }).pipe(
255
+ Effect.provideService(ServerActivation, Effect.never),
256
+ Effect.provide(SqlitePersistence.layerMemory),
257
+ ),
258
+);
259
+
260
+it.effect("keeps a one-time run after a restart interrupts an earlier manual run", () =>
261
+ Effect.gen(function* () {
262
+ yield* TestClock.setTime(Date.parse("2026-11-01T07:59:00.000Z"));
263
+ const sql = yield* SqlClient.SqlClient;
264
+ const created = yield* Effect.gen(function* () {
265
+ const service = yield* ScheduledTaskService.ScheduledTaskService;
266
+ return yield* service.upsert(yield* decodeInput(onceInput));
267
+ }).pipe(Effect.provide(serviceLayer));
268
+ yield* sql`UPDATE scheduled_tasks SET last_run_status = 'running', last_run_at = '2026-11-01T07:59:00.000Z'`;
269
+
270
+ yield* TestClock.setTime(Date.parse("2026-11-01T08:05:00.000Z"));
271
+ yield* Effect.gen(function* () {
272
+ const service = yield* ScheduledTaskService.ScheduledTaskService;
273
+ const [task] = (yield* service.list()).tasks;
274
+ expect(task?.id).toBe(created.task.id);
275
+ expect(task?.lastRunStatus).toBe("failed");
276
+ expect(task?.nextRunAt).toBe("2026-11-01T08:00:00.000Z");
277
+ }).pipe(Effect.provide(serviceLayer));
278
+ }).pipe(
279
+ Effect.provideService(ServerActivation, Effect.never),
280
+ Effect.provide(SqlitePersistence.layerMemory),
281
+ ),
282
+);
283
+
284
+it.effect("reports the stored task when the row was replaced during the run", () =>
285
+ Effect.gen(function* () {
286
+ yield* TestClock.setTime(Date.parse("2026-11-01T07:00:00.000Z"));
287
+ // The launch stands in for a delete and same-id recreate while the run is out.
288
+ const replaceRowDuringLaunch = Layer.unwrap(
289
+ Effect.gen(function* () {
290
+ const sql = yield* SqlClient.SqlClient;
291
+ return Layer.mock(ThreadLaunchService.ThreadLaunchService)({
292
+ launch: () =>
293
+ sql`UPDATE scheduled_tasks SET last_run_status = 'never', last_run_at = NULL, run_count = 0`.pipe(
294
+ Effect.orDie,
295
+ Effect.andThen(Effect.die("synthetic dispatch failure")),
296
+ ),
297
+ });
298
+ }),
299
+ );
300
+ const layer = ScheduledTaskService.layer.pipe(
301
+ Layer.provide(Layer.merge(dependencies, replaceRowDuringLaunch)),
302
+ );
303
+ yield* Effect.gen(function* () {
304
+ const service = yield* ScheduledTaskService.ScheduledTaskService;
305
+ const created = yield* service.upsert(yield* decodeInput(onceInput));
306
+ const ran = yield* service.runNow({ id: created.task.id });
307
+ expect(ran.task.runCount).toBe(0);
308
+ expect(ran.task.lastRunStatus).toBe("never");
309
+ }).pipe(Effect.provide(layer));
310
+ }).pipe(
311
+ Effect.provideService(ServerActivation, Effect.never),
312
+ Effect.provide(SqlitePersistence.layerMemory),
313
+ ),
314
+);
apps/server/src/scheduledTasks/ScheduledTaskService.ts
+141
-53
@@ -298,6 +298,35 @@ function nextRunAt(
298
}
299
}
300
301
+/**
302
+ * Next run after an interrupted run. A one-time task counts from the run's start
303
+ * (`lastRunAt`), so a manual run that began before its time does not use it up.
304
+ */
305
+function nextRunAfterRun(
306
+ task: Pick<ScheduledTask, "enabled" | "schedule" | "lastRunAt">,
307
+ now: DateTime.DateTime,
308
+): string | null {
309
+ const startedAt =
310
+ task.schedule.type === "once" && task.lastRunAt !== null
311
+ ? DateTime.make(task.lastRunAt)
312
+ : Option.none();
313
+ return nextRunAt(
314
+ task,
315
+ Option.getOrElse(startedAt, () => now),
316
+ );
317
+}
318
+
319
+/** An enabled one-time task with a past time would never run, so saving it is an error. */
320
+function requireFutureOnce(
321
+ task: Pick<ScheduledTask, "enabled" | "schedule">,
322
+ now: DateTime.DateTime,
323
+ taskId: ScheduledTaskId,
324
+) {
325
+ return task.enabled && task.schedule.type === "once" && nextRunAt(task, now) === null
326
+ ? taskError("The run time has passed. Pick a time in the future.", { taskId })
327
+ : Effect.void;
328
+}
329
+
330
function errorMessage(error: unknown): string {
331
if (Cause.isCause(error)) return Cause.pretty(error);
332
if (error instanceof Error) return error.message;
@@ -542,6 +571,8 @@ export const layer = Layer.effect(
571
const saveTask = (
572
task: ScheduledTask,
573
requireExisting: boolean,
574
+ /** The schedule this save read, when it left the schedule unchanged. */
575
+ keptSchedule: ScheduledTask["schedule"] | null,
576
webhook: {
577
readonly token: string | null;
578
readonly secret: string | null;
@@ -612,7 +643,18 @@ export const layer = Layer.effect(
643
interaction_mode = excluded.interaction_mode,
644
creation_source = excluded.creation_source,
645
updated_at = excluded.updated_at,
615
- next_run_at = excluded.next_run_at,
646
+ -- Keep a next_run_at that a finishing run moved during this save, unless
647
+ -- another edit changed the schedule or enabled state meanwhile.
648
+ next_run_at = CASE
649
+ WHEN ${keptSchedule === null ? 0 : 1} = 1
650
+ AND scheduled_tasks.schedule_json IN (
651
+ excluded.schedule_json,
652
+ ${keptSchedule === null ? null : JSON.stringify(keptSchedule)}
653
+ )
654
+ AND scheduled_tasks.enabled = excluded.enabled
655
+ THEN scheduled_tasks.next_run_at
656
+ ELSE excluded.next_run_at
657
+ END,
658
-- Only rotate changes a live token, so a save racing a rotation
659
-- cannot bring the old URL back.
660
webhook_token = CASE
@@ -685,7 +727,9 @@ export const layer = Layer.effect(
727
WHERE task_id = ${input.id}
728
AND last_run_status = 'running'
729
AND last_run_at = ${input.startedAtIso}
730
+ RETURNING task_id
731
`.pipe(
732
+ Effect.map((rows) => rows.length > 0),
733
Effect.mapError((cause) =>
734
taskError("Could not record schedule task run.", { taskId: input.id, cause }),
735
),
@@ -695,7 +739,12 @@ export const layer = Layer.effect(
739
// runDueTasks skips 'running' rows forever, and the dispatch may already have gone out,
740
// so next_run_at must advance. Pending webhook attempts count only with their completion.
741
const releaseStuckRun = Effect.fn("ScheduledTaskService.releaseStuckRun")(
698
- function* (task: ScheduledTask, message: string, pendingDeliveryId?: string) {
742
+ function* (
743
+ task: ScheduledTask,
744
+ startedAtIso: string,
745
+ message: string,
746
+ pendingDeliveryId?: string,
747
+ ) {
748
const now = yield* localNow;
749
const reread = yield* Effect.result(findTask(task.id));
750
if (Result.isSuccess(reread) && reread.success === null) return;
@@ -704,7 +753,7 @@ export const layer = Layer.effect(
753
UPDATE scheduled_tasks
754
SET last_run_status = 'failed',
755
last_run_error = ${message},
707
- next_run_at = ${nextRunAt(source, now)},
756
+ next_run_at = ${nextRunAfterRun({ ...source, lastRunAt: startedAtIso }, now)},
757
updated_at = ${iso(now)},
758
run_count = run_count + CASE WHEN EXISTS (
759
SELECT 1 FROM scheduled_task_webhook_pending
@@ -714,7 +763,7 @@ export const layer = Layer.effect(
763
`;
764
yield* notifyChanged;
765
},
717
- (effect, task, _message, _pendingDeliveryId) =>
766
+ (effect, task, _startedAtIso, _message, _pendingDeliveryId) =>
767
effect.pipe(
768
Effect.catch((cause) =>
769
Effect.logWarning("Could not release stuck schedule task run", {
@@ -734,6 +783,9 @@ export const layer = Layer.effect(
783
readonly dispatched: Ref.Ref<boolean>;
784
},
785
) {
786
+ // Read before reserving: nothing between the reservation and its release may fail.
787
+ const startedAt = yield* localNow;
788
+ const startedAtIso = iso(startedAt);
789
const reserved = yield* Ref.modify(activeRuns, (active) => {
790
if (active.has(task.id)) return [false, active] as const;
791
const next = new Set(active);
@@ -744,13 +796,10 @@ export const layer = Layer.effect(
796
if (trigger !== "scheduled") {
797
return yield* taskError("Schedule task is already running.", { taskId: task.id });
798
}
747
- return { task, threadId: null };
799
+ return { task, threadId: null, dispatchFailed: false };
800
}
801
802
return yield* Effect.gen(function* () {
751
- const startedAt = yield* localNow;
752
- const startedAtIso = iso(startedAt);
753
-
803
// Re-read stale poll snapshots so deleted, paused or postponed tasks cannot fire.
804
const active = yield* findTask(task.id);
805
if (active === null) {
@@ -762,7 +811,7 @@ export const layer = Layer.effect(
811
if (trigger !== "scheduled") {
812
return yield* taskError("Schedule task not found.", { taskId: task.id });
813
}
765
- return { task, threadId: null };
814
+ return { task, threadId: null, dispatchFailed: false };
815
}
816
if (
817
webhook !== undefined &&
@@ -770,7 +819,11 @@ export const layer = Layer.effect(
819
NodeSqliteClient.readOnly,
820
)).length > 0
821
)
773
- return { task: { ...active, lastRunStatus: "succeeded" as const }, threadId: null };
822
+ return {
823
+ task: { ...active, lastRunStatus: "succeeded" as const },
824
+ threadId: null,
825
+ dispatchFailed: false,
826
+ };
827
const parsedNextRunAt =
828
active.nextRunAt === null ? Option.none() : DateTime.make(active.nextRunAt);
829
if (
@@ -779,7 +832,7 @@ export const layer = Layer.effect(
832
Option.isNone(parsedNextRunAt) ||
833
DateTime.toEpochMillis(parsedNextRunAt.value) > DateTime.toEpochMillis(startedAt))
834
) {
782
- return { task: active, threadId: null };
835
+ return { task: active, threadId: null, dispatchFailed: false };
836
}
837
// Reject queued deliveries after pause, same-id recreation or trigger changes.
838
if (webhook !== undefined) {
@@ -895,18 +948,28 @@ export const layer = Layer.effect(
948
const lastRunStatus = runSucceeded ? ("succeeded" as const) : ("failed" as const);
949
const lastRunError = runSucceeded ? null : errorMessage(result.cause);
950
const threadId = runSucceeded ? result.value : null;
898
- const current = yield* findTask(task.id);
899
- const scheduleSource = current ?? task;
900
- const completed: ScheduledTask = {
901
- ...scheduleSource,
902
- updatedAt: iso(completedAt),
903
- lastRunAt: startedAtIso,
904
- nextRunAt: nextRunAt(scheduleSource, completedAt),
905
- lastRunStatus,
906
- lastRunError,
907
- runCount: scheduleSource.runCount + 1,
908
- };
909
- if (current !== null) {
951
+ // One transaction, so an edit cannot land between reading the schedule and
952
+ // writing the next run computed from it. The origin is read first: it reads
953
+ // files, and the transaction holds SQLite's writer lock.
954
+ const origin = yield* readWebhookOrigin;
955
+ const record = Effect.gen(function* () {
956
+ const [row] = yield* getRows(task.id);
957
+ const current = row === undefined ? null : yield* decodeRow(row, origin);
958
+ const scheduleSource = current ?? task;
959
+ const completed: ScheduledTask = {
960
+ ...scheduleSource,
961
+ updatedAt: iso(completedAt),
962
+ lastRunAt: startedAtIso,
963
+ // A manual run that starts before a one-time run must not use it up.
964
+ nextRunAt: nextRunAt(
965
+ scheduleSource,
966
+ scheduleSource.schedule.type === "once" ? startedAt : completedAt,
967
+ ),
968
+ lastRunStatus,
969
+ lastRunError,
970
+ runCount: scheduleSource.runCount + 1,
971
+ };
972
+ if (current === null) return { recorded: completed, written: false };
973
// startedAtIso in the guard ensures this writes only to the row this
974
// run marked as running — a task deleted mid-run and recreated with
975
// the same id (idempotent commandId replay) must not be stamped.
@@ -918,32 +981,43 @@ export const layer = Layer.effect(
981
error: lastRunError,
982
startedAtIso,
983
});
921
- if (webhook === undefined) yield* completion;
922
- else
923
- yield* sql
924
- .withTransaction(
925
- Effect.gen(function* () {
926
- const pending =
927
- yield* sql`SELECT 1 FROM scheduled_task_webhook_pending WHERE delivery_id = ${webhook.deliveryId}`;
928
- if (pending.length === 0) yield* completion;
929
- else {
930
- const counted =
931
- yield* sql`UPDATE scheduled_task_webhook_pending SET state = ${runSucceeded ? "completed" : "failed"}
932
- WHERE delivery_id = ${webhook.deliveryId} AND state NOT IN ('completed', 'failed') RETURNING delivery_id`;
933
- if (counted.length > 0) yield* completion;
934
- }
935
- }),
936
- )
937
- .pipe(
938
- Effect.mapError((cause) =>
939
- taskError("Could not record webhook completion.", { taskId: task.id, cause }),
940
- ),
941
- );
942
- yield* notifyChanged;
943
- }
944
- return { task: completed, threadId };
984
+ let written = false;
985
+ if (webhook === undefined) written = yield* completion;
986
+ else {
987
+ const pending =
988
+ yield* sql`SELECT 1 FROM scheduled_task_webhook_pending WHERE delivery_id = ${webhook.deliveryId}`;
989
+ if (pending.length === 0) written = yield* completion;
990
+ else {
991
+ const counted =
992
+ yield* sql`UPDATE scheduled_task_webhook_pending SET state = ${runSucceeded ? "completed" : "failed"}
993
+ WHERE delivery_id = ${webhook.deliveryId} AND state NOT IN ('completed', 'failed') RETURNING delivery_id`;
994
+ if (counted.length > 0) written = yield* completion;
995
+ }
996
+ }
997
+ // A row recreated mid-run is not this run's, so report what is stored.
998
+ return { recorded: written ? completed : current, written };
999
+ });
1000
+ const { recorded, written } = yield* sql
1001
+ .withTransaction(record)
1002
+ .pipe(
1003
+ Effect.mapError((cause) =>
1004
+ isScheduledTaskError(cause)
1005
+ ? cause
1006
+ : taskError(
1007
+ webhook === undefined
1008
+ ? "Could not record schedule task run."
1009
+ : "Could not record webhook completion.",
1010
+ { taskId: task.id, cause },
1011
+ ),
1012
+ ),
1013
+ );
1014
+ if (written) yield* notifyChanged;
1015
+ // The stored row can belong to a replacement, so report this dispatch separately.
1016
+ return { task: recorded, threadId, dispatchFailed: !runSucceeded };
1017
}).pipe(
946
- Effect.onError((cause) => releaseStuckRun(task, errorMessage(cause), webhook?.deliveryId)),
1018
+ Effect.onError((cause) =>
1019
+ releaseStuckRun(task, startedAtIso, errorMessage(cause), webhook?.deliveryId),
1020
+ ),
1021
Effect.ensuring(
1022
Ref.update(activeRuns, (active) => {
1023
const next = new Set(active);
@@ -1039,7 +1113,7 @@ export const layer = Layer.effect(
1113
UPDATE scheduled_tasks
1114
SET last_run_status = 'failed',
1115
last_run_error = 'Run was interrupted by a server restart.',
1042
- next_run_at = ${nextRunAt(decoded.success, now)},
1116
+ next_run_at = ${nextRunAfterRun(decoded.success, now)},
1117
updated_at = ${iso(now)},
1118
run_count = run_count + CASE WHEN EXISTS (
1119
SELECT 1 FROM scheduled_task_webhook_pending
@@ -1150,7 +1224,9 @@ export const layer = Layer.effect(
1224
: undefined),
1225
),
1226
}
1153
- : input.schedule;
1227
+ : input.schedule.type === "once"
1228
+ ? { type: "once", runAt: iso(DateTime.makeUnsafe(input.schedule.runAt)) }
1229
+ : input.schedule;
1230
const webhook =
1231
input.schedule.type === "webhook"
1232
? yield* Effect.gen(function* () {
@@ -1196,6 +1272,8 @@ export const layer = Layer.effect(
1272
existingTask !== null &&
1273
existingTask.enabled === input.enabled &&
1274
isSameSchedule(existingTask.schedule, schedule);
1275
+ if (!scheduleUnchanged)
1276
+ yield* requireFutureOnce({ enabled: input.enabled, schedule }, now, id);
1277
const task: ScheduledTask = {
1278
id,
1279
title: input.title,
@@ -1220,7 +1298,12 @@ export const layer = Layer.effect(
1298
lastRunError: existingTask?.lastRunError ?? null,
1299
runCount: existingTask?.runCount ?? 0,
1300
};
1223
- yield* saveTask(task, input.requireExisting === true, webhook);
1301
+ yield* saveTask(
1302
+ task,
1303
+ input.requireExisting === true,
1304
+ scheduleUnchanged ? existingTask.schedule : null,
1305
+ webhook,
1306
+ );
1307
yield* notifyChanged;
1308
return { task: (yield* findTask(id)) ?? task };
1309
});
@@ -1231,6 +1314,11 @@ export const layer = Layer.effect(
1314
const existing = yield* loadTask(input.id);
1315
if (existing.enabled === input.enabled) return { task: existing };
1316
const now = yield* localNow;
1317
+ yield* requireFutureOnce(
1318
+ { enabled: input.enabled, schedule: existing.schedule },
1319
+ now,
1320
+ input.id,
1321
+ );
1322
const next = nextRunAt({ enabled: input.enabled, schedule: existing.schedule }, now);
1323
// RETURNING so a task deleted between the load and this UPDATE is a
1324
// visible not-found error, not a false success.
@@ -1668,8 +1756,8 @@ export const layer = Layer.effect(
1756
]);
1757
const dispatched = yield* Ref.make(false);
1758
return yield* runTask(task, "webhook", { deliveryId, prompt, dispatched }).pipe(
1671
- Effect.flatMap(({ task: completed }) =>
1672
- completed.lastRunStatus === "failed"
1759
+ Effect.flatMap(({ dispatchFailed }) =>
1760
+ dispatchFailed
1761
? runOutcome("failed").pipe(
1762
Effect.andThen(markDeliveryFailed(deliveryId, "The run failed to start.")),
1763
Effect.andThen(releaseFailedDelivery(deliveryId)),
apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts
+26
@@ -1199,6 +1199,32 @@ it.effect("start failures release both replay keys and relay claims for redelive
1199
),
1200
);
1201
1202
+it.effect("a start failure releases the relay claim when the task row is replaced mid-run", () =>
1203
+ Effect.gen(function* () {
1204
+ const gate = yield* Deferred.make<void>();
1205
+ yield* withService(
1206
+ ({ service, sql, launches }) =>
1207
+ Effect.gen(function* () {
1208
+ const { task } = yield* service.upsert(yield* webhookTaskInput());
1209
+ const request = requestFor(task, { relayDeliveryId: "replaced-mid-run" });
1210
+ const first = yield* waitForSpan(
1211
+ service.triggerWebhook(request),
1212
+ "ScheduledTaskService.runWebhookDelivery",
1213
+ ).pipe(Effect.forkChild);
1214
+ yield* Queue.take(launches);
1215
+ // A same-id recreate while the launch is out: the stored row is no longer this run's.
1216
+ yield* sql`UPDATE scheduled_tasks SET last_run_status = 'never', last_run_at = NULL`;
1217
+ yield* Deferred.succeed(gate, undefined);
1218
+ yield* Fiber.join(first);
1219
+ const retry = yield* service.triggerWebhook(request);
1220
+ assert.equal(retry._tag === "accepted" && retry.outcome, "accepted");
1221
+ yield* Queue.take(launches);
1222
+ }),
1223
+ { gate, failLaunches: { remaining: 1 } },
1224
+ );
1225
+ }),
1226
+);
1227
+
1228
it.effect("main retention keeps fifty runs and preserves filtered and dedupe buckets", () =>
1229
withService(({ service, sql, launches }) =>
1230
Effect.gen(function* () {
apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx
+3
-1
@@ -70,7 +70,9 @@ function environment() {
70
environmentId,
71
label: "Laptop",
72
connection: { phase: state.connected ? "connected" : "disconnected" },
73
- serverConfig: state.connected ? { environment: { platform: "linux" } } : null,
73
+ serverConfig: state.connected
74
+ ? { environment: { platform: "linux", capabilities: { oneTimeSchedules: true } } }
75
+ : null,
76
};
77
}
78
apps/web/src/components/settings/ScheduledTasksSettings.tsx
+68
-12
@@ -77,7 +77,8 @@ import { SettingsGroup } from "./SettingsGroup";
77
import { settingsScopeEnvironmentLabel, settingsScopeEnvironmentLabels } from "./settingsScopeAxis";
78
import {
79
WEBHOOK_SIGNATURE_DEFAULTS,
80
- webhookDraftErrors,
80
+ scheduleDraftErrors,
81
+ toDateTimeLocalValue,
82
webhookDeliveryLabel,
83
defaultScheduledTaskProjectId,
84
matchesScheduledTaskScope,
@@ -136,6 +137,8 @@ const EMPTY_DRAFT: DraftState = {
137
scheduleMode: "fixed",
138
intervalMinutes: "15",
139
timeOfDay: "09:00",
140
+ runAt: "",
141
+ savedRunAt: "",
142
weekdays: new Set([1, 2, 3, 4, 5]),
143
projectId: "",
144
threadId: "",
@@ -284,8 +287,14 @@ function splitModelKey(value: string): ModelSelection | null {
287
};
288
}
289
290
+const ONCE_FORMATTER = new Intl.DateTimeFormat(undefined, {
291
+ dateStyle: "medium",
292
+ timeStyle: "short",
293
+});
294
+
295
export function scheduleLabel(schedule: ScheduledTaskSchedule): string {
296
if (schedule.type === "webhook") return "On webhook";
297
+ if (schedule.type === "once") return `Once, ${ONCE_FORMATTER.format(new Date(schedule.runAt))}`;
298
if (schedule.type === "interval") {
299
const minutes = schedule.everyMs / 60_000;
300
return Number.isInteger(minutes)
@@ -1171,6 +1180,10 @@ function ScheduledTaskEditorForm({
1180
const { scope, connectedEnvironments } = useSettingsScope();
1181
const [environmentId, setEnvironmentId] = useState(initialEnvironmentId);
1182
const environment = useEnvironment(environmentId);
1183
+ // Older servers reject one-time schedules, so offer Once only where it can save.
1184
+ const offersOnce =
1185
+ environment?.serverConfig?.environment.capabilities.oneTimeSchedules === true ||
1186
+ task?.schedule.type === "once";
1187
const connected =
1188
environment?.connection.phase === "connected" && environment.serverConfig !== null;
1189
const tasksQuery = useEnvironmentQuery(
@@ -1278,7 +1291,7 @@ function ScheduledTaskEditorForm({
1291
}
1292
const schedule = scheduleFromDraft(draft);
1293
if (schedule === null) {
1281
- for (const error of webhookDraftErrors(draft)) reportFailure(error.title, error.description);
1294
+ for (const error of scheduleDraftErrors(draft)) reportFailure(error.title, error.description);
1295
return;
1296
}
1297
if (
@@ -1298,6 +1311,13 @@ function ScheduledTaskEditorForm({
1311
reportFailure("Invalid interval", "Enter an interval of at least one minute.");
1312
return;
1313
}
1314
+ if (schedule.type === "once" && !offersOnce) {
1315
+ reportFailure(
1316
+ "Once is not available here",
1317
+ "This environment runs an older T3 Code. Update it to schedule a one-time task, or pick another schedule.",
1318
+ );
1319
+ return;
1320
+ }
1321
if (draft.workspaceMode === "existing_worktree" && !draft.existingWorktreePath.trim()) {
1322
reportFailure("Checkout path is required", "Enter the path of the checkout to run in.");
1323
return;
@@ -1352,7 +1372,8 @@ function ScheduledTaskEditorForm({
1372
<DialogHeader>
1373
<DialogTitle>{draft.editingId ? "Edit task" : "New task"}</DialogTitle>
1374
<DialogDescription>
1355
- Run a prompt automatically on an interval, at a fixed time, or when a webhook is called.
1375
+ Run a prompt automatically on an interval, at a fixed time, once at a set date, or when a
1376
+ webhook is called.
1377
</DialogDescription>
1378
</DialogHeader>
1379
@@ -1580,18 +1601,39 @@ function ScheduledTaskEditorForm({
1601
value={[draft.scheduleMode]}
1602
onValueChange={(values) => {
1603
const mode = values[0] as ScheduleMode | undefined;
1583
- if (mode === "fixed" || mode === "interval" || mode === "webhook")
1584
- setDraft((current) => ({
1585
- ...current,
1586
- scheduleMode: mode,
1587
- prompt:
1588
- mode === "webhook" && !current.prompt.trim()
1589
- ? DEFAULT_WEBHOOK_PROMPT
1590
- : current.prompt,
1591
- }));
1604
+ if (
1605
+ mode === "fixed" ||
1606
+ mode === "once" ||
1607
+ mode === "interval" ||
1608
+ mode === "webhook"
1609
+ )
1610
+ setDraft((current) => {
1611
+ const suggested =
1612
+ mode === "once" && !current.runAt
1613
+ ? new Date(Math.ceil(Date.now() / 3_600_000) * 3_600_000)
1614
+ : null;
1615
+ return {
1616
+ ...current,
1617
+ scheduleMode: mode,
1618
+ // Keep the instant too, so an hour that repeats when clocks go back stays exact.
1619
+ ...(suggested === null
1620
+ ? {}
1621
+ : {
1622
+ runAt: toDateTimeLocalValue(suggested),
1623
+ savedRunAt: suggested.toISOString(),
1624
+ }),
1625
+ prompt:
1626
+ mode === "webhook" && !current.prompt.trim()
1627
+ ? DEFAULT_WEBHOOK_PROMPT
1628
+ : current.prompt,
1629
+ };
1630
+ });
1631
}}
1632
>
1633
<Toggle value="fixed">At a time</Toggle>
1634
+ {offersOnce || draft.scheduleMode === "once" ? (
1635
+ <Toggle value="once">Once</Toggle>
1636
+ ) : null}
1637
<Toggle value="interval">Every interval</Toggle>
1638
<Toggle value="webhook">On webhook</Toggle>
1639
</ToggleGroup>
@@ -1769,6 +1811,20 @@ function ScheduledTaskEditorForm({
1811
</div>
1812
) : null}
1813
</div>
1814
+ ) : draft.scheduleMode === "once" ? (
1815
+ <div className="flex items-center gap-2">
1816
+ <Label htmlFor="scheduled-task-run-at">Run on</Label>
1817
+ <Input
1818
+ type="datetime-local"
1819
+ id="scheduled-task-run-at"
1820
+ nativeInput
1821
+ className="w-56"
1822
+ value={draft.runAt}
1823
+ onChange={(event) =>
1824
+ setDraft((current) => ({ ...current, runAt: event.target.value }))
1825
+ }
1826
+ />
1827
+ </div>
1828
) : draft.scheduleMode === "fixed" ? (
1829
<div className="flex flex-wrap items-center gap-3">
1830
<div className="flex items-center gap-2">
apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts
+37
-1
@@ -7,7 +7,7 @@ import {
7
ScheduledTaskId,
8
type ScheduledTask,
9
} from "@t3tools/contracts";
10
-import { describe, expect, it } from "vite-plus/test";
10
+import { afterEach, describe, expect, it, vi } from "vite-plus/test";
11
12
import type {
13
SidebarProjectGroupMember,
@@ -170,6 +170,42 @@ describe("editing scheduled task branch settings", () => {
170
});
171
});
172
173
+describe("one-time scheduled tasks", () => {
174
+ afterEach(() => vi.unstubAllEnvs());
175
+
176
+ it("round-trips the run time through the local date-time input", () => {
177
+ const runAt = "2026-11-03T17:00:42.000Z";
178
+ const draft = taskToDraft({ ...legacyTask, schedule: { type: "once", runAt } });
179
+ expect(draft.scheduleMode).toBe("once");
180
+ expect(scheduleFromDraft(draft)).toEqual({ type: "once", runAt });
181
+ const moved = scheduleFromDraft({ ...draft, runAt: "2026-11-04T09:30" });
182
+ expect(moved).toEqual({ type: "once", runAt: new Date("2026-11-04T09:30").toISOString() });
183
+ expect(scheduleFromDraft({ ...draft, runAt: "" })).toBeNull();
184
+ });
185
+
186
+ it("rejects a time skipped by daylight saving", () => {
187
+ vi.stubEnv("TZ", "America/Los_Angeles");
188
+ const draft = taskToDraft({
189
+ ...legacyTask,
190
+ schedule: { type: "once", runAt: "2027-03-14T18:00:00.000Z" },
191
+ });
192
+ expect(scheduleFromDraft({ ...draft, runAt: "2027-03-14T02:30" })).toBeNull();
193
+ });
194
+
195
+ it("keeps the saved offset when an edit stays in an hour that repeats", () => {
196
+ vi.stubEnv("TZ", "America/Los_Angeles");
197
+ // 01:30 PST, the second 01:30 on 2026-11-01.
198
+ const draft = taskToDraft({
199
+ ...legacyTask,
200
+ schedule: { type: "once", runAt: "2026-11-01T09:30:00.000Z" },
201
+ });
202
+ expect(scheduleFromDraft({ ...draft, runAt: "2026-11-01T01:35" })).toEqual({
203
+ type: "once",
204
+ runAt: "2026-11-01T09:35:00.000Z",
205
+ });
206
+ });
207
+});
208
+
209
describe("webhook scheduled tasks", () => {
210
const signature = { header: "x-signature", encoding: "base64", prefix: "" } as const;
211
const webhookTask: ScheduledTask = {
apps/web/src/components/settings/scheduledTasksSettings.logic.ts
+45
-5
@@ -52,7 +52,7 @@ export function validateScheduledTasksSearch(raw: Record<string, unknown>) {
52
};
53
}
54
55
-export type ScheduleMode = "fixed" | "interval" | "webhook";
55
+export type ScheduleMode = "fixed" | "once" | "interval" | "webhook";
56
export type WorkspaceMode = "root" | "worktree" | "existing_worktree";
57
58
export interface DraftState {
@@ -63,6 +63,10 @@ export interface DraftState {
63
readonly scheduleMode: ScheduleMode;
64
readonly intervalMinutes: string;
65
readonly timeOfDay: string;
66
+ /** Local date and time as a `datetime-local` input value, such as 2026-11-02T15:00. */
67
+ readonly runAt: string;
68
+ /** The stored ISO run time, sent back unchanged when the field was not edited. */
69
+ readonly savedRunAt: string;
70
readonly weekdays: ReadonlySet<number>;
71
readonly projectId: string;
72
readonly threadId: string;
@@ -96,7 +100,24 @@ export const WEBHOOK_SIGNATURE_DEFAULTS = {
100
signaturePrefix: "sha256=",
101
} as const;
102
99
-export function webhookDraftErrors(draft: DraftState) {
103
+/** Formats a date as a `datetime-local` input value in the browser's time zone. */
104
+export function toDateTimeLocalValue(date: Date): string {
105
+ const pad = (value: number) => String(value).padStart(2, "0");
106
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
107
+}
108
+
109
+export function scheduleDraftErrors(draft: DraftState) {
110
+ if (draft.scheduleMode === "once") {
111
+ const runAt = new Date(draft.runAt);
112
+ if (Number.isNaN(runAt.getTime()))
113
+ return [{ title: "Invalid run time", description: "Pick a date and time." }];
114
+ // A time skipped by a daylight saving change parses to a different clock time.
115
+ if (toDateTimeLocalValue(runAt) !== draft.runAt)
116
+ return [
117
+ { title: "Invalid run time", description: "That time does not exist in your time zone." },
118
+ ];
119
+ return [];
120
+ }
121
if (draft.scheduleMode !== "webhook") return [];
122
if (parseMaxDeliveryAge(draft.maxDeliveryAgeMinutes) === undefined)
123
return [
@@ -144,8 +165,26 @@ export function webhookDeliveryLabel(delivery: {
165
}
166
167
export function scheduleFromDraft(draft: DraftState): ScheduledTaskUpsertSchedule | null {
168
+ if (scheduleDraftErrors(draft).length > 0) return null;
169
+ if (draft.scheduleMode === "once") {
170
+ const saved = draft.savedRunAt ? new Date(draft.savedRunAt) : null;
171
+ if (saved !== null && toDateTimeLocalValue(saved) === draft.runAt)
172
+ return { type: "once", runAt: draft.savedRunAt };
173
+ // A `datetime-local` value has no offset. In an hour that repeats when clocks go
174
+ // back, keep the saved time's offset; otherwise Date reads it as local time.
175
+ const withSavedOffset =
176
+ saved === null
177
+ ? null
178
+ : new Date(Date.parse(`${draft.runAt}Z`) + saved.getTimezoneOffset() * 60_000);
179
+ return {
180
+ type: "once",
181
+ runAt:
182
+ withSavedOffset !== null && toDateTimeLocalValue(withSavedOffset) === draft.runAt
183
+ ? withSavedOffset.toISOString()
184
+ : new Date(draft.runAt).toISOString(),
185
+ };
186
+ }
187
if (draft.scheduleMode === "webhook") {
148
- if (webhookDraftErrors(draft).length > 0) return null;
188
const maxDeliveryAgeMinutes = parseMaxDeliveryAge(draft.maxDeliveryAgeMinutes);
189
const replayKey = draft.replayKey.trim();
190
const coalesceKey = draft.coalesceKey.trim();
@@ -206,11 +245,12 @@ export function taskToDraft(task: ScheduledTask): DraftState {
245
title: task.title,
246
prompt: task.prompt,
247
enabled: task.enabled,
209
- scheduleMode:
210
- schedule.type === "interval" ? "interval" : schedule.type === "webhook" ? "webhook" : "fixed",
248
+ scheduleMode: schedule.type === "fixed_time" ? "fixed" : schedule.type,
249
intervalMinutes:
250
schedule.type === "interval" ? String(Math.max(1, schedule.everyMs / 60_000)) : "15",
251
timeOfDay: schedule.type === "fixed_time" ? schedule.timeOfDay : "09:00",
252
+ runAt: schedule.type === "once" ? toDateTimeLocalValue(new Date(schedule.runAt)) : "",
253
+ savedRunAt: schedule.type === "once" ? schedule.runAt : "",
254
weekdays,
255
projectId: task.projectId,
256
threadId: task.threadId ?? "",
docs/user/project-settings.md
+4
-2
@@ -78,11 +78,13 @@ branch name remains.
78
79
## Scheduled tasks on mobile
80
81
-Open **Settings → Scheduled tasks** to create recurring tasks or manage existing
81
+Open **Settings → Scheduled tasks** to create scheduled tasks or manage existing
82
ones across your connected environments. Use the settings filter to narrow the
83
list by environment or project. Each task runs on the environment you choose,
84
using its project, model, and workspace settings. Fixed-time schedules use that
85
-environment's time zone, which may differ from your phone's.
85
+environment's time zone, which may differ from your phone's. Choose **Once**
86
+to run a task a single time at a date and time in your own time zone. If the
87
+environment is offline then, the task runs when it is back.
88
89
Deleting a thread also deletes tasks that post into that thread. Tasks that start
90
a new thread on each run survive deletion of their previous threads.
evals/mcp-tool-use/cases/pull-requests.ndjson
+2
-1
@@ -21,7 +21,7 @@
21
{"id": "stack-links-every-layer", "area": "pull-requests", "kind": "guard", "pattern": "stacked PRs: every layer ends up linked", "experience": "Must keep working: for a 2-PR stack, both layers end up linked, not only the top.", "rule": "For a stack, call it for every layer, not just the current branch or the top PR.", "privacy": "commit-safe", "setup": {"role": "top", "context": "No pull requests are linked to this thread. Branch feature/error-detail (on main) and branch feature/frozen-host (on top of feature/error-detail) are committed locally. Nothing is pushed yet.", "mocks": {"link_pull_request": "default"}, "world": {"branch": "feature/frozen-host", "branches": {"feature/error-detail": "e1d2c3b"}, "commits": [{"sha": "f7e6d5c", "subject": "feat(server): detect a frozen host and say so"}, {"sha": "e1d2c3b", "subject": "feat(server): include the failing step in connection errors"}], "nextPullRequests": "The next pull request created on acme/app is #124, and the one after it is #125."}, "shellMocks": [{"match": "gh pr create.*(--base|-B)[= ]['\"]?main\\b", "output": "https://github.com/acme/app/pull/124"}, {"match": "gh pr create.*(--base|-B)[= ]['\"]?feature/error-detail\\b", "output": "https://github.com/acme/app/pull/125"}]}, "prompt": "Open both as stacked PRs: feature/error-detail against main, and feature/frozen-host on top of it.", "expect": {"linked": ["~/pull/124", "~/pull/125"]}, "notes": "No real 'only the top layer linked' miss exists after v2 (checked all stacked creates since Oct 2). The real run used watch because of 'Full stop'. Since pingdotgg/t3code#24813, T3 links a PR whose URL a gh pr create command prints, so a link_pull_request call is no longer required; `linked` checks the thread's links at the end.", "maxSteps": 10}
22
{"id": "takeover-links-pr", "area": "pull-requests", "kind": "guard", "pattern": "takeover of a pasted PR links it", "experience": "Must keep working: on 'take over this PR and get it in', link the pasted PR before working on it.", "rule": "register every pull request you create or work on for this thread", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"link_pull_request": "default", "watch_pull_request": "default"}, "context": "This worktree has the PR's branch fix/config-snapshot checked out.", "world": {"branch": "fix/config-snapshot", "commits": [{"sha": "abc1234", "subject": "fix(server): stream config snapshots so slow ones keep the socket alive"}], "diff": "diff --git a/apps/server/src/config/snapshot.ts b/apps/server/src/config/snapshot.ts\n--- a/apps/server/src/config/snapshot.ts\n+++ b/apps/server/src/config/snapshot.ts\n@@ -1,6 +1,8 @@\n-import { buildSnapshot, streamSnapshot } from './build';\n+import { streamSnapshot } from './build';\n \n export async function sendSnapshot(socket: Socket, config: Config) {\n- const snapshot = await buildSnapshot(config);\n- socket.send(snapshot);\n+ // Send in chunks so a slow snapshot never blocks the heartbeat.\n+ for await (const chunk of streamSnapshot(config)) {\n+ socket.send(chunk);\n+ }\n }\n", "files": {"apps/server/src/config/snapshot.ts": "import { streamSnapshot } from './build';\n\nexport async function sendSnapshot(socket: Socket, config: Config) {\n // Send in chunks so a slow snapshot never blocks the heartbeat.\n for await (const chunk of streamSnapshot(config)) {\n socket.send(chunk);\n }\n}\n", "apps/server/src/config/build.ts": "export async function buildSnapshot(config: Config) {\n return JSON.stringify(config);\n}\n\nexport async function* streamSnapshot(config: Config) {\n for (const [key, value] of Object.entries(config)) yield JSON.stringify({ key, value });\n}\n"}, "prs": [{"number": 123, "title": "fix(server): slow config snapshots no longer drop connections", "headRefName": "fix/config-snapshot", "checks": [{"name": "Lint", "state": "pass"}, {"name": "Typecheck", "state": "pass"}, {"name": "Check", "state": "pending"}, {"name": "Test Web", "state": "pending"}], "author": {"login": "contributor"}}]}}, "prompt": "https://github.com/acme/app/pull/123\n\nThis looks legit. Take over and get it in.", "expect": {"calls": [{"tool": "link_pull_request|watch_pull_request", "args": {"url": "~/pull/123"}}]}, "notes": "A run that calls watch_pull_request first (which also links) would fail this check. If the runner treats watch as a link, relax it.", "maxSteps": 14}
23
{"id": "handback-unwatches", "area": "pull-requests", "kind": "guard", "pattern": "unwatch before handing back", "experience": "Must keep working: when the babysit goal is met and the user merges, call unwatch_pull_request before the hand-back reply.", "rule": "When monitoring is done and you hand the work back to the user, call unwatch_pull_request first", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "Make CI setup survive npm registry outages, then open a PR. You are done when CI on the PR is green. I will merge it myself."}, {"role": "assistant", "text": "Opened [#124](https://github.com/acme/app/pull/124). T3 Code is watching it; I will report when CI is green.", "toolCalls": [{"tool": "Edit", "input": {"file_path": "/home/user/.t3/worktrees/t3code/t3-f8cdd940/.github/workflows/ci.yml", "old_string": " - run: pnpm install", "new_string": " - run: pnpm install || pnpm install --registry https://registry.npmmirror.com"}, "result": "The file /home/user/.t3/worktrees/t3code/t3-f8cdd940/.github/workflows/ci.yml has been updated successfully."}, {"tool": "Bash", "input": {"command": "git add -A && git commit -m \"ci: fall back to the registry mirror when npm is down\""}, "result": "[ci/npm-outage abc1234] ci: fall back to the registry mirror when npm is down\n 1 file changed"}, {"tool": "Bash", "input": {"command": "git push -u origin ci/npm-outage"}, "result": "To github.com:acme/app.git\n * [new branch] ci/npm-outage -> ci/npm-outage\nbranch 'ci/npm-outage' set up to track 'origin/ci/npm-outage'."}, {"tool": "Bash", "input": {"command": "gh pr create --base main --title \"ci: fall back to the registry mirror when npm is down\" --fill"}, "result": "https://github.com/acme/app/pull/124"}, {"tool": "link_pull_request", "input": {"url": "https://github.com/acme/app/pull/124"}, "result": {"host": "github.com", "repository": "acme/app", "number": 124, "url": "https://github.com/acme/app/pull/124", "alreadyLinked": false}}, {"tool": "watch_pull_request", "input": {"url": "https://github.com/acme/app/pull/124"}, "result": {"host": "github.com", "repository": "acme/app", "number": 124, "url": "https://github.com/acme/app/pull/124", "watching": true, "wasWatching": false}}]}], "mocks": {"unwatch_pull_request": "default"}, "world": {"branch": "ci/npm-outage", "commits": [{"sha": "abc1234", "subject": "ci: fall back to the registry mirror when npm is down"}], "diff": "diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml\n--- a/.github/workflows/ci.yml\n+++ b/.github/workflows/ci.yml\n@@ -8,1 +8,1 @@\n- - run: pnpm install\n+ - run: pnpm install || pnpm install --registry https://registry.npmmirror.com\n", "prs": [{"number": 124, "title": "ci: fall back to the registry mirror when npm is down", "headRefName": "ci/npm-outage", "checks": [{"name": "Lint", "state": "pass"}, {"name": "Typecheck", "state": "pass"}, {"name": "Test", "state": "pass"}]}]}}, "prompt": "Update on pull request #124 (https://github.com/acme/app/pull/124), which T3 Code is watching for you:\n- All 12 checks passed on abc1234.\n\nLook into each item and act on it as your task requires. This PR stays linked and watched, so do not link, watch, or list it again. End your turn when you are done, and T3 Code wakes you on the next change. When you hand the work back to the user, call unwatch_pull_request first so the thread returns to their inbox.", "expect": {"calls": [{"tool": "unwatch_pull_request", "args": {"url": "~/pull/124"}}], "notCalls": ["watch_pull_request"], "shellMustNot": ["gh pr merge"]}, "notes": "Unwatch was followed 7 of 7 times after the fixes. No real 'forgot to unwatch' miss was found, so this is a guard, not a bad case.", "maxSteps": 7}
24
-{"id": "schedule-one-off-tomorrow", "area": "pull-requests", "kind": "guard", "pattern": "schedule asked: schedule_task, not the job", "experience": "Must keep working: a schedule ask creates a schedule_task with an object schedule and reports the next run, without running the check now.", "rule": "schedule_task creates persistent recurring work in the app scheduler. Pass schedule as a structured object / After scheduling a timer, report the returned cadence and next run time", "privacy": "commit-safe", "setup": {"role": "top", "context": "Today is Saturday 2026-10-24, 10:00 local time.", "mocks": {"schedule_task": {"scheduledTaskId": "scheduled-task-4", "title": "Check app for memory leaks", "schedule": {"type": "fixed_time", "timeOfDay": "23:00", "weekdays": [0]}, "enabled": true, "bindToCurrentThread": true, "nextRunAt": "2026-10-25T23:00:00-07:00"}}, "shellMocks": [{"match": "\\bdate\\b", "output": "Saturday 2026-10-24 10:00 PDT"}]}, "prompt": "Definitely want to schedule something to check the app for memory leaks at some point tomorrow, maybe like 11pm?", "expect": {"calls": [{"tool": "schedule_task"}], "notCalls": ["delegate_task", "run_scheduled_task_now"], "textMust": ["(11(:00)? ?[Pp]\\.?[Mm]|23:00)"]}, "notes": "No one-shot schedule type exists, so a weekly fixed_time plus a later delete is the accepted pattern."}
24
+{"id": "schedule-one-off-tomorrow", "area": "pull-requests", "kind": "guard", "pattern": "schedule asked: schedule_task, not the job", "experience": "Must keep working: a schedule ask creates a schedule_task with an object schedule and reports the next run, without running the check now.", "rule": "schedule_task creates persistent recurring work in the app scheduler. Pass schedule as a structured object / After scheduling a timer, report the returned cadence and next run time", "privacy": "commit-safe", "setup": {"role": "top", "context": "Today is Saturday 2026-10-24, 10:00 local time.", "mocks": {"schedule_task": {"scheduledTaskId": "scheduled-task-4", "title": "Check app for memory leaks", "schedule": {"type": "once", "runAt": "2026-10-25T23:00:00-07:00"}, "enabled": true, "bindToCurrentThread": true, "nextRunAt": "2026-10-25T23:00:00-07:00"}}, "shellMocks": [{"match": "\\bdate\\b", "output": "Saturday 2026-10-24 10:00 PDT"}]}, "prompt": "Definitely want to schedule something to check the app for memory leaks at some point tomorrow, maybe like 11pm?", "expect": {"calls": [{"tool": "schedule_task", "args": {"schedule.type": "once"}}], "notCalls": ["delegate_task", "run_scheduled_task_now"], "textMust": ["(11(:00)? ?[Pp]\\.?[Mm]|23:00)"]}, "notes": "A one-off time uses a once schedule. Before once existed, a weekly fixed_time plus a later delete was accepted."}
25
{"id": "control-pr-lookup-question", "area": "pull-requests", "kind": "control", "pattern": "PRs named only as background in a question", "experience": "Asking about PRs must not link, watch, or list them.", "rule": "Do not link unrelated PRs mentioned only as background.", "privacy": "commit-safe", "setup": {"role": "top", "world": {"prs": [{"number": 101, "title": "fix(web): small UI fix", "state": "MERGED", "diff": "diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx\n--- a/apps/web/src/components/Sidebar.tsx\n+++ b/apps/web/src/components/Sidebar.tsx\n@@ -10,1 +10,1 @@\n- <span>{title}</span>\n+ <span className=\"truncate\">{title}</span>\n"}, {"number": 102, "title": "fix(ws): cap reconnect backoff at 30s", "state": "MERGED", "diff": "diff --git a/apps/web/src/ws/backoff.ts b/apps/web/src/ws/backoff.ts\n--- a/apps/web/src/ws/backoff.ts\n+++ b/apps/web/src/ws/backoff.ts\n@@ -4,1 +4,1 @@\n- return Math.min(base * 2 ** attempt, 60_000);\n+ return Math.min(base * 2 ** attempt, 30_000);\n"}, {"number": 103, "title": "chore: update dependencies", "state": "MERGED", "diff": "diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml\n--- a/pnpm-lock.yaml\n+++ b/pnpm-lock.yaml\n@@ -120,1 +120,1 @@\n- vitest: 4.0.1\n+ vitest: 4.0.3\n"}]}}, "prompt": "Did any of #101, #102, or #103 touch the reconnect backoff logic?", "expect": {"notCalls": ["link_pull_request", "link_pull_requests", "watch_pull_request", "list_thread_pull_requests", "unlink_pull_request"]}, "notes": ""}
26
{"id": "control-link-means-url", "area": "pull-requests", "kind": "control", "pattern": "'link the PR' means show the URL", "experience": "'Link the PR that did this' about a merged culprit PR means give the URL in the reply, not link_pull_request.", "rule": "Do not link unrelated PRs mentioned only as background.", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "Why isn't the new thread selector grouping projects anymore?"}, {"role": "assistant", "text": "#120, merged yesterday, removed the grouping step when it moved the selector to the new list component.", "toolCalls": [{"tool": "Bash", "input": {"command": "git log --oneline -S groupByProject -- apps/web/src/ThreadSelector.tsx"}, "result": "8e1f2a3 refactor(web): move thread selector to the shared list (#120)"}, {"tool": "Bash", "input": {"command": "git show 8e1f2a3 --stat"}, "result": "commit 8e1f2a3\n\n refactor(web): move thread selector to the shared list (#120)\n\n apps/web/src/ThreadSelector.tsx | 14 ++------------"}]}], "world": {"prs": [{"number": 120, "title": "refactor(web): move thread selector to the shared list", "state": "MERGED", "headRefName": "refactor/selector"}]}}, "prompt": "Link the pr that did this", "expect": {"notCalls": ["link_pull_request", "link_pull_requests", "watch_pull_request"], "textMust": ["github\\.com/acme/app/pull/120"]}, "notes": "Least certain control: 'link' is ambiguous. The user's next message was 'File revert pr', which shows he wanted to see it, not track it."}
27
{"id": "control-nightly-time-question", "area": "pull-requests", "kind": "control", "pattern": "question about a CI schedule is not a schedule ask", "experience": "'When does the next nightly go out?' is answered from the workflow file, with no scheduler tools.", "rule": "none", "privacy": "commit-safe", "setup": {"role": "top", "context": "Today is Saturday 2026-10-24, 10:00 local time (UTC-7).", "shellMocks": [{"match": "^date\\b", "output": "Sat Oct 24 10:00:00 PDT 2026"}, {"match": "gh run list", "output": "completed\tsuccess\tnightly\tmain\tschedule\t991\t21m\t2026-10-24T09:00:00Z"}], "world": {"files": {".github/workflows/nightly.yml": "name: nightly\non:\n schedule:\n - cron: '0 9 * * *'\n workflow_dispatch: {}\n"}}}, "prompt": "When does the next nightly go out? Want to start testing this asap", "expect": {"notCalls": ["schedule_task", "list_scheduled_tasks", "run_scheduled_task_now"]}, "notes": ""}
@@ -34,3 +34,4 @@
34
{"id": "link-stacked-prs", "area": "pull-requests", "privacy": "commit-safe", "kind": "bad", "pattern": "links many PRs one call at a time", "experience": "Asked to link every PR of a stack so it shows in T3 Code, the agent called link_pull_request once per PR.", "rule": "link_pull_request takes one PR per call", "setup": {"role": "top", "context": "No pull requests are linked to this thread.", "world": {"repo": "acme/app", "branch": "t3/stack-14"}, "shellMocks": [{"match": "gh stack view|gh pr list", "output": "#201 feat: stack layer 1 t3/stack-1\n#202 feat: stack layer 2 t3/stack-2\n#203 feat: stack layer 3 t3/stack-3\n#204 feat: stack layer 4 t3/stack-4\n#205 feat: stack layer 5 t3/stack-5\n#206 feat: stack layer 6 t3/stack-6\n#207 feat: stack layer 7 t3/stack-7\n#208 feat: stack layer 8 t3/stack-8\n#209 feat: stack layer 9 t3/stack-9\n#210 feat: stack layer 10 t3/stack-10\n#211 feat: stack layer 11 t3/stack-11\n#212 feat: stack layer 12 t3/stack-12\n#213 feat: stack layer 13 t3/stack-13\n#214 feat: stack layer 14 t3/stack-14"}]}, "prompt": "oh also, can you link all of the stacked prs into this thread? just so i can see them in t3code. `gh stack view` lists them.", "expect": {"calls": [{"tool": "link_pull_requests"}], "linked": ["~/pull/201", "~/pull/202", "~/pull/203", "~/pull/204", "~/pull/205", "~/pull/206", "~/pull/207", "~/pull/208", "~/pull/209", "~/pull/210", "~/pull/211", "~/pull/212", "~/pull/213", "~/pull/214"], "maxCalls": {"link_pull_requests": 1, "link_pull_request": 0}}, "maxSteps": 10, "source": {"thread": "Maintainer thread, 2026-10-05: 'can you link all of the stacked prs into this thread?' The agent linked 14 PRs one call each; another run linked 58."}}
35
{"id": "link-pasted-prs", "area": "pull-requests", "privacy": "commit-safe", "kind": "bad", "pattern": "links many PRs one call at a time", "experience": "Given a list of PR URLs to link, the agent linked them one call each.", "rule": "link_pull_request takes one PR per call", "setup": {"role": "top", "context": "No pull requests are linked to this thread.", "world": {"repo": "acme/app", "branch": "main"}}, "prompt": "link these here so i can track them:\nhttps://github.com/acme/app/pull/301\nhttps://github.com/acme/app/pull/302\nhttps://github.com/acme/app/pull/303\nhttps://github.com/acme/app/pull/304\nhttps://github.com/acme/app/pull/305\nhttps://github.com/acme/app/pull/306\nhttps://github.com/acme/app/pull/307\nhttps://github.com/acme/app/pull/308\nhttps://github.com/acme/app/pull/309\nhttps://github.com/acme/app/pull/310\nhttps://github.com/acme/app/pull/311\nhttps://github.com/acme/app/pull/312", "expect": {"calls": [{"tool": "link_pull_requests"}], "linked": ["~/pull/301", "~/pull/302", "~/pull/303", "~/pull/304", "~/pull/305", "~/pull/306", "~/pull/307", "~/pull/308", "~/pull/309", "~/pull/310", "~/pull/311", "~/pull/312"], "maxCalls": {"link_pull_requests": 1, "link_pull_request": 0}}, "maxSteps": 10, "source": {"thread": "Maintainer thread, 2026-10-05: 'can you link all of the stacked prs into this thread?' The agent linked 14 PRs one call each; another run linked 58."}}
36
{"id": "link-one-pr", "area": "pull-requests", "privacy": "commit-safe", "kind": "control", "pattern": "single link stays single", "experience": "Linking one named PR is ordinary work.", "setup": {"role": "top", "context": "No pull requests are linked to this thread.", "world": {"repo": "acme/app", "branch": "main"}}, "prompt": "link https://github.com/acme/app/pull/130 here", "expect": {"calls": [{"tool": "link_pull_request", "args": {"url": "~/pull/130"}}], "notCalls": ["link_pull_requests"]}, "maxSteps": 6, "source": {"thread": "Synthetic control for batch link"}}
37
+{"id": "schedule-one-time-date", "area": "pull-requests", "kind": "bad", "pattern": "one-off date scheduled as a daily task", "experience": "Theo asked whether a scheduled task can run at a specific date and time. schedule_task only had daily times, intervals, and webhooks, so a one-off request became a daily task.", "source": {"report": "maintainer request, 2026-10-31: scheduled tasks could not run at one date and time"}, "rule": "schedule: {type:'once',runAt} for one date and time", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"schedule_task": {"scheduledTaskId": "scheduled-task-4", "title": "Cut 2.0 release branch", "schedule": {"type": "once", "runAt": "2026-11-03T09:00:00.000Z"}, "enabled": true, "nextRunAt": "2026-11-03T09:00:00.000Z"}}}, "prompt": "On November 3rd at 9am UTC, start a new thread that cuts the 2.0 release branch from main in acme/app. Only that one time.", "expect": {"calls": [{"tool": "schedule_task", "args": {"schedule.type": "once", "schedule.runAt": "~11-03T09:00"}}], "notCalls": ["delegate_task", "run_scheduled_task_now"]}, "notes": "Mock result shape is an approximation."}
packages/contracts/src/environment.ts
+2
@@ -161,6 +161,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
161
linkFence: Schema.optionalKey(Schema.Boolean),
162
/** Server answers server.prepareTriage. */
163
triage: Schema.optionalKey(Schema.Boolean),
164
+ /** Server accepts `{ type: "once" }` scheduled tasks; older servers reject them on save. */
165
+ oneTimeSchedules: Schema.optionalKey(Schema.Boolean),
166
});
167
export type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type;
168
packages/contracts/src/orchestratorMcp.ts
+1
-1
@@ -67,7 +67,7 @@ const OrchestratorMcpSchedule = Schema.Union([
67
OrchestratorMcpScheduleFromJsonString,
68
]).annotate({
69
description:
70
- "Trigger: {type:'interval',everyMs}, {type:'fixed_time',timeOfDay,weekdays?}, or {type:'webhook'}.",
70
+ "Trigger: {type:'interval',everyMs}, {type:'fixed_time',timeOfDay,weekdays?}, {type:'once',runAt}, or {type:'webhook'}.",
71
});
72
73
const OrchestratorMcpTargetOptionsFromRecord = Schema.Record(
packages/contracts/src/scheduledTask.test.ts
+16
@@ -22,6 +22,22 @@ describe("ScheduledTaskSchedule", () => {
22
everyMs: MIN_SCHEDULED_TASK_INTERVAL_MS - 1,
23
});
24
});
25
+
26
+ it("accepts a one-time run only with an offset", () => {
27
+ for (const runAt of ["2026-11-03T09:00Z", "2026-11-03T09:00:00.000-08:00"]) {
28
+ expect(decodeUpsertSchedule({ type: "once", runAt })).toEqual({ type: "once", runAt });
29
+ }
30
+ for (const runAt of [
31
+ "2026-11-03T09:00",
32
+ "2026-13-03T09:00Z",
33
+ "2026-02-30T09:00Z",
34
+ "9999-12-31T23:30-01:00",
35
+ "0000-01-01T00:00+00:01",
36
+ "tomorrow",
37
+ ]) {
38
+ expect(() => decodeUpsertSchedule({ type: "once", runAt })).toThrow();
39
+ }
40
+ });
41
});
42
43
it.each(["literal", " ", "\t\n", "{{body.bad", "{{unknown.field}}"])(
packages/contracts/src/scheduledTask.ts
+30
@@ -45,6 +45,34 @@ const ScheduledTaskFixedTimeSchedule = Schema.Struct({
45
),
46
});
47
48
+const ISO_WITH_OFFSET =
49
+ /^(\d{4})-(\d{2})-(\d{2})T([01]\d|2[0-3]):[0-5]\d(:[0-5]\d(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
50
+
51
+const YEAR_0000 = Date.parse("0000-01-01T00:00:00Z");
52
+const YEAR_10000 = Date.parse("+010000-01-01T00:00:00Z");
53
+
54
+/** Date.parse rolls impossible days like Feb 30 into the next month, so check the day too. */
55
+function isIsoWithOffset(value: string): boolean {
56
+ const match = ISO_WITH_OFFSET.exec(value);
57
+ // The server stores UTC, which must stay a four-digit year to decode again.
58
+ const time = Date.parse(value);
59
+ if (!match || !(time >= YEAR_0000 && time < YEAR_10000)) return false;
60
+ const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])];
61
+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
62
+ const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
63
+ return days !== undefined && day >= 1 && day <= days;
64
+}
65
+
66
+// Checked by filter, not pattern, to keep the MCP tool schema small.
67
+const ScheduledTaskOnceSchedule = Schema.Struct({
68
+ type: Schema.Literal("once"),
69
+ runAt: TrimmedNonEmptyString.check(
70
+ Schema.makeFilter(
71
+ (value) => isIsoWithOffset(value) || "Expected an ISO date and time with an offset.",
72
+ ),
73
+ ),
74
+});
75
+
76
const ScheduledTaskWebhookSignatureFields = {
77
header: TrimmedNonEmptyString.annotate({
78
description: "Header with the signature, such as x-hub-signature-256.",
@@ -166,6 +194,7 @@ const ScheduledTaskUpsertWebhookSchedule = Schema.Struct({
194
export const ScheduledTaskSchedule = Schema.Union([
195
ScheduledTaskIntervalSchedule,
196
ScheduledTaskFixedTimeSchedule,
197
+ ScheduledTaskOnceSchedule,
198
ScheduledTaskWebhookSchedule,
199
]);
200
export type ScheduledTaskSchedule = typeof ScheduledTaskSchedule.Type;
@@ -180,6 +209,7 @@ export const ScheduledTaskUpsertSchedule = Schema.Union([
209
}),
210
}),
211
ScheduledTaskFixedTimeSchedule,
212
+ ScheduledTaskOnceSchedule,
213
ScheduledTaskUpsertWebhookSchedule,
214
]);
215
export type ScheduledTaskUpsertSchedule = typeof ScheduledTaskUpsertSchedule.Type;
packages/shared/src/t3McpToolPresentation.ts
+1
-4
@@ -144,10 +144,7 @@ const T3_MCP_TOOLS: Readonly<Record<string, T3McpToolDefinition>> = {
144
["Cancel", "Canceling", "Requested cancellation of", "a delegated task"],
145
"task-cancel",
146
),
147
- schedule_task: tool(
148
- ["Schedule", "Scheduling", "Scheduled", "a recurring task"],
149
- "schedule-create",
150
- ),
147
+ schedule_task: tool(["Schedule", "Scheduling", "Scheduled", "a task"], "schedule-create"),
148
list_scheduled_tasks: tool(["List", "Listing", "Listed", "scheduled tasks"], "schedule-list"),
149
update_scheduled_task: tool(
150
["Update", "Updating", "Updated", "a scheduled task"],