Skip to content
TypeScript

feat(scheduler): run a scheduled task once at a specific date and time (#28104)

Theo Browne4ac97be2b67d
diff --git a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx
index 1af02becdc8..fdf352c2744 100644
--- a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx
@@ -109,6 +109,10 @@ const DAYS = [
function describeSchedule(task: ScheduledTask): string {
if (task.schedule.type === "webhook") return "On webhook";
+ if (task.schedule.type === "once") {
+ const runAt = new Date(task.schedule.runAt);
+ return `Once, ${formatRunAtDate(runAt)} at ${formatRunAtTime(runAt)}`;
+ }
if (task.schedule.type === "interval") return formatScheduledTaskInterval(task.schedule.everyMs);
const days = task.schedule.weekdays?.length ? repeatLabel(task.schedule.weekdays) : "Every day";
return `${days} at ${formatTime(task.schedule.timeOfDay)}`;
@@ -122,6 +126,14 @@ function formatTime(value: string): string {
return time.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
}
+function formatRunAtDate(value: Date): string {
+ return value.toLocaleDateString([], { month: "short", day: "numeric", year: "numeric" });
+}
+
+function formatRunAtTime(value: Date): string {
+ return value.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
+}
+
function timePickerValue(value: string): Date {
const [hours, minutes] = value.split(":").map(Number);
const time = new Date();
@@ -687,6 +699,7 @@ function TaskForm({
});
const submissionPending = useRef(false);
const [timePickerOpen, setTimePickerOpen] = useState(false);
+ const [runAtPicker, setRunAtPicker] = useState<"date" | "time" | null>(null);
const taskMissing =
draft.task !== null &&
tasks.data !== null &&
@@ -701,6 +714,9 @@ function TaskForm({
}
};
+ const offersOnce =
+ config?.environment.capabilities.oneTimeSchedules === true ||
+ draft.task?.schedule.type === "once";
const save = async () => {
if (
!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
@@ -728,6 +744,13 @@ function TaskForm({
);
return;
}
+ if (draft.schedule.mode === "once" && !offersOnce) {
+ Dialog.alert(
+ "Once is not available here",
+ "This environment runs an older T3 Code. Update it to schedule a one-time task, or pick another schedule.",
+ );
+ return;
+ }
const parsedFilters = parseWebhookFilterDrafts(draft.schedule.filters);
if (draft.schedule.mode === "webhook" && "error" in parsedFilters) {
Dialog.alert("Invalid filter", parsedFilters.error);
@@ -964,19 +987,31 @@ function TaskForm({
variant="card"
options={[
{ value: "fixed_time", label: "At a time" },
+ // Older servers reject one-time schedules on save.
+ ...(offersOnce || draft.schedule.mode === "once"
+ ? [{ value: "once" as const, label: "Once" }]
+ : []),
{ value: "interval", label: "Interval" },
{ value: "webhook", label: "On webhook" },
]}
selected={draft.schedule.mode}
onSelect={(mode) => {
setTimePickerOpen(false);
+ setRunAtPicker(null);
setDraft({
...draft,
prompt:
mode === "webhook" && !draft.prompt.trim()
? DEFAULT_WEBHOOK_PROMPT
: draft.prompt,
- schedule: { ...draft.schedule, mode },
+ schedule: {
+ ...draft.schedule,
+ mode,
+ runAt:
+ mode === "once" && !draft.schedule.runAt
+ ? new Date(Math.ceil(Date.now() / 3_600_000) * 3_600_000).toISOString()
+ : draft.schedule.runAt,
+ },
});
}}
/>
@@ -1058,6 +1093,53 @@ function TaskForm({
}}
/>
</>
+ ) : draft.schedule.mode === "once" ? (
+ (["date", "time"] as const).map((field) => {
+ const runAt = new Date(draft.schedule.runAt);
+ const label = field === "date" ? formatRunAtDate(runAt) : formatRunAtTime(runAt);
+ return (
+ <View key={field}>
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={`${field === "date" ? "Date" : "Time"}, ${label}`}
+ onPress={() => setRunAtPicker((open) => (open === field ? null : field))}
+ className="min-h-14 flex-row items-center gap-3 border-t border-border-subtle px-4 py-3 active:opacity-70"
+ >
+ <Text textRole="body" className="text-foreground">
+ {field === "date" ? "Date" : "Time"}
+ </Text>
+ <Text
+ textRole="footnote"
+ className="min-w-0 flex-1 text-right text-foreground-muted"
+ >
+ {label}
+ </Text>
+ <SymbolView
+ name="chevron.right"
+ size={14}
+ tintColorClassName="accent-chevron"
+ type="monochrome"
+ />
+ </Pressable>
+ {runAtPicker === field ? (
+ <DateTimePicker
+ value={runAt}
+ mode={field}
+ display={Platform.OS === "ios" ? "spinner" : "default"}
+ onDismiss={() => setRunAtPicker(null)}
+ onValueChange={(_, selected) => {
+ // Android shows a dialog that closes on pick; iOS stays inline.
+ if (Platform.OS === "android") setRunAtPicker(null);
+ setDraft({
+ ...draft,
+ schedule: { ...draft.schedule, runAt: selected.toISOString() },
+ });
+ }}
+ />
+ ) : null}
+ </View>
+ );
+ })
) : draft.schedule.mode === "webhook" ? (
<>
<WebhookScheduleDetails
diff --git a/apps/mobile/src/features/settings/scheduledTaskDraft.ts b/apps/mobile/src/features/settings/scheduledTaskDraft.ts
index 4ff15c4d9e4..d89b004a0dc 100644
--- a/apps/mobile/src/features/settings/scheduledTaskDraft.ts
+++ b/apps/mobile/src/features/settings/scheduledTaskDraft.ts
@@ -51,8 +51,10 @@ export function scheduledTaskDefaultModel(
}
export type ScheduleDraft = {
- readonly mode: "fixed_time" | "interval" | "webhook";
+ readonly mode: "fixed_time" | "once" | "interval" | "webhook";
readonly timeOfDay: string;
+ /** ISO time for a one-time run. Empty until the user picks the "Once" mode. */
+ readonly runAt: string;
readonly weekdays: ReadonlyArray<number>;
readonly intervalMinutes: string;
readonly signature: ScheduledTaskWebhookSignature | null;
@@ -68,6 +70,7 @@ export type ScheduleDraft = {
export const DEFAULT_SCHEDULE: ScheduleDraft = {
mode: "fixed_time",
timeOfDay: "09:00",
+ runAt: "",
weekdays: [1, 2, 3, 4, 5],
intervalMinutes: "15",
signature: null,
@@ -89,6 +92,8 @@ export function scheduleDraftForTask(task: Pick<ScheduledTask, "schedule">): Sch
? [...new Set(task.schedule.weekdays)].sort((a, b) => a - b)
: [0, 1, 2, 3, 4, 5, 6],
};
+ case "once":
+ return { ...DEFAULT_SCHEDULE, mode: "once", runAt: task.schedule.runAt };
case "interval":
return {
...DEFAULT_SCHEDULE,
@@ -166,6 +171,10 @@ export function scheduleFromDraft(draft: ScheduleDraft): ScheduledTaskUpsertSche
: {}),
};
}
+ if (draft.mode === "once") {
+ const runAt = new Date(draft.runAt);
+ return Number.isNaN(runAt.getTime()) ? null : { type: "once", runAt: runAt.toISOString() };
+ }
if (draft.mode === "interval") {
const minutes = parseIntervalMinutes(draft.intervalMinutes);
const everyMs = Math.round(minutes * 60_000);
@@ -215,6 +224,7 @@ function draftSignature(draft: ScheduledTaskDraft): string {
.map((option) => [option.id, option.value]),
draft.schedule.mode,
draft.schedule.timeOfDay,
+ draft.schedule.runAt,
[...draft.schedule.weekdays].sort((a, b) => a - b),
draft.schedule.intervalMinutes,
draft.schedule.maxDeliveryAgeMinutes,
diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts
index 72d7f0c2de7..d542b4ee55b 100644
--- a/apps/server/src/environment/ServerEnvironment.ts
+++ b/apps/server/src/environment/ServerEnvironment.ts
@@ -267,6 +267,7 @@ export const make = Effect.gen(function* () {
projectOrganization: true,
ignoredFileListing: true,
triage: true,
+ oneTimeSchedules: true,
npmReleaseLookup: true,
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
...(serverInstallation === null ? {} : { serverInstallation }),
diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts
index 413ab984211..7c05f5c8d8e 100644
--- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts
+++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts
@@ -165,7 +165,7 @@ const ScheduleTaskTool = Tool.make("schedule_task", {
failureMode: "return",
dependencies,
})
- .annotate(Tool.Title, "Schedule a recurring task")
+ .annotate(Tool.Title, "Schedule a task")
.annotate(Tool.Destructive, true)
.annotate(Tool.OpenWorld, true);
diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json
index 8f73039d971..3e1e5dc80f7 100644
--- a/apps/server/src/provider/agentContextBudget.json
+++ b/apps/server/src/provider/agentContextBudget.json
@@ -1,5 +1,5 @@
{
"claudeSystemAppendBytes": 5153,
"codexAdditionalContextBytes": 6883,
- "mcpToolListJsonBytes": 47020
+ "mcpToolListJsonBytes": 47074
}
diff --git a/apps/server/src/scheduledTasks/Schedule.test.ts b/apps/server/src/scheduledTasks/Schedule.test.ts
index f5973969747..0941c7392ff 100644
--- a/apps/server/src/scheduledTasks/Schedule.test.ts
+++ b/apps/server/src/scheduledTasks/Schedule.test.ts
@@ -27,6 +27,12 @@ describe("scheduled task schedule calculation", () => {
});
it("compares schedules structurally", () => {
+ expect(
+ isSameSchedule(
+ { type: "once", runAt: "2026-11-01T03:00:00-05:00" },
+ { type: "once", runAt: "2026-11-01T08:00:00.000Z" },
+ ),
+ ).toBe(true);
expect(
isSameSchedule({ type: "interval", everyMs: 60_000 }, { type: "interval", everyMs: 60_000 }),
).toBe(true);
diff --git a/apps/server/src/scheduledTasks/Schedule.ts b/apps/server/src/scheduledTasks/Schedule.ts
index bac32bb9131..f8fb648aaaa 100644
--- a/apps/server/src/scheduledTasks/Schedule.ts
+++ b/apps/server/src/scheduledTasks/Schedule.ts
@@ -1,5 +1,6 @@
import { MIN_SCHEDULED_TASK_INTERVAL_MS, type ScheduledTaskSchedule } from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
+import * as Option from "effect/Option";
const MINUTE_MS = 60_000;
@@ -14,6 +15,13 @@ export function nextScheduledRunAt(
from: DateTime.DateTime,
): DateTime.DateTime | null {
if (schedule.type === "webhook") return null;
+ if (schedule.type === "once") {
+ const runAt = DateTime.make(schedule.runAt);
+ return Option.isSome(runAt) &&
+ DateTime.toEpochMillis(runAt.value) > DateTime.toEpochMillis(from)
+ ? runAt.value
+ : null;
+ }
if (schedule.type === "interval") {
// Intervals advance elapsed time, including across daylight-saving changes.
return DateTime.addDuration(from, Math.max(schedule.everyMs, MIN_SCHEDULED_TASK_INTERVAL_MS));
@@ -48,6 +56,7 @@ export function isSameSchedule(a: ScheduledTaskSchedule, b: ScheduledTaskSchedul
return b.type === "interval" && a.everyMs === b.everyMs;
}
if (a.type === "webhook") return b.type === "webhook";
+ if (a.type === "once") return b.type === "once" && Date.parse(a.runAt) === Date.parse(b.runAt);
if (b.type !== "fixed_time") return false;
// Compare parsed times so padded-hour edits do not reschedule pending runs.
const aTime = parseTimeOfDay(a.timeOfDay);
diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.interval.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.interval.test.ts
index 4a1a58505c5..c2cc1f382b6 100644
--- a/apps/server/src/scheduledTasks/ScheduledTaskService.interval.test.ts
+++ b/apps/server/src/scheduledTasks/ScheduledTaskService.interval.test.ts
@@ -4,6 +4,7 @@ import { ScheduledTaskUpsertInput } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
+import * as SqlClient from "effect/sql/SqlClient";
import * as TestClock from "effect/testing/TestClock";
import { afterEach, vi } from "vite-plus/test";
@@ -129,3 +130,185 @@ it.effect.each([
Effect.provide(SqlitePersistence.layerMemory),
),
);
+
+// Each launch takes two minutes, so a manual run can start before the run time and end after it.
+const slowLaunchLayer = ScheduledTaskService.layer.pipe(
+ Layer.provide(
+ Layer.merge(
+ dependencies,
+ Layer.mock(ThreadLaunchService.ThreadLaunchService)({
+ launch: () => TestClock.adjust("2 minutes").pipe(Effect.andThen(Effect.die("synthetic"))),
+ }),
+ ),
+ ),
+);
+
+it.effect("runs a one-time schedule once and rejects past times", () =>
+ Effect.gen(function* () {
+ yield* TestClock.setTime(Date.parse("2026-11-01T07:59:00.000Z"));
+ yield* Effect.gen(function* () {
+ const service = yield* ScheduledTaskService.ScheduledTaskService;
+ const decoded = yield* decodeInput({
+ ...input,
+ schedule: { type: "once", runAt: "2026-11-01T03:00:00-05:00" },
+ });
+ const created = yield* service.upsert(decoded);
+ expect(created.task.schedule).toEqual({ type: "once", runAt: "2026-11-01T08:00:00.000Z" });
+ expect(created.task.nextRunAt).toBe("2026-11-01T08:00:00.000Z");
+
+ // A manual run that starts before the time keeps the scheduled run, even if it ends after.
+ const early = yield* service.runNow({ id: created.task.id });
+ expect(early.task.nextRunAt).toBe("2026-11-01T08:00:00.000Z");
+
+ const due = yield* service.runNow({ id: created.task.id });
+ expect(due.task.nextRunAt).toBeNull();
+ expect((yield* service.list()).tasks[0]?.nextRunAt).toBeNull();
+
+ yield* service.setEnabled({ id: created.task.id, enabled: false });
+ const resumed = yield* service
+ .setEnabled({ id: created.task.id, enabled: true })
+ .pipe(Effect.flip);
+ expect(resumed.message).toBe("The run time has passed. Pick a time in the future.");
+
+ const past = yield* service
+ .upsert({ ...decoded, commandId: undefined, title: "Late" })
+ .pipe(Effect.flip);
+ expect(past.message).toBe("The run time has passed. Pick a time in the future.");
+ }).pipe(Effect.provide(slowLaunchLayer));
+ }).pipe(
+ Effect.provideService(ServerActivation, Effect.never),
+ Effect.provide(SqlitePersistence.layerMemory),
+ ),
+);
+
+const ONCE = { type: "once", runAt: "2026-11-01T08:00:00Z" } as const;
+/** A next run that only the simulated concurrent write produces. */
+const MOVED = "2030-01-01T00:00:00.000Z";
+
+const onceInput = {
+ ...input,
+ commandId: "once-race",
+ schedule: { type: "once", runAt: "2026-11-01T08:00:00Z" },
+};
+
+it.effect.each([
+ { change: "a run completes", saved: ONCE, edited: ONCE, pause: false, expected: MOVED },
+ {
+ change: "a run completes during a padded-time edit",
+ saved: { type: "fixed_time", timeOfDay: "9:00" },
+ edited: { type: "fixed_time", timeOfDay: "09:00" },
+ pause: false,
+ expected: MOVED,
+ },
+ {
+ change: "another client pauses the task",
+ saved: ONCE,
+ edited: ONCE,
+ pause: true,
+ expected: "2026-11-01T08:00:00.000Z",
+ },
+] as const)(
+ "a title save keeps the stored next run only while nothing else changed: $change",
+ ({ saved, edited, pause, expected }) =>
+ Effect.gen(function* () {
+ yield* TestClock.setTime(Date.parse("2026-11-01T07:00:00.000Z"));
+ // The project check runs between the save's read and write, so it stands in for
+ // a concurrent write in that gap.
+ const writeMidSave = Layer.unwrap(
+ Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ return Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
+ namedProjectsRoot: "/projects",
+ isScratchProject: () =>
+ sql`UPDATE scheduled_tasks SET next_run_at = ${MOVED}, enabled = ${pause ? 0 : 1}`.pipe(
+ Effect.as(false),
+ Effect.orDie,
+ ),
+ });
+ }),
+ );
+ const layer = ScheduledTaskService.layer.pipe(
+ Layer.provide(Layer.merge(dependencies, writeMidSave)),
+ );
+ yield* Effect.gen(function* () {
+ const service = yield* ScheduledTaskService.ScheduledTaskService;
+ const worktree = { type: "worktree", baseRef: "main" };
+ yield* service.upsert(
+ yield* decodeInput({
+ ...onceInput,
+ schedule: saved,
+ workspaceStrategy: { type: "root" },
+ }),
+ );
+ const renamed = yield* service.upsert(
+ yield* decodeInput({
+ ...onceInput,
+ schedule: edited,
+ workspaceStrategy: worktree,
+ title: "Renamed",
+ }),
+ );
+ expect(renamed.task.enabled).toBe(true);
+ expect(renamed.task.nextRunAt).toBe(expected);
+ }).pipe(Effect.provide(layer));
+ }).pipe(
+ Effect.provideService(ServerActivation, Effect.never),
+ Effect.provide(SqlitePersistence.layerMemory),
+ ),
+);
+
+it.effect("keeps a one-time run after a restart interrupts an earlier manual run", () =>
+ Effect.gen(function* () {
+ yield* TestClock.setTime(Date.parse("2026-11-01T07:59:00.000Z"));
+ const sql = yield* SqlClient.SqlClient;
+ const created = yield* Effect.gen(function* () {
+ const service = yield* ScheduledTaskService.ScheduledTaskService;
+ return yield* service.upsert(yield* decodeInput(onceInput));
+ }).pipe(Effect.provide(serviceLayer));
+ yield* sql`UPDATE scheduled_tasks SET last_run_status = 'running', last_run_at = '2026-11-01T07:59:00.000Z'`;
+
+ yield* TestClock.setTime(Date.parse("2026-11-01T08:05:00.000Z"));
+ yield* Effect.gen(function* () {
+ const service = yield* ScheduledTaskService.ScheduledTaskService;
+ const [task] = (yield* service.list()).tasks;
+ expect(task?.id).toBe(created.task.id);
+ expect(task?.lastRunStatus).toBe("failed");
+ expect(task?.nextRunAt).toBe("2026-11-01T08:00:00.000Z");
+ }).pipe(Effect.provide(serviceLayer));
+ }).pipe(
+ Effect.provideService(ServerActivation, Effect.never),
+ Effect.provide(SqlitePersistence.layerMemory),
+ ),
+);
+
+it.effect("reports the stored task when the row was replaced during the run", () =>
+ Effect.gen(function* () {
+ yield* TestClock.setTime(Date.parse("2026-11-01T07:00:00.000Z"));
+ // The launch stands in for a delete and same-id recreate while the run is out.
+ const replaceRowDuringLaunch = Layer.unwrap(
+ Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ return Layer.mock(ThreadLaunchService.ThreadLaunchService)({
+ launch: () =>
+ sql`UPDATE scheduled_tasks SET last_run_status = 'never', last_run_at = NULL, run_count = 0`.pipe(
+ Effect.orDie,
+ Effect.andThen(Effect.die("synthetic dispatch failure")),
+ ),
+ });
+ }),
+ );
+ const layer = ScheduledTaskService.layer.pipe(
+ Layer.provide(Layer.merge(dependencies, replaceRowDuringLaunch)),
+ );
+ yield* Effect.gen(function* () {
+ const service = yield* ScheduledTaskService.ScheduledTaskService;
+ const created = yield* service.upsert(yield* decodeInput(onceInput));
+ const ran = yield* service.runNow({ id: created.task.id });
+ expect(ran.task.runCount).toBe(0);
+ expect(ran.task.lastRunStatus).toBe("never");
+ }).pipe(Effect.provide(layer));
+ }).pipe(
+ Effect.provideService(ServerActivation, Effect.never),
+ Effect.provide(SqlitePersistence.layerMemory),
+ ),
+);
diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts
index c41f0a952ab..c12474a6fb8 100644
--- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts
+++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts
@@ -298,6 +298,35 @@ function nextRunAt(
}
}
+/**
+ * Next run after an interrupted run. A one-time task counts from the run's start
+ * (`lastRunAt`), so a manual run that began before its time does not use it up.
+ */
+function nextRunAfterRun(
+ task: Pick<ScheduledTask, "enabled" | "schedule" | "lastRunAt">,
+ now: DateTime.DateTime,
+): string | null {
+ const startedAt =
+ task.schedule.type === "once" && task.lastRunAt !== null
+ ? DateTime.make(task.lastRunAt)
+ : Option.none();
+ return nextRunAt(
+ task,
+ Option.getOrElse(startedAt, () => now),
+ );
+}
+
+/** An enabled one-time task with a past time would never run, so saving it is an error. */
+function requireFutureOnce(
+ task: Pick<ScheduledTask, "enabled" | "schedule">,
+ now: DateTime.DateTime,
+ taskId: ScheduledTaskId,
+) {
+ return task.enabled && task.schedule.type === "once" && nextRunAt(task, now) === null
+ ? taskError("The run time has passed. Pick a time in the future.", { taskId })
+ : Effect.void;
+}
+
function errorMessage(error: unknown): string {
if (Cause.isCause(error)) return Cause.pretty(error);
if (error instanceof Error) return error.message;
@@ -542,6 +571,8 @@ export const layer = Layer.effect(
const saveTask = (
task: ScheduledTask,
requireExisting: boolean,
+ /** The schedule this save read, when it left the schedule unchanged. */
+ keptSchedule: ScheduledTask["schedule"] | null,
webhook: {
readonly token: string | null;
readonly secret: string | null;
@@ -612,7 +643,18 @@ export const layer = Layer.effect(
interaction_mode = excluded.interaction_mode,
creation_source = excluded.creation_source,
updated_at = excluded.updated_at,
- next_run_at = excluded.next_run_at,
+ -- Keep a next_run_at that a finishing run moved during this save, unless
+ -- another edit changed the schedule or enabled state meanwhile.
+ next_run_at = CASE
+ WHEN ${keptSchedule === null ? 0 : 1} = 1
+ AND scheduled_tasks.schedule_json IN (
+ excluded.schedule_json,
+ ${keptSchedule === null ? null : JSON.stringify(keptSchedule)}
+ )
+ AND scheduled_tasks.enabled = excluded.enabled
+ THEN scheduled_tasks.next_run_at
+ ELSE excluded.next_run_at
+ END,
-- Only rotate changes a live token, so a save racing a rotation
-- cannot bring the old URL back.
webhook_token = CASE
@@ -685,7 +727,9 @@ export const layer = Layer.effect(
WHERE task_id = ${input.id}
AND last_run_status = 'running'
AND last_run_at = ${input.startedAtIso}
+ RETURNING task_id
`.pipe(
+ Effect.map((rows) => rows.length > 0),
Effect.mapError((cause) =>
taskError("Could not record schedule task run.", { taskId: input.id, cause }),
),
@@ -695,7 +739,12 @@ export const layer = Layer.effect(
// runDueTasks skips 'running' rows forever, and the dispatch may already have gone out,
// so next_run_at must advance. Pending webhook attempts count only with their completion.
const releaseStuckRun = Effect.fn("ScheduledTaskService.releaseStuckRun")(
- function* (task: ScheduledTask, message: string, pendingDeliveryId?: string) {
+ function* (
+ task: ScheduledTask,
+ startedAtIso: string,
+ message: string,
+ pendingDeliveryId?: string,
+ ) {
const now = yield* localNow;
const reread = yield* Effect.result(findTask(task.id));
if (Result.isSuccess(reread) && reread.success === null) return;
@@ -704,7 +753,7 @@ export const layer = Layer.effect(
UPDATE scheduled_tasks
SET last_run_status = 'failed',
last_run_error = ${message},
- next_run_at = ${nextRunAt(source, now)},
+ next_run_at = ${nextRunAfterRun({ ...source, lastRunAt: startedAtIso }, now)},
updated_at = ${iso(now)},
run_count = run_count + CASE WHEN EXISTS (
SELECT 1 FROM scheduled_task_webhook_pending
@@ -714,7 +763,7 @@ export const layer = Layer.effect(
`;
yield* notifyChanged;
},
- (effect, task, _message, _pendingDeliveryId) =>
+ (effect, task, _startedAtIso, _message, _pendingDeliveryId) =>
effect.pipe(
Effect.catch((cause) =>
Effect.logWarning("Could not release stuck schedule task run", {
@@ -734,6 +783,9 @@ export const layer = Layer.effect(
readonly dispatched: Ref.Ref<boolean>;
},
) {
+ // Read before reserving: nothing between the reservation and its release may fail.
+ const startedAt = yield* localNow;
+ const startedAtIso = iso(startedAt);
const reserved = yield* Ref.modify(activeRuns, (active) => {
if (active.has(task.id)) return [false, active] as const;
const next = new Set(active);
@@ -744,13 +796,10 @@ export const layer = Layer.effect(
if (trigger !== "scheduled") {
return yield* taskError("Schedule task is already running.", { taskId: task.id });
}
- return { task, threadId: null };
+ return { task, threadId: null, dispatchFailed: false };
}
return yield* Effect.gen(function* () {
- const startedAt = yield* localNow;
- const startedAtIso = iso(startedAt);
-
// Re-read stale poll snapshots so deleted, paused or postponed tasks cannot fire.
const active = yield* findTask(task.id);
if (active === null) {
@@ -762,7 +811,7 @@ export const layer = Layer.effect(
if (trigger !== "scheduled") {
return yield* taskError("Schedule task not found.", { taskId: task.id });
}
- return { task, threadId: null };
+ return { task, threadId: null, dispatchFailed: false };
}
if (
webhook !== undefined &&
@@ -770,7 +819,11 @@ export const layer = Layer.effect(
NodeSqliteClient.readOnly,
)).length > 0
)
- return { task: { ...active, lastRunStatus: "succeeded" as const }, threadId: null };
+ return {
+ task: { ...active, lastRunStatus: "succeeded" as const },
+ threadId: null,
+ dispatchFailed: false,
+ };
const parsedNextRunAt =
active.nextRunAt === null ? Option.none() : DateTime.make(active.nextRunAt);
if (
@@ -779,7 +832,7 @@ export const layer = Layer.effect(
Option.isNone(parsedNextRunAt) ||
DateTime.toEpochMillis(parsedNextRunAt.value) > DateTime.toEpochMillis(startedAt))
) {
- return { task: active, threadId: null };
+ return { task: active, threadId: null, dispatchFailed: false };
}
// Reject queued deliveries after pause, same-id recreation or trigger changes.
if (webhook !== undefined) {
@@ -895,18 +948,28 @@ export const layer = Layer.effect(
const lastRunStatus = runSucceeded ? ("succeeded" as const) : ("failed" as const);
const lastRunError = runSucceeded ? null : errorMessage(result.cause);
const threadId = runSucceeded ? result.value : null;
- const current = yield* findTask(task.id);
- const scheduleSource = current ?? task;
- const completed: ScheduledTask = {
- ...scheduleSource,
- updatedAt: iso(completedAt),
- lastRunAt: startedAtIso,
- nextRunAt: nextRunAt(scheduleSource, completedAt),
- lastRunStatus,
- lastRunError,
- runCount: scheduleSource.runCount + 1,
- };
- if (current !== null) {
+ // One transaction, so an edit cannot land between reading the schedule and
+ // writing the next run computed from it. The origin is read first: it reads
+ // files, and the transaction holds SQLite's writer lock.
+ const origin = yield* readWebhookOrigin;
+ const record = Effect.gen(function* () {
+ const [row] = yield* getRows(task.id);
+ const current = row === undefined ? null : yield* decodeRow(row, origin);
+ const scheduleSource = current ?? task;
+ const completed: ScheduledTask = {
+ ...scheduleSource,
+ updatedAt: iso(completedAt),
+ lastRunAt: startedAtIso,
+ // A manual run that starts before a one-time run must not use it up.
+ nextRunAt: nextRunAt(
+ scheduleSource,
+ scheduleSource.schedule.type === "once" ? startedAt : completedAt,
+ ),
+ lastRunStatus,
+ lastRunError,
+ runCount: scheduleSource.runCount + 1,
+ };
+ if (current === null) return { recorded: completed, written: false };
// startedAtIso in the guard ensures this writes only to the row this
// run marked as running — a task deleted mid-run and recreated with
// the same id (idempotent commandId replay) must not be stamped.
@@ -918,32 +981,43 @@ export const layer = Layer.effect(
error: lastRunError,
startedAtIso,
});
- if (webhook === undefined) yield* completion;
- else
- yield* sql
- .withTransaction(
- Effect.gen(function* () {
- const pending =
- yield* sql`SELECT 1 FROM scheduled_task_webhook_pending WHERE delivery_id = ${webhook.deliveryId}`;
- if (pending.length === 0) yield* completion;
- else {
- const counted =
- yield* sql`UPDATE scheduled_task_webhook_pending SET state = ${runSucceeded ? "completed" : "failed"}
- WHERE delivery_id = ${webhook.deliveryId} AND state NOT IN ('completed', 'failed') RETURNING delivery_id`;
- if (counted.length > 0) yield* completion;
- }
- }),
- )
- .pipe(
- Effect.mapError((cause) =>
- taskError("Could not record webhook completion.", { taskId: task.id, cause }),
- ),
- );
- yield* notifyChanged;
- }
- return { task: completed, threadId };
+ let written = false;
+ if (webhook === undefined) written = yield* completion;
+ else {
+ const pending =
+ yield* sql`SELECT 1 FROM scheduled_task_webhook_pending WHERE delivery_id = ${webhook.deliveryId}`;
+ if (pending.length === 0) written = yield* completion;
+ else {
+ const counted =
+ yield* sql`UPDATE scheduled_task_webhook_pending SET state = ${runSucceeded ? "completed" : "failed"}
+ WHERE delivery_id = ${webhook.deliveryId} AND state NOT IN ('completed', 'failed') RETURNING delivery_id`;
+ if (counted.length > 0) written = yield* completion;
+ }
+ }
+ // A row recreated mid-run is not this run's, so report what is stored.
+ return { recorded: written ? completed : current, written };
+ });
+ const { recorded, written } = yield* sql
+ .withTransaction(record)
+ .pipe(
+ Effect.mapError((cause) =>
+ isScheduledTaskError(cause)
+ ? cause
+ : taskError(
+ webhook === undefined
+ ? "Could not record schedule task run."
+ : "Could not record webhook completion.",
+ { taskId: task.id, cause },
+ ),
+ ),
+ );
+ if (written) yield* notifyChanged;
+ // The stored row can belong to a replacement, so report this dispatch separately.
+ return { task: recorded, threadId, dispatchFailed: !runSucceeded };
}).pipe(
- Effect.onError((cause) => releaseStuckRun(task, errorMessage(cause), webhook?.deliveryId)),
+ Effect.onError((cause) =>
+ releaseStuckRun(task, startedAtIso, errorMessage(cause), webhook?.deliveryId),
+ ),
Effect.ensuring(
Ref.update(activeRuns, (active) => {
const next = new Set(active);
@@ -1039,7 +1113,7 @@ export const layer = Layer.effect(
UPDATE scheduled_tasks
SET last_run_status = 'failed',
last_run_error = 'Run was interrupted by a server restart.',
- next_run_at = ${nextRunAt(decoded.success, now)},
+ next_run_at = ${nextRunAfterRun(decoded.success, now)},
updated_at = ${iso(now)},
run_count = run_count + CASE WHEN EXISTS (
SELECT 1 FROM scheduled_task_webhook_pending
@@ -1150,7 +1224,9 @@ export const layer = Layer.effect(
: undefined),
),
}
- : input.schedule;
+ : input.schedule.type === "once"
+ ? { type: "once", runAt: iso(DateTime.makeUnsafe(input.schedule.runAt)) }
+ : input.schedule;
const webhook =
input.schedule.type === "webhook"
? yield* Effect.gen(function* () {
@@ -1196,6 +1272,8 @@ export const layer = Layer.effect(
existingTask !== null &&
existingTask.enabled === input.enabled &&
isSameSchedule(existingTask.schedule, schedule);
+ if (!scheduleUnchanged)
+ yield* requireFutureOnce({ enabled: input.enabled, schedule }, now, id);
const task: ScheduledTask = {
id,
title: input.title,
@@ -1220,7 +1298,12 @@ export const layer = Layer.effect(
lastRunError: existingTask?.lastRunError ?? null,
runCount: existingTask?.runCount ?? 0,
};
- yield* saveTask(task, input.requireExisting === true, webhook);
+ yield* saveTask(
+ task,
+ input.requireExisting === true,
+ scheduleUnchanged ? existingTask.schedule : null,
+ webhook,
+ );
yield* notifyChanged;
return { task: (yield* findTask(id)) ?? task };
});
@@ -1231,6 +1314,11 @@ export const layer = Layer.effect(
const existing = yield* loadTask(input.id);
if (existing.enabled === input.enabled) return { task: existing };
const now = yield* localNow;
+ yield* requireFutureOnce(
+ { enabled: input.enabled, schedule: existing.schedule },
+ now,
+ input.id,
+ );
const next = nextRunAt({ enabled: input.enabled, schedule: existing.schedule }, now);
// RETURNING so a task deleted between the load and this UPDATE is a
// visible not-found error, not a false success.
@@ -1668,8 +1756,8 @@ export const layer = Layer.effect(
]);
const dispatched = yield* Ref.make(false);
return yield* runTask(task, "webhook", { deliveryId, prompt, dispatched }).pipe(
- Effect.flatMap(({ task: completed }) =>
- completed.lastRunStatus === "failed"
+ Effect.flatMap(({ dispatchFailed }) =>
+ dispatchFailed
? runOutcome("failed").pipe(
Effect.andThen(markDeliveryFailed(deliveryId, "The run failed to start.")),
Effect.andThen(releaseFailedDelivery(deliveryId)),
diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts
index cdd4e60e62d..3bc3fe506e7 100644
--- a/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts
+++ b/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts
@@ -1199,6 +1199,32 @@ it.effect("start failures release both replay keys and relay claims for redelive
),
);
+it.effect("a start failure releases the relay claim when the task row is replaced mid-run", () =>
+ Effect.gen(function* () {
+ const gate = yield* Deferred.make<void>();
+ yield* withService(
+ ({ service, sql, launches }) =>
+ Effect.gen(function* () {
+ const { task } = yield* service.upsert(yield* webhookTaskInput());
+ const request = requestFor(task, { relayDeliveryId: "replaced-mid-run" });
+ const first = yield* waitForSpan(
+ service.triggerWebhook(request),
+ "ScheduledTaskService.runWebhookDelivery",
+ ).pipe(Effect.forkChild);
+ yield* Queue.take(launches);
+ // A same-id recreate while the launch is out: the stored row is no longer this run's.
+ yield* sql`UPDATE scheduled_tasks SET last_run_status = 'never', last_run_at = NULL`;
+ yield* Deferred.succeed(gate, undefined);
+ yield* Fiber.join(first);
+ const retry = yield* service.triggerWebhook(request);
+ assert.equal(retry._tag === "accepted" && retry.outcome, "accepted");
+ yield* Queue.take(launches);
+ }),
+ { gate, failLaunches: { remaining: 1 } },
+ );
+ }),
+);
+
it.effect("main retention keeps fifty runs and preserves filtered and dedupe buckets", () =>
withService(({ service, sql, launches }) =>
Effect.gen(function* () {
diff --git a/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx b/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx
index 7e42bba4bc6..ca8192dd894 100644
--- a/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx
+++ b/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx
@@ -70,7 +70,9 @@ function environment() {
environmentId,
label: "Laptop",
connection: { phase: state.connected ? "connected" : "disconnected" },
- serverConfig: state.connected ? { environment: { platform: "linux" } } : null,
+ serverConfig: state.connected
+ ? { environment: { platform: "linux", capabilities: { oneTimeSchedules: true } } }
+ : null,
};
}
diff --git a/apps/web/src/components/settings/ScheduledTasksSettings.tsx b/apps/web/src/components/settings/ScheduledTasksSettings.tsx
index 05c740e55a8..9489e4162cb 100644
--- a/apps/web/src/components/settings/ScheduledTasksSettings.tsx
+++ b/apps/web/src/components/settings/ScheduledTasksSettings.tsx
@@ -77,7 +77,8 @@ import { SettingsGroup } from "./SettingsGroup";
import { settingsScopeEnvironmentLabel, settingsScopeEnvironmentLabels } from "./settingsScopeAxis";
import {
WEBHOOK_SIGNATURE_DEFAULTS,
- webhookDraftErrors,
+ scheduleDraftErrors,
+ toDateTimeLocalValue,
webhookDeliveryLabel,
defaultScheduledTaskProjectId,
matchesScheduledTaskScope,
@@ -136,6 +137,8 @@ const EMPTY_DRAFT: DraftState = {
scheduleMode: "fixed",
intervalMinutes: "15",
timeOfDay: "09:00",
+ runAt: "",
+ savedRunAt: "",
weekdays: new Set([1, 2, 3, 4, 5]),
projectId: "",
threadId: "",
@@ -284,8 +287,14 @@ function splitModelKey(value: string): ModelSelection | null {
};
}
+const ONCE_FORMATTER = new Intl.DateTimeFormat(undefined, {
+ dateStyle: "medium",
+ timeStyle: "short",
+});
+
export function scheduleLabel(schedule: ScheduledTaskSchedule): string {
if (schedule.type === "webhook") return "On webhook";
+ if (schedule.type === "once") return `Once, ${ONCE_FORMATTER.format(new Date(schedule.runAt))}`;
if (schedule.type === "interval") {
const minutes = schedule.everyMs / 60_000;
return Number.isInteger(minutes)
@@ -1171,6 +1180,10 @@ function ScheduledTaskEditorForm({
const { scope, connectedEnvironments } = useSettingsScope();
const [environmentId, setEnvironmentId] = useState(initialEnvironmentId);
const environment = useEnvironment(environmentId);
+ // Older servers reject one-time schedules, so offer Once only where it can save.
+ const offersOnce =
+ environment?.serverConfig?.environment.capabilities.oneTimeSchedules === true ||
+ task?.schedule.type === "once";
const connected =
environment?.connection.phase === "connected" && environment.serverConfig !== null;
const tasksQuery = useEnvironmentQuery(
@@ -1278,7 +1291,7 @@ function ScheduledTaskEditorForm({
}
const schedule = scheduleFromDraft(draft);
if (schedule === null) {
- for (const error of webhookDraftErrors(draft)) reportFailure(error.title, error.description);
+ for (const error of scheduleDraftErrors(draft)) reportFailure(error.title, error.description);
return;
}
if (
@@ -1298,6 +1311,13 @@ function ScheduledTaskEditorForm({
reportFailure("Invalid interval", "Enter an interval of at least one minute.");
return;
}
+ if (schedule.type === "once" && !offersOnce) {
+ reportFailure(
+ "Once is not available here",
+ "This environment runs an older T3 Code. Update it to schedule a one-time task, or pick another schedule.",
+ );
+ return;
+ }
if (draft.workspaceMode === "existing_worktree" && !draft.existingWorktreePath.trim()) {
reportFailure("Checkout path is required", "Enter the path of the checkout to run in.");
return;
@@ -1352,7 +1372,8 @@ function ScheduledTaskEditorForm({
<DialogHeader>
<DialogTitle>{draft.editingId ? "Edit task" : "New task"}</DialogTitle>
<DialogDescription>
- Run a prompt automatically on an interval, at a fixed time, or when a webhook is called.
+ Run a prompt automatically on an interval, at a fixed time, once at a set date, or when a
+ webhook is called.
</DialogDescription>
</DialogHeader>
@@ -1580,18 +1601,39 @@ function ScheduledTaskEditorForm({
value={[draft.scheduleMode]}
onValueChange={(values) => {
const mode = values[0] as ScheduleMode | undefined;
- if (mode === "fixed" || mode === "interval" || mode === "webhook")
- setDraft((current) => ({
- ...current,
- scheduleMode: mode,
- prompt:
- mode === "webhook" && !current.prompt.trim()
- ? DEFAULT_WEBHOOK_PROMPT
- : current.prompt,
- }));
+ if (
+ mode === "fixed" ||
+ mode === "once" ||
+ mode === "interval" ||
+ mode === "webhook"
+ )
+ setDraft((current) => {
+ const suggested =
+ mode === "once" && !current.runAt
+ ? new Date(Math.ceil(Date.now() / 3_600_000) * 3_600_000)
+ : null;
+ return {
+ ...current,
+ scheduleMode: mode,
+ // Keep the instant too, so an hour that repeats when clocks go back stays exact.
+ ...(suggested === null
+ ? {}
+ : {
+ runAt: toDateTimeLocalValue(suggested),
+ savedRunAt: suggested.toISOString(),
+ }),
+ prompt:
+ mode === "webhook" && !current.prompt.trim()
+ ? DEFAULT_WEBHOOK_PROMPT
+ : current.prompt,
+ };
+ });
}}
>
<Toggle value="fixed">At a time</Toggle>
+ {offersOnce || draft.scheduleMode === "once" ? (
+ <Toggle value="once">Once</Toggle>
+ ) : null}
<Toggle value="interval">Every interval</Toggle>
<Toggle value="webhook">On webhook</Toggle>
</ToggleGroup>
@@ -1769,6 +1811,20 @@ function ScheduledTaskEditorForm({
</div>
) : null}
</div>
+ ) : draft.scheduleMode === "once" ? (
+ <div className="flex items-center gap-2">
+ <Label htmlFor="scheduled-task-run-at">Run on</Label>
+ <Input
+ type="datetime-local"
+ id="scheduled-task-run-at"
+ nativeInput
+ className="w-56"
+ value={draft.runAt}
+ onChange={(event) =>
+ setDraft((current) => ({ ...current, runAt: event.target.value }))
+ }
+ />
+ </div>
) : draft.scheduleMode === "fixed" ? (
<div className="flex flex-wrap items-center gap-3">
<div className="flex items-center gap-2">
diff --git a/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts b/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts
index 7d13e1edc4e..c4c66c1cfba 100644
--- a/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts
+++ b/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts
@@ -7,7 +7,7 @@ import {
ScheduledTaskId,
type ScheduledTask,
} from "@t3tools/contracts";
-import { describe, expect, it } from "vite-plus/test";
+import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import type {
SidebarProjectGroupMember,
@@ -170,6 +170,42 @@ describe("editing scheduled task branch settings", () => {
});
});
+describe("one-time scheduled tasks", () => {
+ afterEach(() => vi.unstubAllEnvs());
+
+ it("round-trips the run time through the local date-time input", () => {
+ const runAt = "2026-11-03T17:00:42.000Z";
+ const draft = taskToDraft({ ...legacyTask, schedule: { type: "once", runAt } });
+ expect(draft.scheduleMode).toBe("once");
+ expect(scheduleFromDraft(draft)).toEqual({ type: "once", runAt });
+ const moved = scheduleFromDraft({ ...draft, runAt: "2026-11-04T09:30" });
+ expect(moved).toEqual({ type: "once", runAt: new Date("2026-11-04T09:30").toISOString() });
+ expect(scheduleFromDraft({ ...draft, runAt: "" })).toBeNull();
+ });
+
+ it("rejects a time skipped by daylight saving", () => {
+ vi.stubEnv("TZ", "America/Los_Angeles");
+ const draft = taskToDraft({
+ ...legacyTask,
+ schedule: { type: "once", runAt: "2027-03-14T18:00:00.000Z" },
+ });
+ expect(scheduleFromDraft({ ...draft, runAt: "2027-03-14T02:30" })).toBeNull();
+ });
+
+ it("keeps the saved offset when an edit stays in an hour that repeats", () => {
+ vi.stubEnv("TZ", "America/Los_Angeles");
+ // 01:30 PST, the second 01:30 on 2026-11-01.
+ const draft = taskToDraft({
+ ...legacyTask,
+ schedule: { type: "once", runAt: "2026-11-01T09:30:00.000Z" },
+ });
+ expect(scheduleFromDraft({ ...draft, runAt: "2026-11-01T01:35" })).toEqual({
+ type: "once",
+ runAt: "2026-11-01T09:35:00.000Z",
+ });
+ });
+});
+
describe("webhook scheduled tasks", () => {
const signature = { header: "x-signature", encoding: "base64", prefix: "" } as const;
const webhookTask: ScheduledTask = {
diff --git a/apps/web/src/components/settings/scheduledTasksSettings.logic.ts b/apps/web/src/components/settings/scheduledTasksSettings.logic.ts
index 35647d5a76d..9e0d0dad27c 100644
--- a/apps/web/src/components/settings/scheduledTasksSettings.logic.ts
+++ b/apps/web/src/components/settings/scheduledTasksSettings.logic.ts
@@ -52,7 +52,7 @@ export function validateScheduledTasksSearch(raw: Record<string, unknown>) {
};
}
-export type ScheduleMode = "fixed" | "interval" | "webhook";
+export type ScheduleMode = "fixed" | "once" | "interval" | "webhook";
export type WorkspaceMode = "root" | "worktree" | "existing_worktree";
export interface DraftState {
@@ -63,6 +63,10 @@ export interface DraftState {
readonly scheduleMode: ScheduleMode;
readonly intervalMinutes: string;
readonly timeOfDay: string;
+ /** Local date and time as a `datetime-local` input value, such as 2026-11-02T15:00. */
+ readonly runAt: string;
+ /** The stored ISO run time, sent back unchanged when the field was not edited. */
+ readonly savedRunAt: string;
readonly weekdays: ReadonlySet<number>;
readonly projectId: string;
readonly threadId: string;
@@ -96,7 +100,24 @@ export const WEBHOOK_SIGNATURE_DEFAULTS = {
signaturePrefix: "sha256=",
} as const;
-export function webhookDraftErrors(draft: DraftState) {
+/** Formats a date as a `datetime-local` input value in the browser's time zone. */
+export function toDateTimeLocalValue(date: Date): string {
+ const pad = (value: number) => String(value).padStart(2, "0");
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
+}
+
+export function scheduleDraftErrors(draft: DraftState) {
+ if (draft.scheduleMode === "once") {
+ const runAt = new Date(draft.runAt);
+ if (Number.isNaN(runAt.getTime()))
+ return [{ title: "Invalid run time", description: "Pick a date and time." }];
+ // A time skipped by a daylight saving change parses to a different clock time.
+ if (toDateTimeLocalValue(runAt) !== draft.runAt)
+ return [
+ { title: "Invalid run time", description: "That time does not exist in your time zone." },
+ ];
+ return [];
+ }
if (draft.scheduleMode !== "webhook") return [];
if (parseMaxDeliveryAge(draft.maxDeliveryAgeMinutes) === undefined)
return [
@@ -144,8 +165,26 @@ export function webhookDeliveryLabel(delivery: {
}
export function scheduleFromDraft(draft: DraftState): ScheduledTaskUpsertSchedule | null {
+ if (scheduleDraftErrors(draft).length > 0) return null;
+ if (draft.scheduleMode === "once") {
+ const saved = draft.savedRunAt ? new Date(draft.savedRunAt) : null;
+ if (saved !== null && toDateTimeLocalValue(saved) === draft.runAt)
+ return { type: "once", runAt: draft.savedRunAt };
+ // A `datetime-local` value has no offset. In an hour that repeats when clocks go
+ // back, keep the saved time's offset; otherwise Date reads it as local time.
+ const withSavedOffset =
+ saved === null
+ ? null
+ : new Date(Date.parse(`${draft.runAt}Z`) + saved.getTimezoneOffset() * 60_000);
+ return {
+ type: "once",
+ runAt:
+ withSavedOffset !== null && toDateTimeLocalValue(withSavedOffset) === draft.runAt
+ ? withSavedOffset.toISOString()
+ : new Date(draft.runAt).toISOString(),
+ };
+ }
if (draft.scheduleMode === "webhook") {
- if (webhookDraftErrors(draft).length > 0) return null;
const maxDeliveryAgeMinutes = parseMaxDeliveryAge(draft.maxDeliveryAgeMinutes);
const replayKey = draft.replayKey.trim();
const coalesceKey = draft.coalesceKey.trim();
@@ -206,11 +245,12 @@ export function taskToDraft(task: ScheduledTask): DraftState {
title: task.title,
prompt: task.prompt,
enabled: task.enabled,
- scheduleMode:
- schedule.type === "interval" ? "interval" : schedule.type === "webhook" ? "webhook" : "fixed",
+ scheduleMode: schedule.type === "fixed_time" ? "fixed" : schedule.type,
intervalMinutes:
schedule.type === "interval" ? String(Math.max(1, schedule.everyMs / 60_000)) : "15",
timeOfDay: schedule.type === "fixed_time" ? schedule.timeOfDay : "09:00",
+ runAt: schedule.type === "once" ? toDateTimeLocalValue(new Date(schedule.runAt)) : "",
+ savedRunAt: schedule.type === "once" ? schedule.runAt : "",
weekdays,
projectId: task.projectId,
threadId: task.threadId ?? "",
diff --git a/docs/user/project-settings.md b/docs/user/project-settings.md
index 802c15433f0..ddecdc40faf 100644
--- a/docs/user/project-settings.md
+++ b/docs/user/project-settings.md
@@ -78,11 +78,13 @@ branch name remains.
## Scheduled tasks on mobile
-Open **Settings → Scheduled tasks** to create recurring tasks or manage existing
+Open **Settings → Scheduled tasks** to create scheduled tasks or manage existing
ones across your connected environments. Use the settings filter to narrow the
list by environment or project. Each task runs on the environment you choose,
using its project, model, and workspace settings. Fixed-time schedules use that
-environment's time zone, which may differ from your phone's.
+environment's time zone, which may differ from your phone's. Choose **Once**
+to run a task a single time at a date and time in your own time zone. If the
+environment is offline then, the task runs when it is back.
Deleting a thread also deletes tasks that post into that thread. Tasks that start
a new thread on each run survive deletion of their previous threads.
diff --git a/evals/mcp-tool-use/cases/pull-requests.ndjson b/evals/mcp-tool-use/cases/pull-requests.ndjson
index 57ea8334c9d..997243d873a 100644
--- a/evals/mcp-tool-use/cases/pull-requests.ndjson
+++ b/evals/mcp-tool-use/cases/pull-requests.ndjson
@@ -21,7 +21,7 @@
{"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}
{"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}
{"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}
-{"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."}
+{"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."}
{"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": ""}
{"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."}
{"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 @@
{"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."}}
{"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."}}
{"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"}}
+{"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."}
diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts
index 9d60bec43fe..f9cd98311d1 100644
--- a/packages/contracts/src/environment.ts
+++ b/packages/contracts/src/environment.ts
@@ -161,6 +161,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
linkFence: Schema.optionalKey(Schema.Boolean),
/** Server answers server.prepareTriage. */
triage: Schema.optionalKey(Schema.Boolean),
+ /** Server accepts `{ type: "once" }` scheduled tasks; older servers reject them on save. */
+ oneTimeSchedules: Schema.optionalKey(Schema.Boolean),
});
export type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type;
diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts
index 1474a5d6e87..438a3fe2def 100644
--- a/packages/contracts/src/orchestratorMcp.ts
+++ b/packages/contracts/src/orchestratorMcp.ts
@@ -67,7 +67,7 @@ const OrchestratorMcpSchedule = Schema.Union([
OrchestratorMcpScheduleFromJsonString,
]).annotate({
description:
- "Trigger: {type:'interval',everyMs}, {type:'fixed_time',timeOfDay,weekdays?}, or {type:'webhook'}.",
+ "Trigger: {type:'interval',everyMs}, {type:'fixed_time',timeOfDay,weekdays?}, {type:'once',runAt}, or {type:'webhook'}.",
});
const OrchestratorMcpTargetOptionsFromRecord = Schema.Record(
diff --git a/packages/contracts/src/scheduledTask.test.ts b/packages/contracts/src/scheduledTask.test.ts
index 50a49de7f86..c9b4d597bd0 100644
--- a/packages/contracts/src/scheduledTask.test.ts
+++ b/packages/contracts/src/scheduledTask.test.ts
@@ -22,6 +22,22 @@ describe("ScheduledTaskSchedule", () => {
everyMs: MIN_SCHEDULED_TASK_INTERVAL_MS - 1,
});
});
+
+ it("accepts a one-time run only with an offset", () => {
+ for (const runAt of ["2026-11-03T09:00Z", "2026-11-03T09:00:00.000-08:00"]) {
+ expect(decodeUpsertSchedule({ type: "once", runAt })).toEqual({ type: "once", runAt });
+ }
+ for (const runAt of [
+ "2026-11-03T09:00",
+ "2026-13-03T09:00Z",
+ "2026-02-30T09:00Z",
+ "9999-12-31T23:30-01:00",
+ "0000-01-01T00:00+00:01",
+ "tomorrow",
+ ]) {
+ expect(() => decodeUpsertSchedule({ type: "once", runAt })).toThrow();
+ }
+ });
});
it.each(["literal", " ", "\t\n", "{{body.bad", "{{unknown.field}}"])(
diff --git a/packages/contracts/src/scheduledTask.ts b/packages/contracts/src/scheduledTask.ts
index b4dffacd74c..5fbbc48301d 100644
--- a/packages/contracts/src/scheduledTask.ts
+++ b/packages/contracts/src/scheduledTask.ts
@@ -45,6 +45,34 @@ const ScheduledTaskFixedTimeSchedule = Schema.Struct({
),
});
+const ISO_WITH_OFFSET =
+ /^(\d{4})-(\d{2})-(\d{2})T([01]\d|2[0-3]):[0-5]\d(:[0-5]\d(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
+
+const YEAR_0000 = Date.parse("0000-01-01T00:00:00Z");
+const YEAR_10000 = Date.parse("+010000-01-01T00:00:00Z");
+
+/** Date.parse rolls impossible days like Feb 30 into the next month, so check the day too. */
+function isIsoWithOffset(value: string): boolean {
+ const match = ISO_WITH_OFFSET.exec(value);
+ // The server stores UTC, which must stay a four-digit year to decode again.
+ const time = Date.parse(value);
+ if (!match || !(time >= YEAR_0000 && time < YEAR_10000)) return false;
+ const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])];
+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
+ const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
+ return days !== undefined && day >= 1 && day <= days;
+}
+
+// Checked by filter, not pattern, to keep the MCP tool schema small.
+const ScheduledTaskOnceSchedule = Schema.Struct({
+ type: Schema.Literal("once"),
+ runAt: TrimmedNonEmptyString.check(
+ Schema.makeFilter(
+ (value) => isIsoWithOffset(value) || "Expected an ISO date and time with an offset.",
+ ),
+ ),
+});
+
const ScheduledTaskWebhookSignatureFields = {
header: TrimmedNonEmptyString.annotate({
description: "Header with the signature, such as x-hub-signature-256.",
@@ -166,6 +194,7 @@ const ScheduledTaskUpsertWebhookSchedule = Schema.Struct({
export const ScheduledTaskSchedule = Schema.Union([
ScheduledTaskIntervalSchedule,
ScheduledTaskFixedTimeSchedule,
+ ScheduledTaskOnceSchedule,
ScheduledTaskWebhookSchedule,
]);
export type ScheduledTaskSchedule = typeof ScheduledTaskSchedule.Type;
@@ -180,6 +209,7 @@ export const ScheduledTaskUpsertSchedule = Schema.Union([
}),
}),
ScheduledTaskFixedTimeSchedule,
+ ScheduledTaskOnceSchedule,
ScheduledTaskUpsertWebhookSchedule,
]);
export type ScheduledTaskUpsertSchedule = typeof ScheduledTaskUpsertSchedule.Type;
diff --git a/packages/shared/src/t3McpToolPresentation.ts b/packages/shared/src/t3McpToolPresentation.ts
index 1b07ede90c4..3fc2db1648e 100644
--- a/packages/shared/src/t3McpToolPresentation.ts
+++ b/packages/shared/src/t3McpToolPresentation.ts
@@ -144,10 +144,7 @@ const T3_MCP_TOOLS: Readonly<Record<string, T3McpToolDefinition>> = {
["Cancel", "Canceling", "Requested cancellation of", "a delegated task"],
"task-cancel",
),
- schedule_task: tool(
- ["Schedule", "Scheduling", "Scheduled", "a recurring task"],
- "schedule-create",
- ),
+ schedule_task: tool(["Schedule", "Scheduling", "Scheduled", "a task"], "schedule-create"),
list_scheduled_tasks: tool(["List", "Listing", "Listed", "scheduled tasks"], "schedule-list"),
update_scheduled_task: tool(
["Update", "Updating", "Updated", "a scheduled task"],