Skip to content

Commit d9b0640

Browse files
committed
feat(server): gate scheduled tasks behind a settings switch
The scheduler fired whenever tasks existed, with no way to turn the behavior off short of cancelling every task. Adds an enableScheduledTasks ServerSettings flag (default on): the tick reads it per cycle and skips the due-scan when off, stored schedules are untouched and resume with normal coalescing when re-enabled, and the per-project schedule UI hides while the switch is off. Surfaces as Settings -> Integrations -> Automation -> Scheduled tasks, following the enableAgentBrowserAccess pattern end-to-end: contracts schema + patch key, per-tick server gate, web toggle with search entry and restore-defaults wiring, and user docs.
1 parent 6f33ca5 commit d9b0640

9 files changed

Lines changed: 189 additions & 53 deletions

File tree

‎apps/server/src/orchestration/Layers/TaskScheduler.test.ts‎

Lines changed: 71 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import { expect, it } from "@effect/vitest";
44
import * as Effect from "effect/Effect";
55
import * as Layer from "effect/Layer";
66

7+
import type { DeepPartial } from "@t3tools/shared/Struct";
8+
79
import {
810
OrchestrationEngineService,
911
type OrchestrationEngineShape,
@@ -13,6 +15,8 @@ import {
1315
type ProjectionSnapshotQueryShape,
1416
} from "../Services/ProjectionSnapshotQuery.ts";
1517
import { TaskScheduler } from "../Services/TaskScheduler.ts";
18+
import { ServerSettingsService } from "../../serverSettings.ts";
19+
import type { ServerSettings } from "@t3tools/contracts";
1620
import { makeTaskSchedulerLive } from "./TaskScheduler.ts";
1721

1822
function makeDueTask(input: {
@@ -40,53 +44,79 @@ const state = {
4044
dispatched: [] as Array<{ type: string; commandId: CommandId; dueAt: string }>,
4145
};
4246

43-
const schedulerLayer = makeTaskSchedulerLive({ tickIntervalMs: 60_000 }).pipe(
44-
Layer.provideMerge(
45-
Layer.succeed(ProjectionSnapshotQuery, {
46-
listDueTasks: () => Effect.succeed(state.dueTasks),
47-
} as unknown as ProjectionSnapshotQueryShape),
48-
),
49-
Layer.provideMerge(
50-
Layer.succeed(OrchestrationEngineService, {
51-
dispatch: (command: { type: string; commandId: CommandId; dueAt?: string }) =>
52-
Effect.sync(() => {
53-
state.dispatched.push(command as { type: string; commandId: CommandId; dueAt: string });
54-
return { sequence: 1 };
55-
}),
56-
} as unknown as OrchestrationEngineShape),
57-
),
58-
);
59-
60-
it.layer(schedulerLayer.pipe(Layer.provideMerge(NodeServices.layer)))("task scheduler", (it) => {
61-
it.effect("dispatches a deterministic task.fire per due slot", () =>
62-
Effect.gen(function* () {
63-
state.dispatched = [];
64-
state.dueTasks = [
65-
makeDueTask({ taskId: "task-a", nextFireAt: "2026-01-01T00:00:00.000Z" }),
66-
makeDueTask({ taskId: "task-b", nextFireAt: "2026-01-01T00:05:00.000Z" }),
67-
];
68-
69-
const scheduler = yield* TaskScheduler;
70-
const firedCount = yield* scheduler.tick();
47+
const fakeProjectionLayer = Layer.succeed(ProjectionSnapshotQuery, {
48+
listDueTasks: () => Effect.succeed(state.dueTasks),
49+
} as unknown as ProjectionSnapshotQueryShape);
7150

72-
expect(firedCount).toBe(2);
73-
expect(state.dispatched).toHaveLength(2);
74-
// Deterministic ids keyed by the due slot so crash-retries collapse
75-
// into the engine's idempotent command receipts.
76-
expect(state.dispatched[0]?.type).toBe("task.fire");
77-
expect(state.dispatched[0]?.commandId).toBe(
78-
CommandId.make("server:task-fire:task-a:2026-01-01T00:00:00.000Z"),
79-
);
80-
expect(state.dispatched[1]?.commandId).toBe(
81-
CommandId.make("server:task-fire:task-b:2026-01-01T00:05:00.000Z"),
82-
);
51+
const fakeEngineLayer = Layer.succeed(OrchestrationEngineService, {
52+
dispatch: (command: { type: string; commandId: CommandId; dueAt?: string }) =>
53+
Effect.sync(() => {
54+
state.dispatched.push(command as { type: string; commandId: CommandId; dueAt: string });
55+
return { sequence: 1 };
8356
}),
57+
} as unknown as OrchestrationEngineShape);
58+
59+
const schedulerLayerWithSettings = (settingsOverrides?: DeepPartial<ServerSettings>) =>
60+
makeTaskSchedulerLive({ tickIntervalMs: 60_000 }).pipe(
61+
Layer.provideMerge(ServerSettingsService.layerTest(settingsOverrides)),
62+
Layer.provideMerge(fakeProjectionLayer),
63+
Layer.provideMerge(fakeEngineLayer),
8464
);
8565

86-
it.effect("returns zero and dispatches nothing when no task is due", () =>
66+
it.layer(schedulerLayerWithSettings().pipe(Layer.provideMerge(NodeServices.layer)))(
67+
"task scheduler",
68+
(it) => {
69+
it.effect("dispatches a deterministic task.fire per due slot", () =>
70+
Effect.gen(function* () {
71+
state.dispatched = [];
72+
state.dueTasks = [
73+
makeDueTask({ taskId: "task-a", nextFireAt: "2026-01-01T00:00:00.000Z" }),
74+
makeDueTask({ taskId: "task-b", nextFireAt: "2026-01-01T00:05:00.000Z" }),
75+
];
76+
77+
const scheduler = yield* TaskScheduler;
78+
const firedCount = yield* scheduler.tick();
79+
80+
expect(firedCount).toBe(2);
81+
expect(state.dispatched).toHaveLength(2);
82+
// Deterministic ids keyed by the due slot so crash-retries collapse
83+
// into the engine's idempotent command receipts.
84+
expect(state.dispatched[0]?.type).toBe("task.fire");
85+
expect(state.dispatched[0]?.commandId).toBe(
86+
CommandId.make("server:task-fire:task-a:2026-01-01T00:00:00.000Z"),
87+
);
88+
expect(state.dispatched[1]?.commandId).toBe(
89+
CommandId.make("server:task-fire:task-b:2026-01-01T00:05:00.000Z"),
90+
);
91+
}),
92+
);
93+
94+
it.effect("returns zero and dispatches nothing when no task is due", () =>
95+
Effect.gen(function* () {
96+
state.dispatched = [];
97+
state.dueTasks = [];
98+
99+
const scheduler = yield* TaskScheduler;
100+
const firedCount = yield* scheduler.tick();
101+
102+
expect(firedCount).toBe(0);
103+
expect(state.dispatched).toHaveLength(0);
104+
}),
105+
);
106+
},
107+
);
108+
109+
it.layer(
110+
schedulerLayerWithSettings({ enableScheduledTasks: false }).pipe(
111+
Layer.provideMerge(NodeServices.layer),
112+
),
113+
)("task scheduler with the feature switch off", (it) => {
114+
it.effect("skips the due scan and dispatches nothing", () =>
87115
Effect.gen(function* () {
88116
state.dispatched = [];
89-
state.dueTasks = [];
117+
state.dueTasks = [
118+
makeDueTask({ taskId: "task-off", nextFireAt: "2026-01-01T00:00:00.000Z" }),
119+
];
90120

91121
const scheduler = yield* TaskScheduler;
92122
const firedCount = yield* scheduler.tick();

‎apps/server/src/orchestration/Layers/TaskScheduler.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import * as Schedule from "effect/Schedule";
88
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
99
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
1010
import { TaskScheduler, type TaskSchedulerShape } from "../Services/TaskScheduler.ts";
11+
import { ServerSettingsService } from "../../serverSettings.ts";
1112
import { forkParked } from "../../serverActivation.ts";
1213

1314
const DEFAULT_TICK_INTERVAL_MS = 15 * 1000;
@@ -26,10 +27,28 @@ const makeTaskScheduler = (options?: TaskSchedulerLiveOptions) =>
2627
Effect.gen(function* () {
2728
const orchestrationEngine = yield* OrchestrationEngineService;
2829
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
30+
// The feature switch is read per tick, not captured at startup, so
31+
// toggling it in settings takes effect within one tick interval without
32+
// a server restart.
33+
const serverSettings = yield* ServerSettingsService;
2934

3035
const tickIntervalMs = Math.max(1, options?.tickIntervalMs ?? DEFAULT_TICK_INTERVAL_MS);
3136

3237
const tickEffect: TaskSchedulerShape["tick"] = Effect.fn("TaskScheduler.tick")(function* () {
38+
// Disabled is the cheap path: no due-scan, no dispatch. Stored tasks
39+
// are untouched — their nextFireAt keeps aging and fires coalesce into
40+
// the first future slot when re-enabled (decider's drift anchoring).
41+
// A failed settings read fails open: the tick behaves as before the
42+
// switch existed rather than silently disabling automation.
43+
const enabled = yield* serverSettings.getSettings.pipe(
44+
Effect.map((settings) => settings.enableScheduledTasks),
45+
Effect.catchCause((cause) =>
46+
Effect.logWarning("task.scheduler.settings-read-failed", { cause }).pipe(Effect.as(true)),
47+
),
48+
);
49+
if (!enabled) {
50+
return 0;
51+
}
3352
// ISO strings compare lexicographically, but the query uses SQLite
3453
// string comparison on next_fire_at — pass the same normalized format
3554
// the projector writes.

‎apps/server/src/serverSettings.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,24 @@ it.layer(NodeServices.layer)("server settings", (it) => {
116116
}),
117117
);
118118

119+
it.effect("round-trips the scheduled tasks feature switch", () =>
120+
Effect.gen(function* () {
121+
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
122+
123+
assert.equal(DEFAULT_SERVER_SETTINGS.enableScheduledTasks, true);
124+
125+
const disabled = yield* serverSettings.updateSettings({ enableScheduledTasks: false });
126+
assert.equal(disabled.enableScheduledTasks, false);
127+
// Persisted sparsely (non-default only) and reloaded cleanly.
128+
const reloaded = yield* serverSettings.getSettings;
129+
assert.equal(reloaded.enableScheduledTasks, false);
130+
131+
yield* serverSettings.updateSettings({ enableScheduledTasks: true });
132+
const restored = yield* serverSettings.getSettings;
133+
assert.equal(restored.enableScheduledTasks, true);
134+
}).pipe(Effect.provide(makeServerSettingsLayer())),
135+
);
136+
119137
it.effect(
120138
"decodes legacy object-shaped textGenerationModelSelection.options from settings.json",
121139
() =>

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

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
/**
22
* Integrations settings - preferences for surfaces T3 Code embeds rather than
3-
* owns. Browser is the first section: the defaults a preview tab opens at,
4-
* applied to both hand-opened tabs and agent `preview_open` calls that don't
5-
* state their own size.
3+
* owns. Automation covers server-side scheduled runs; Browser holds the
4+
* defaults a preview tab opens at, applied to both hand-opened tabs and agent
5+
* `preview_open` calls that don't state their own size.
66
*
77
* @module IntegrationsSettings
88
*/
@@ -355,6 +355,37 @@ function BrowserAppearanceSetting({ disabled }: { readonly disabled: boolean })
355355
);
356356
}
357357

358+
function ScheduledTasksSetting() {
359+
const settings = usePrimarySettings();
360+
const updateSettings = useUpdatePrimarySettings();
361+
362+
return (
363+
<SettingsRow
364+
{...searchableSetting("scheduled-tasks")}
365+
description="Let T3 Code start agent runs at their scheduled times — nightly chores, delayed follow-ups, recurring work. When off, nothing fires and the per-project schedule UI hides; stored schedules resume where they left off when turned back on."
366+
resetAction={
367+
settings.enableScheduledTasks !== DEFAULT_UNIFIED_SETTINGS.enableScheduledTasks ? (
368+
<SettingResetButton
369+
label="scheduled tasks"
370+
onClick={() =>
371+
updateSettings({
372+
enableScheduledTasks: DEFAULT_UNIFIED_SETTINGS.enableScheduledTasks,
373+
})
374+
}
375+
/>
376+
) : null
377+
}
378+
control={
379+
<Switch
380+
checked={settings.enableScheduledTasks}
381+
onCheckedChange={(checked) => updateSettings({ enableScheduledTasks: Boolean(checked) })}
382+
aria-label="Enable scheduled tasks"
383+
/>
384+
}
385+
/>
386+
);
387+
}
388+
358389
function AgentBrowserAccessSetting() {
359390
const settings = usePrimarySettings();
360391
const updateSettings = useUpdatePrimarySettings();
@@ -467,6 +498,9 @@ export function IntegrationsSettingsPanel() {
467498

468499
return (
469500
<SettingsPageContainer>
501+
<SettingsSection id="automation" title="Automation">
502+
<ScheduledTasksSetting />
503+
</SettingsSection>
470504
<SettingsSection id="browser" title="Browser">
471505
{/* Server-authoritative, so it stays editable on every client and sits
472506
outside the block covering the desktop-only defaults. */}

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

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1145,15 +1145,17 @@ function ProjectDetail({ group }: { group: SidebarProjectSnapshot }) {
11451145
) : null}
11461146
</SettingsSection>
11471147

1148-
<ScheduledTasksSection
1149-
environmentId={representative.environmentId}
1150-
projectId={representative.id}
1151-
threads={threads.filter(
1152-
(thread) =>
1153-
thread.environmentId === representative.environmentId &&
1154-
thread.projectId === representative.id,
1155-
)}
1156-
/>
1148+
{settings.enableScheduledTasks ? (
1149+
<ScheduledTasksSection
1150+
environmentId={representative.environmentId}
1151+
projectId={representative.id}
1152+
threads={threads.filter(
1153+
(thread) =>
1154+
thread.environmentId === representative.environmentId &&
1155+
thread.projectId === representative.id,
1156+
)}
1157+
/>
1158+
) : null}
11571159

11581160
<SettingsSection title="Danger">
11591161
<SettingsRow

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -540,6 +540,9 @@ export function useSettingsRestore(onRestored?: () => void) {
540540
...(settings.enableAgentBrowserAccess !== DEFAULT_UNIFIED_SETTINGS.enableAgentBrowserAccess
541541
? ["Agent browser access"]
542542
: []),
543+
...(settings.enableScheduledTasks !== DEFAULT_UNIFIED_SETTINGS.enableScheduledTasks
544+
? ["Scheduled tasks"]
545+
: []),
543546
],
544547
[
545548
isTextGenerationModelDirty,
@@ -550,6 +553,7 @@ export function useSettingsRestore(onRestored?: () => void) {
550553
settings.browserAutoShowFloatingPreview,
551554
settings.appearanceContrast,
552555
settings.enableAgentBrowserAccess,
556+
settings.enableScheduledTasks,
553557
settings.confirmQuit,
554558
settings.confirmThreadArchive,
555559
settings.confirmThreadDelete,
@@ -683,6 +687,7 @@ export function useSettingsRestore(onRestored?: () => void) {
683687
// name, so a user restoring defaults is told the agent regains access
684688
// rather than discovering it later.
685689
enableAgentBrowserAccess: DEFAULT_UNIFIED_SETTINGS.enableAgentBrowserAccess,
690+
enableScheduledTasks: DEFAULT_UNIFIED_SETTINGS.enableScheduledTasks,
686691
});
687692
onRestored?.();
688693
}, [

‎apps/web/src/components/settings/settingsSearch.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,12 @@ export const SETTINGS_SEARCH_ITEMS = [
209209
to: "/settings/integrations",
210210
targetId: "browser",
211211
},
212+
{
213+
id: "scheduled-tasks",
214+
title: "Scheduled tasks",
215+
to: "/settings/integrations",
216+
targetId: "automation",
217+
},
212218
{
213219
id: "browser-default-viewport",
214220
title: "Default browser viewport",

‎docs/user/scheduled-tasks.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,14 @@ uses the thread's model selection and permission mode.
2323
Open **Settings → Projects → Scheduled tasks** and select **Cancel** next to the task.
2424
Cancelled tasks stay visible until the panel is refreshed elsewhere.
2525

26+
## Turn the feature off
27+
28+
Open **Settings → Integrations → Automation** and turn off **Scheduled tasks**. The
29+
server stops starting runs at due times and the per-project schedule UI hides on every
30+
connected client. Nothing is deleted: stored schedules keep their times and resume —
31+
with missed fires coalescing into one, like any other downtime — when you turn the
32+
feature back on.
33+
2634
## Good to know
2735

2836
- Tasks are stored with your server's data and survive restarts. If the server is down

‎packages/contracts/src/settings.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -616,6 +616,19 @@ export const ServerSettings = Schema.Struct({
616616
* between a desktop window and a phone attached to the same server.
617617
*/
618618
enableAgentBrowserAccess: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
619+
/**
620+
* Whether the server's task scheduler may start agent turns at their due
621+
* times. Turning this off stops the scheduler from dispatching `task.fire`
622+
* for due tasks — existing schedules stay stored and resume untouched when
623+
* the feature is turned back on (missed fires coalesce into one, exactly
624+
* like downtime). Clients read the same flag through `serverGetConfig` to
625+
* hide the schedule UI everywhere at once.
626+
*
627+
* Server-authoritative rather than client-local: firing happens on the
628+
* server even with no client open, so a client-side switch could not
629+
* actually stop anything.
630+
*/
631+
enableScheduledTasks: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
619632
backgroundActivity: BackgroundActivitySettings,
620633
// Legacy flat fields retained for old settings files and old clients. New
621634
// consumers should resolve `backgroundActivity` instead.
@@ -824,6 +837,7 @@ export const ServerSettingsPatch = Schema.Struct({
824837
enableLegacyTokenStreaming: Schema.optionalKey(Schema.Boolean),
825838
enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean),
826839
enableAgentBrowserAccess: Schema.optionalKey(Schema.Boolean),
840+
enableScheduledTasks: Schema.optionalKey(Schema.Boolean),
827841
backgroundActivity: Schema.optionalKey(
828842
Schema.Struct({
829843
schemaVersion: Schema.optionalKey(Schema.Literal(1)),

0 commit comments

Comments
 (0)