Open History to see the last commit
1import {
2 CommandId,
3 MessageId,
4 ScheduledTask,
5 ScheduledTaskError,
6 ScheduledTaskId,
7 ThreadId,
8 type ScheduledTaskDeleteInput,
9 type ScheduledTaskDeleteResult,
10 type ScheduledTaskListResult,
11 type ScheduledTaskMutationResult,
12 type ScheduledTaskRunNowInput,
13 type ScheduledTaskRunNowResult,
14 type ScheduledTaskSetEnabledInput,
15 type ScheduledTaskUpsertInput,
16} from "@t3tools/contracts";
17import * as Cause from "effect/Cause";
18import * as Context from "effect/Context";
19import * as Crypto from "effect/Crypto";
20import * as DateTime from "effect/DateTime";
21import * as Duration from "effect/Duration";
22import * as Effect from "effect/Effect";
23import * as Layer from "effect/Layer";
24import * as PubSub from "effect/PubSub";
25import * as Ref from "effect/Ref";
26import * as Result from "effect/Result";
27import * as Schema from "effect/Schema";
28import * as Stream from "effect/Stream";
29import * as SqlClient from "effect/unstable/sql/SqlClient";
30
31import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts";
32import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
33import { isMissedFixedTimeRun, isSameSchedule, nextScheduledRunAt } from "./Schedule.ts";
34
35const decodeTask = Schema.decodeUnknownEffect(ScheduledTask);
36const decodeScheduleJson = Schema.decodeUnknownEffect(
37 Schema.fromJsonString(ScheduledTask.fields.schedule),
38);
39const decodeWorkspaceStrategyJson = Schema.decodeUnknownEffect(
40 Schema.fromJsonString(ScheduledTask.fields.workspaceStrategy),
41);
42const decodeModelSelectionJson = Schema.decodeUnknownEffect(
43 Schema.fromJsonString(ScheduledTask.fields.modelSelection),
44);
45
46interface ScheduledTaskRow {
47 readonly task_id: string;
48 readonly title: string;
49 readonly prompt: string;
50 readonly enabled: number;
51 readonly schedule_json: string;
52 readonly project_id: string;
53 readonly thread_id: string | null;
54 readonly workspace_strategy_json: string;
55 readonly model_selection_json: string;
56 readonly runtime_mode: string;
57 readonly interaction_mode: string;
58 readonly created_by: string;
59 readonly creation_source: string;
60 readonly created_at: string;
61 readonly updated_at: string;
62 readonly next_run_at: string | null;
63 readonly last_run_at: string | null;
64 readonly last_run_status: string;
65 readonly last_run_error: string | null;
66 readonly run_count: number;
67}
68
69export class ScheduledTaskService extends Context.Service<
70 ScheduledTaskService,
71 {
72 readonly list: () => Effect.Effect<ScheduledTaskListResult, ScheduledTaskError>;
73 /** Emits the full task list on subscribe and again after every change (CRUD, run transitions, reschedules). */
74 readonly subscribeList: () => Stream.Stream<ScheduledTaskListResult, ScheduledTaskError>;
75 readonly upsert: (
76 input: ScheduledTaskUpsertInput,
77 ) => Effect.Effect<ScheduledTaskMutationResult, ScheduledTaskError>;
78 /** Partial update flipping only the enabled flag; never touches other fields. */
79 readonly setEnabled: (
80 input: ScheduledTaskSetEnabledInput,
81 ) => Effect.Effect<ScheduledTaskMutationResult, ScheduledTaskError>;
82 readonly delete: (
83 input: ScheduledTaskDeleteInput,
84 ) => Effect.Effect<ScheduledTaskDeleteResult, ScheduledTaskError>;
85 readonly runNow: (
86 input: ScheduledTaskRunNowInput,
87 ) => Effect.Effect<ScheduledTaskRunNowResult, ScheduledTaskError>;
88 }
89>()("t3/scheduledTasks/ScheduledTaskService") {}
90
91function taskError(message: string, input?: { taskId?: ScheduledTaskId; cause?: unknown }) {
92 return new ScheduledTaskError({
93 message,
94 ...(input?.taskId === undefined ? {} : { taskId: input.taskId }),
95 ...(input?.cause === undefined ? {} : { cause: input.cause }),
96 });
97}
98
99function iso(value: DateTime.DateTime): string {
100 return DateTime.formatIso(DateTime.toUtc(value));
101}
102
103const localNow = DateTime.withCurrentZoneLocal(DateTime.nowInCurrentZone);
104
105function nextRunAt(
106 task: Pick<ScheduledTask, "enabled" | "schedule">,
107 from: DateTime.DateTime,
108): string | null {
109 if (!task.enabled) return null;
110 const next = nextScheduledRunAt(task.schedule, from);
111 return next === null ? null : iso(next);
112}
113
114function errorMessage(error: unknown): string {
115 if (Cause.isCause(error)) return Cause.pretty(error);
116 if (error instanceof Error) return error.message;
117 return String(error);
118}
119
120const decodeRow = (row: ScheduledTaskRow) =>
121 Effect.gen(function* () {
122 const id = ScheduledTaskId.make(row.task_id);
123 const schedule = yield* decodeScheduleJson(row.schedule_json);
124 const workspaceStrategy = yield* decodeWorkspaceStrategyJson(row.workspace_strategy_json);
125 const modelSelection = yield* decodeModelSelectionJson(row.model_selection_json);
126 return yield* decodeTask({
127 id,
128 title: row.title,
129 prompt: row.prompt,
130 enabled: row.enabled === 1,
131 schedule,
132 projectId: row.project_id,
133 threadId: row.thread_id,
134 workspaceStrategy,
135 modelSelection,
136 runtimeMode: row.runtime_mode,
137 interactionMode: row.interaction_mode,
138 createdBy: row.created_by,
139 creationSource: row.creation_source,
140 createdAt: row.created_at,
141 updatedAt: row.updated_at,
142 nextRunAt: row.next_run_at,
143 lastRunAt: row.last_run_at,
144 lastRunStatus: row.last_run_status,
145 lastRunError: row.last_run_error,
146 runCount: row.run_count,
147 });
148 }).pipe(
149 Effect.mapError((cause) =>
150 taskError("Could not decode schedule task row.", {
151 taskId: ScheduledTaskId.make(row.task_id),
152 cause,
153 }),
154 ),
155 );
156
157/** Select poll candidates before decoding their schedules or other JSON payloads. */
158export const listDueTasks = Effect.fn("ScheduledTaskService.listDueTasks")(function* (
159 now: DateTime.DateTime,
160) {
161 const sql = yield* SqlClient.SqlClient;
162 const rows = yield* sql<ScheduledTaskRow>`
163 SELECT * FROM scheduled_tasks
164 WHERE enabled = 1 AND next_run_at IS NOT NULL
165 AND next_run_at <= ${iso(now)} AND last_run_status <> 'running'
166 ORDER BY next_run_at ASC, task_id ASC
167 `;
168 const tasks: ScheduledTask[] = [];
169 for (const row of rows) {
170 const decoded = yield* Effect.result(decodeRow(row));
171 if (Result.isSuccess(decoded)) {
172 tasks.push(decoded.success);
173 } else {
174 yield* Effect.logWarning("Skipping undecodable schedule task row", {
175 taskId: row.task_id,
176 cause: decoded.failure,
177 });
178 }
179 }
180 return tasks;
181});
182
183export const layer = Layer.effect(
184 ScheduledTaskService,
185 Effect.gen(function* () {
186 const sql = yield* SqlClient.SqlClient;
187 const crypto = yield* Crypto.Crypto;
188 const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService;
189 const threadManagement = yield* ThreadManagementService.ThreadManagementService;
190 const activeRuns = yield* Ref.make<ReadonlySet<ScheduledTaskId>>(new Set());
191 // Sliding(1) coalesces the dirty-signal: every notification triggers a
192 // full list() re-emit anyway, so a slow subscriber only ever needs the
193 // latest signal — an unbounded backlog would just grow memory.
194 const changesPubSub = yield* PubSub.sliding<void>(1);
195 const notifyChanged = PubSub.publish(changesPubSub, undefined).pipe(Effect.asVoid);
196
197 const selectAllRows = () => sql<ScheduledTaskRow>`
198 SELECT
199 task_id,
200 title,
201 prompt,
202 enabled,
203 schedule_json,
204 project_id,
205 thread_id,
206 workspace_strategy_json,
207 model_selection_json,
208 runtime_mode,
209 interaction_mode,
210 created_by,
211 creation_source,
212 created_at,
213 updated_at,
214 next_run_at,
215 last_run_at,
216 last_run_status,
217 last_run_error,
218 run_count
219 FROM scheduled_tasks
220 ORDER BY updated_at DESC, task_id ASC
221 `;
222
223 // Strict decode for the API surface: a corrupt row is a visible error.
224 const listRows = Effect.fn("ScheduledTaskService.listRows")(function* () {
225 const rows = yield* selectAllRows();
226 return yield* Effect.forEach(rows, decodeRow, { concurrency: 1 });
227 });
228
229 const getRows = (id: ScheduledTaskId) => sql<ScheduledTaskRow>`
230 SELECT
231 task_id,
232 title,
233 prompt,
234 enabled,
235 schedule_json,
236 project_id,
237 thread_id,
238 workspace_strategy_json,
239 model_selection_json,
240 runtime_mode,
241 interaction_mode,
242 created_by,
243 creation_source,
244 created_at,
245 updated_at,
246 next_run_at,
247 last_run_at,
248 last_run_status,
249 last_run_error,
250 run_count
251 FROM scheduled_tasks
252 WHERE task_id = ${id}
253 `;
254
255 /** Load a task, returning `null` when it does not exist; real load/decode failures propagate. */
256 const findTask = Effect.fn("ScheduledTaskService.findTask")(function* (id: ScheduledTaskId) {
257 const rows = yield* getRows(id).pipe(
258 Effect.mapError((cause) =>
259 taskError("Could not load schedule task.", { taskId: id, cause }),
260 ),
261 );
262 const row = rows[0];
263 if (row === undefined) return null;
264 return yield* decodeRow(row);
265 });
266
267 const loadTask = Effect.fn("ScheduledTaskService.loadTask")(function* (id: ScheduledTaskId) {
268 const task = yield* findTask(id);
269 if (task === null) {
270 return yield* taskError("Schedule task not found.", { taskId: id });
271 }
272 return task;
273 });
274
275 // Run-state columns (last_run_*, run_count) are intentionally absent from
276 // the conflict clause: they are owned by the run transitions below, and a
277 // concurrent settings save must not overwrite an in-flight increment.
278 const saveTask = (task: ScheduledTask) =>
279 sql`
280 INSERT INTO scheduled_tasks (
281 task_id,
282 title,
283 prompt,
284 enabled,
285 schedule_json,
286 project_id,
287 thread_id,
288 workspace_strategy_json,
289 model_selection_json,
290 runtime_mode,
291 interaction_mode,
292 created_by,
293 creation_source,
294 created_at,
295 updated_at,
296 next_run_at,
297 last_run_at,
298 last_run_status,
299 last_run_error,
300 run_count
301 )
302 VALUES (
303 ${task.id},
304 ${task.title},
305 ${task.prompt},
306 ${task.enabled ? 1 : 0},
307 ${JSON.stringify(task.schedule)},
308 ${task.projectId},
309 ${task.threadId},
310 ${JSON.stringify(task.workspaceStrategy)},
311 ${JSON.stringify(task.modelSelection)},
312 ${task.runtimeMode},
313 ${task.interactionMode},
314 ${task.createdBy},
315 ${task.creationSource},
316 ${task.createdAt},
317 ${task.updatedAt},
318 ${task.nextRunAt},
319 ${task.lastRunAt},
320 ${task.lastRunStatus},
321 ${task.lastRunError},
322 ${task.runCount}
323 )
324 ON CONFLICT (task_id)
325 DO UPDATE SET
326 title = excluded.title,
327 prompt = excluded.prompt,
328 enabled = excluded.enabled,
329 schedule_json = excluded.schedule_json,
330 project_id = excluded.project_id,
331 thread_id = excluded.thread_id,
332 workspace_strategy_json = excluded.workspace_strategy_json,
333 model_selection_json = excluded.model_selection_json,
334 runtime_mode = excluded.runtime_mode,
335 interaction_mode = excluded.interaction_mode,
336 creation_source = excluded.creation_source,
337 updated_at = excluded.updated_at,
338 next_run_at = excluded.next_run_at
339 `.pipe(
340 Effect.mapError((cause) =>
341 taskError("Could not save schedule task.", { taskId: task.id, cause }),
342 ),
343 );
344
345 const deleteRow = (id: ScheduledTaskId) =>
346 sql`DELETE FROM scheduled_tasks WHERE task_id = ${id}`.pipe(
347 Effect.mapError((cause) =>
348 taskError("Could not delete schedule task.", { taskId: id, cause }),
349 ),
350 );
351
352 // Run-state transitions use targeted UPDATEs (never the full-row upsert) so
353 // a completing run cannot resurrect a deleted task or clobber concurrent
354 // edits to the task definition.
355 const markRunning = (id: ScheduledTaskId, startedAtIso: string) =>
356 sql`
357 UPDATE scheduled_tasks
358 SET updated_at = ${startedAtIso},
359 last_run_at = ${startedAtIso},
360 last_run_status = 'running',
361 last_run_error = NULL
362 WHERE task_id = ${id}
363 `.pipe(
364 Effect.mapError((cause) =>
365 taskError("Could not mark schedule task as running.", { taskId: id, cause }),
366 ),
367 );
368
369 const markCompleted = (input: {
370 readonly id: ScheduledTaskId;
371 readonly completedAtIso: string;
372 readonly nextRunAtIso: string | null;
373 readonly status: "succeeded" | "failed";
374 readonly error: string | null;
375 readonly startedAtIso: string;
376 }) =>
377 sql`
378 UPDATE scheduled_tasks
379 SET updated_at = ${input.completedAtIso},
380 next_run_at = ${input.nextRunAtIso},
381 last_run_status = ${input.status},
382 last_run_error = ${input.error},
383 run_count = run_count + 1
384 WHERE task_id = ${input.id}
385 AND last_run_status = 'running'
386 AND last_run_at = ${input.startedAtIso}
387 `.pipe(
388 Effect.mapError((cause) =>
389 taskError("Could not record schedule task run.", { taskId: input.id, cause }),
390 ),
391 );
392
393 // Best-effort escape hatch: if anything fails between markRunning and
394 // markCompleted, write a full terminal record so runDueTasks neither skips
395 // the task forever (it filters out 'running' rows) nor re-fires it
396 // immediately: the dispatch may already have gone out, so next_run_at must
397 // advance and run_count must count the attempt.
398 const releaseStuckRun = (task: ScheduledTask, message: string) =>
399 Effect.gen(function* () {
400 const now = yield* localNow;
401 // Compute the next occurrence from the current row so a schedule
402 // edited while the run was in flight is honoured; fall back to the
403 // run's snapshot only if the re-read itself fails.
404 const reread = yield* Effect.result(findTask(task.id));
405 if (Result.isSuccess(reread) && reread.success === null) return; // deleted — nothing to release
406 const source = Result.isSuccess(reread) && reread.success !== null ? reread.success : task;
407 yield* sql`
408 UPDATE scheduled_tasks
409 SET last_run_status = 'failed',
410 last_run_error = ${message},
411 next_run_at = ${nextRunAt(source, now)},
412 updated_at = ${iso(now)},
413 run_count = run_count + 1
414 WHERE task_id = ${task.id} AND last_run_status = 'running'
415 `;
416 yield* notifyChanged;
417 }).pipe(
418 Effect.catch((cause) =>
419 Effect.logWarning("Could not release stuck schedule task run", {
420 taskId: task.id,
421 cause,
422 }),
423 ),
424 );
425
426 const runTask = Effect.fn("ScheduledTaskService.runTask")(function* (
427 task: ScheduledTask,
428 trigger: "scheduled" | "manual",
429 ) {
430 const reserved = yield* Ref.modify(activeRuns, (active) => {
431 if (active.has(task.id)) return [false, active] as const;
432 const next = new Set(active);
433 next.add(task.id);
434 return [true, next] as const;
435 });
436 if (!reserved) {
437 if (trigger === "manual") {
438 return yield* taskError("Schedule task is already running.", { taskId: task.id });
439 }
440 return task;
441 }
442
443 return yield* Effect.gen(function* () {
444 const startedAt = yield* localNow;
445 const startedAtIso = iso(startedAt);
446
447 // The in-memory snapshot may be stale: re-read before touching run
448 // state. The task may have been deleted, paused, or postponed since
449 // the poll loaded it — none of those may fire.
450 const active = yield* findTask(task.id);
451 if (active === null) {
452 // A manual run on a just-deleted task must fail loudly, not report
453 // a successful run that never dispatched.
454 if (trigger === "manual") {
455 return yield* taskError("Schedule task not found.", { taskId: task.id });
456 }
457 return task;
458 }
459 if (
460 trigger === "scheduled" &&
461 (!active.enabled ||
462 active.nextRunAt === null ||
463 DateTime.toEpochMillis(DateTime.makeUnsafe(active.nextRunAt)) >
464 DateTime.toEpochMillis(startedAt))
465 ) {
466 return active;
467 }
468
469 yield* markRunning(active.id, startedAtIso);
470 yield* notifyChanged;
471
472 const fireKey = `${active.id}:${DateTime.toEpochMillis(startedAt)}:${trigger}`;
473 const commandId = CommandId.make(`scheduled-task:${fireKey}`);
474 const messageId = MessageId.make(`scheduled-task-message:${fireKey}`);
475 // Dispatch from the fresh row so prompt/model/binding edits made
476 // after the poll read are honoured.
477 const prompt = active.prompt;
478
479 // Effect.exit (not Effect.result) so defects and interruptions in the
480 // dispatch are also captured and recorded as a failed run instead of
481 // aborting before markCompleted.
482 const result =
483 active.threadId === null
484 ? yield* Effect.exit(
485 threadLaunch.launch({
486 commandId,
487 projectId: active.projectId,
488 title: active.title,
489 modelSelection: active.modelSelection,
490 runtimeMode: active.runtimeMode,
491 interactionMode: active.interactionMode,
492 workspaceStrategy: active.workspaceStrategy,
493 initialMessage: {
494 messageId,
495 scheduledTaskId: active.id,
496 text: prompt,
497 attachments: [],
498 },
499 createdBy: active.createdBy,
500 creationSource: active.creationSource,
501 }),
502 )
503 : yield* Effect.exit(
504 threadManagement.sendToThread({
505 projectId: active.projectId,
506 commandId,
507 threadId: ThreadId.make(active.threadId),
508 messageId,
509 scheduledTaskId: active.id,
510 text: prompt,
511 attachments: [],
512 modelSelection: active.modelSelection,
513 mode: "auto",
514 createdBy: active.createdBy,
515 creationSource: active.creationSource,
516 }),
517 );
518
519 const completedAt = yield* localNow;
520 const runSucceeded = result._tag === "Success";
521 const lastRunStatus = runSucceeded ? ("succeeded" as const) : ("failed" as const);
522 const lastRunError = runSucceeded ? null : errorMessage(result.cause);
523 // Re-read the task so the next run is computed from the schedule as it
524 // is *now* (the user may have edited or deleted it while we ran).
525 const current = yield* findTask(task.id);
526 const scheduleSource = current ?? task;
527 const completed: ScheduledTask = {
528 ...scheduleSource,
529 updatedAt: iso(completedAt),
530 lastRunAt: startedAtIso,
531 nextRunAt: nextRunAt(scheduleSource, completedAt),
532 lastRunStatus,
533 lastRunError,
534 runCount: scheduleSource.runCount + 1,
535 };
536 if (current !== null) {
537 // startedAtIso in the guard ensures this writes only to the row this
538 // run marked as running — a task deleted mid-run and recreated with
539 // the same id (idempotent commandId replay) must not be stamped.
540 yield* markCompleted({
541 id: task.id,
542 completedAtIso: completed.updatedAt,
543 nextRunAtIso: completed.nextRunAt,
544 status: lastRunStatus,
545 error: lastRunError,
546 startedAtIso,
547 });
548 yield* notifyChanged;
549 }
550 return completed;
551 }).pipe(
552 Effect.onError((cause) => releaseStuckRun(task, errorMessage(cause))),
553 Effect.ensuring(
554 Ref.update(activeRuns, (active) => {
555 const next = new Set(active);
556 next.delete(task.id);
557 return next;
558 }),
559 ),
560 );
561 });
562
563 // A due fixed-time run that is long past its slot (server was off or
564 // asleep) is skipped and re-aimed at its next occurrence, not fired late.
565 const rescheduleMissedRun = Effect.fn("ScheduledTaskService.rescheduleMissedRun")(function* (
566 task: ScheduledTask,
567 now: DateTime.DateTime,
568 ) {
569 const next = nextRunAt(task, now);
570 yield* Effect.logInfo("Skipping missed schedule task run", {
571 taskId: task.id,
572 missedRunAt: task.nextRunAt,
573 rescheduledTo: next,
574 });
575 yield* sql`
576 UPDATE scheduled_tasks
577 SET next_run_at = ${next},
578 updated_at = ${iso(now)}
579 WHERE task_id = ${task.id}
580 `.pipe(
581 Effect.mapError((cause) =>
582 taskError("Could not reschedule missed schedule task run.", { taskId: task.id, cause }),
583 ),
584 );
585 yield* notifyChanged;
586 });
587
588 const runDueTasks = Effect.fn("ScheduledTaskService.runDueTasks")(function* () {
589 const now = yield* localNow;
590 const tasks = yield* listDueTasks(now).pipe(
591 Effect.mapError((cause) => taskError("Could not list schedule tasks.", { cause })),
592 );
593 const due = tasks.flatMap((task) =>
594 task.nextRunAt === null ? [] : [{ task, dueAt: DateTime.makeUnsafe(task.nextRunAt) }],
595 );
596 yield* Effect.forEach(
597 due,
598 ({ task, dueAt }) =>
599 (isMissedFixedTimeRun(task.schedule, dueAt, now)
600 ? rescheduleMissedRun(task, now)
601 : runTask(task, "scheduled")
602 ).pipe(
603 Effect.catch((cause) =>
604 Effect.logWarning("Scheduled task run failed", { taskId: task.id, cause }),
605 ),
606 ),
607 { concurrency: 1, discard: true },
608 );
609 });
610
611 // Recover from a crash or hard shutdown mid-run: rows stuck in 'running'
612 // would otherwise be skipped by the due-task filter forever. The dispatch
613 // may already have gone out before the crash, so next_run_at must advance
614 // and run_count must count the attempt — otherwise the first poll after
615 // every restart re-fires the interrupted task (same rationale as
616 // releaseStuckRun). Schedules are JSON, so this is per-row Effect work
617 // rather than a single UPDATE.
618 yield* Effect.gen(function* () {
619 const rows = yield* selectAllRows();
620 const stuck = rows.filter((row) => row.last_run_status === "running");
621 if (stuck.length === 0) return;
622 const now = yield* localNow;
623 yield* Effect.forEach(
624 stuck,
625 (row) =>
626 Effect.gen(function* () {
627 const decoded = yield* Effect.result(decodeRow(row));
628 if (Result.isSuccess(decoded)) {
629 yield* sql`
630 UPDATE scheduled_tasks
631 SET last_run_status = 'failed',
632 last_run_error = 'Run was interrupted by a server restart.',
633 next_run_at = ${nextRunAt(decoded.success, now)},
634 updated_at = ${iso(now)},
635 run_count = run_count + 1
636 WHERE task_id = ${row.task_id} AND last_run_status = 'running'
637 `;
638 return;
639 }
640 // The schedule cannot be decoded, so the next occurrence cannot
641 // be computed — still release the row so it is not stuck in
642 // 'running' (the lenient poller skips it, so it cannot re-fire).
643 yield* Effect.logWarning(
644 "Recovering undecodable schedule task row without rescheduling",
645 { taskId: row.task_id, cause: decoded.failure },
646 );
647 yield* sql`
648 UPDATE scheduled_tasks
649 SET last_run_status = 'failed',
650 last_run_error = 'Run was interrupted by a server restart.',
651 updated_at = ${iso(now)},
652 run_count = run_count + 1
653 WHERE task_id = ${row.task_id} AND last_run_status = 'running'
654 `;
655 }),
656 { concurrency: 1, discard: true },
657 );
658 yield* notifyChanged;
659 }).pipe(
660 Effect.catch((cause) =>
661 Effect.logWarning("Could not reset interrupted schedule task runs", { cause }),
662 ),
663 );
664
665 yield* runDueTasks().pipe(
666 Effect.catch((cause) => Effect.logWarning("Scheduled task polling failed", { cause })),
667 Effect.delay(Duration.seconds(5)),
668 Effect.forever,
669 Effect.forkScoped,
670 );
671
672 const list: ScheduledTaskService["Service"]["list"] = () =>
673 listRows().pipe(
674 Effect.map((tasks) => ({ tasks })),
675 Effect.mapError((cause) => taskError("Could not list schedule tasks.", { cause })),
676 );
677
678 const subscribeList: ScheduledTaskService["Service"]["subscribeList"] = () =>
679 Stream.unwrap(
680 Effect.gen(function* () {
681 // Subscribe before taking the snapshot so a change landing between
682 // the two is buffered by the subscription rather than dropped.
683 const subscription = yield* PubSub.subscribe(changesPubSub);
684 return Stream.concat(
685 Stream.fromEffect(list()),
686 Stream.fromSubscription(subscription).pipe(Stream.mapEffect(() => list())),
687 );
688 }),
689 );
690
691 const upsert: ScheduledTaskService["Service"]["upsert"] = (input) =>
692 Effect.gen(function* () {
693 const now = yield* localNow;
694 const uuid =
695 input.commandId === undefined
696 ? yield* crypto.randomUUIDv4.pipe(
697 Effect.mapError((cause) =>
698 taskError("Could not generate schedule task id.", { cause }),
699 ),
700 )
701 : null;
702 const id =
703 input.id ??
704 ScheduledTaskId.make(
705 input.commandId ? `scheduled-task:${input.commandId}` : `scheduled-task:${uuid}`,
706 );
707 // Look up by the *resolved* id so idempotent creates (commandId replays)
708 // keep their run history, and so real load failures propagate instead
709 // of silently resetting an existing row.
710 const existingTask = yield* findTask(id);
711 // Keep the existing next_run_at when the schedule itself is untouched:
712 // editing a title or prompt must not postpone (or resurrect) a due
713 // run — only schedule/enabled changes restart the clock.
714 const scheduleUnchanged =
715 existingTask !== null &&
716 existingTask.enabled === input.enabled &&
717 isSameSchedule(existingTask.schedule, input.schedule);
718 const task: ScheduledTask = {
719 id,
720 title: input.title,
721 prompt: input.prompt,
722 enabled: input.enabled,
723 schedule: input.schedule,
724 projectId: input.projectId,
725 threadId: input.threadId ?? null,
726 workspaceStrategy: input.workspaceStrategy,
727 modelSelection: input.modelSelection,
728 runtimeMode: input.runtimeMode,
729 interactionMode: input.interactionMode,
730 createdBy: existingTask?.createdBy ?? input.createdBy ?? "user",
731 creationSource: input.creationSource ?? "web",
732 createdAt: existingTask?.createdAt ?? iso(now),
733 updatedAt: iso(now),
734 nextRunAt: scheduleUnchanged
735 ? existingTask.nextRunAt
736 : nextRunAt({ enabled: input.enabled, schedule: input.schedule }, now),
737 lastRunAt: existingTask?.lastRunAt ?? null,
738 lastRunStatus: existingTask?.lastRunStatus ?? "never",
739 lastRunError: existingTask?.lastRunError ?? null,
740 runCount: existingTask?.runCount ?? 0,
741 };
742 yield* saveTask(task);
743 yield* notifyChanged;
744 return { task };
745 });
746
747 const setEnabled: ScheduledTaskService["Service"]["setEnabled"] = (input) =>
748 Effect.gen(function* () {
749 const existing = yield* loadTask(input.id);
750 if (existing.enabled === input.enabled) return { task: existing };
751 const now = yield* localNow;
752 const next = nextRunAt({ enabled: input.enabled, schedule: existing.schedule }, now);
753 // RETURNING so a task deleted between the load and this UPDATE is a
754 // visible not-found error, not a false success.
755 const updated = yield* sql<{ task_id: string }>`
756 UPDATE scheduled_tasks
757 SET enabled = ${input.enabled ? 1 : 0},
758 next_run_at = ${next},
759 updated_at = ${iso(now)}
760 WHERE task_id = ${input.id}
761 RETURNING task_id
762 `.pipe(
763 Effect.mapError((cause) =>
764 taskError("Could not update schedule task.", { taskId: input.id, cause }),
765 ),
766 );
767 if (updated.length === 0) {
768 return yield* taskError("Schedule task not found.", { taskId: input.id });
769 }
770 yield* notifyChanged;
771 return {
772 task: { ...existing, enabled: input.enabled, nextRunAt: next, updatedAt: iso(now) },
773 };
774 });
775
776 const deleteTask: ScheduledTaskService["Service"]["delete"] = (input) =>
777 deleteRow(input.id).pipe(Effect.andThen(notifyChanged), Effect.as({ id: input.id }));
778
779 const runNow: ScheduledTaskService["Service"]["runNow"] = (input: ScheduledTaskRunNowInput) =>
780 Effect.gen(function* () {
781 const task = yield* loadTask(input.id);
782 const next = yield* runTask(task, "manual").pipe(
783 Effect.mapError((cause) =>
784 taskError("Could not run schedule task.", { taskId: input.id, cause }),
785 ),
786 );
787 return { task: next };
788 });
789
790 return ScheduledTaskService.of({
791 list,
792 subscribeList,
793 upsert,
794 setEnabled,
795 delete: deleteTask,
796 runNow,
797 });
798 }),
799);