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