Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ScheduledTaskService.ts

799 lines29.6 KB

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;
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 });
98​
99function automationPrompt(task: ScheduledTask): string {
100 return `[Triggered by schedule task: ${task.title}]\n\n${task.prompt}`;
102​
103function iso(value: DateTime.DateTime): string {
104 return DateTime.formatIso(DateTime.toUtc(value));
106​
107const localNow = DateTime.withCurrentZoneLocal(DateTime.nowInCurrentZone);
108​
109function nextRunAt(
110 task: Pick<ScheduledTask, "enabled" | "schedule">,
111 from: DateTime.DateTime,
112): string | null {
113 if (!task.enabled) return null;
114 const next = nextScheduledRunAt(task.schedule, from);
115 return next === null ? null : iso(next);
117​
118function errorMessage(error: unknown): string {
119 if (Cause.isCause(error)) return Cause.pretty(error);
120 if (error instanceof Error) return error.message;
121 return String(error);
123​
124const decodeRow = (row: ScheduledTaskRow) =>
125 Effect.gen(function* () {
126 const id = ScheduledTaskId.make(row.task_id);
127 const schedule = yield* decodeScheduleJson(row.schedule_json);
128 const workspaceStrategy = yield* decodeWorkspaceStrategyJson(row.workspace_strategy_json);
129 const modelSelection = yield* decodeModelSelectionJson(row.model_selection_json);
130 return yield* decodeTask({
131 id,
132 title: row.title,
133 prompt: row.prompt,
134 enabled: row.enabled === 1,
135 schedule,
136 projectId: row.project_id,
137 threadId: row.thread_id,
138 workspaceStrategy,
139 modelSelection,
140 runtimeMode: row.runtime_mode,
141 interactionMode: row.interaction_mode,
142 createdBy: row.created_by,
143 creationSource: row.creation_source,
144 createdAt: row.created_at,
145 updatedAt: row.updated_at,
146 nextRunAt: row.next_run_at,
147 lastRunAt: row.last_run_at,
148 lastRunStatus: row.last_run_status,
149 lastRunError: row.last_run_error,
150 runCount: row.run_count,
151 });
152 }).pipe(
153 Effect.mapError((cause) =>
154 taskError("Could not decode schedule task row.", {
155 taskId: ScheduledTaskId.make(row.task_id),
156 cause,
157 }),
158 ),
159 );
160​
161export const layer = Layer.effect(
162 ScheduledTaskService,
163 Effect.gen(function* () {
164 const sql = yield* SqlClient.SqlClient;
165 const crypto = yield* Crypto.Crypto;
166 const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService;
167 const threadManagement = yield* ThreadManagementService.ThreadManagementService;
168 const activeRuns = yield* Ref.make<ReadonlySet<ScheduledTaskId>>(new Set());
169 // Sliding(1) coalesces the dirty-signal: every notification triggers a
170 // full list() re-emit anyway, so a slow subscriber only ever needs the
171 // latest signal — an unbounded backlog would just grow memory.
172 const changesPubSub = yield* PubSub.sliding<void>(1);
173 const notifyChanged = PubSub.publish(changesPubSub, undefined).pipe(Effect.asVoid);
174​
175 const selectAllRows = () => sql<ScheduledTaskRow>`
176 SELECT
177 task_id,
178 title,
179 prompt,
180 enabled,
181 schedule_json,
182 project_id,
183 thread_id,
184 workspace_strategy_json,
185 model_selection_json,
186 runtime_mode,
187 interaction_mode,
188 created_by,
189 creation_source,
190 created_at,
191 updated_at,
192 next_run_at,
193 last_run_at,
194 last_run_status,
195 last_run_error,
196 run_count
197 FROM scheduled_tasks
198 ORDER BY updated_at DESC, task_id ASC
199 `;
200​
201 // Strict decode for the API surface: a corrupt row is a visible error.
202 const listRows = Effect.fn("ScheduledTaskService.listRows")(function* () {
203 const rows = yield* selectAllRows();
204 return yield* Effect.forEach(rows, decodeRow, { concurrency: 1 });
205 });
206​
207 // Lenient decode for the scheduler: one corrupt row must never halt the
208 // poll loop or crash recovery for every other task — skip it and log.
209 const listTasksLenient = Effect.fn("ScheduledTaskService.listTasksLenient")(function* () {
210 const rows = yield* selectAllRows();
211 const tasks: ScheduledTask[] = [];
212 for (const row of rows) {
213 const decoded = yield* Effect.result(decodeRow(row));
214 if (Result.isSuccess(decoded)) {
215 tasks.push(decoded.success);
216 } else {
217 yield* Effect.logWarning("Skipping undecodable schedule task row", {
218 taskId: row.task_id,
219 cause: decoded.failure,
220 });
221 }
222 }
223 return tasks;
224 });
225​
226 const getRows = (id: ScheduledTaskId) => sql<ScheduledTaskRow>`
227 SELECT
228 task_id,
229 title,
230 prompt,
231 enabled,
232 schedule_json,
233 project_id,
234 thread_id,
235 workspace_strategy_json,
236 model_selection_json,
237 runtime_mode,
238 interaction_mode,
239 created_by,
240 creation_source,
241 created_at,
242 updated_at,
243 next_run_at,
244 last_run_at,
245 last_run_status,
246 last_run_error,
247 run_count
248 FROM scheduled_tasks
249 WHERE task_id = ${id}
250 `;
251​
252 /** Load a task, returning `null` when it does not exist; real load/decode failures propagate. */
253 const findTask = Effect.fn("ScheduledTaskService.findTask")(function* (id: ScheduledTaskId) {
254 const rows = yield* getRows(id).pipe(
255 Effect.mapError((cause) =>
256 taskError("Could not load schedule task.", { taskId: id, cause }),
257 ),
258 );
259 const row = rows[0];
260 if (row === undefined) return null;
261 return yield* decodeRow(row);
262 });
263​
264 const loadTask = Effect.fn("ScheduledTaskService.loadTask")(function* (id: ScheduledTaskId) {
265 const task = yield* findTask(id);
266 if (task === null) {
267 return yield* taskError("Schedule task not found.", { taskId: id });
268 }
269 return task;
270 });
271​
272 // Run-state columns (last_run_*, run_count) are intentionally absent from
273 // the conflict clause: they are owned by the run transitions below, and a
274 // concurrent settings save must not overwrite an in-flight increment.
275 const saveTask = (task: ScheduledTask) =>
276 sql`
277 INSERT INTO scheduled_tasks (
278 task_id,
279 title,
280 prompt,
281 enabled,
282 schedule_json,
283 project_id,
284 thread_id,
285 workspace_strategy_json,
286 model_selection_json,
287 runtime_mode,
288 interaction_mode,
289 created_by,
290 creation_source,
291 created_at,
292 updated_at,
293 next_run_at,
294 last_run_at,
295 last_run_status,
296 last_run_error,
297 run_count
298 )
299 VALUES (
300 ${task.id},
301 ${task.title},
302 ${task.prompt},
303 ${task.enabled ? 1 : 0},
304 ${JSON.stringify(task.schedule)},
305 ${task.projectId},
306 ${task.threadId},
307 ${JSON.stringify(task.workspaceStrategy)},
308 ${JSON.stringify(task.modelSelection)},
309 ${task.runtimeMode},
310 ${task.interactionMode},
311 ${task.createdBy},
312 ${task.creationSource},
313 ${task.createdAt},
314 ${task.updatedAt},
315 ${task.nextRunAt},
316 ${task.lastRunAt},
317 ${task.lastRunStatus},
318 ${task.lastRunError},
319 ${task.runCount}
320 )
321 ON CONFLICT (task_id)
322 DO UPDATE SET
323 title = excluded.title,
324 prompt = excluded.prompt,
325 enabled = excluded.enabled,
326 schedule_json = excluded.schedule_json,
327 project_id = excluded.project_id,
328 thread_id = excluded.thread_id,
329 workspace_strategy_json = excluded.workspace_strategy_json,
330 model_selection_json = excluded.model_selection_json,
331 runtime_mode = excluded.runtime_mode,
332 interaction_mode = excluded.interaction_mode,
333 creation_source = excluded.creation_source,
334 updated_at = excluded.updated_at,
335 next_run_at = excluded.next_run_at
336 `.pipe(
337 Effect.mapError((cause) =>
338 taskError("Could not save schedule task.", { taskId: task.id, cause }),
339 ),
340 );
341​
342 const deleteRow = (id: ScheduledTaskId) =>
343 sql`DELETE FROM scheduled_tasks WHERE task_id = ${id}`.pipe(
344 Effect.mapError((cause) =>
345 taskError("Could not delete schedule task.", { taskId: id, cause }),
346 ),
347 );
348​
349 // Run-state transitions use targeted UPDATEs (never the full-row upsert) so
350 // a completing run cannot resurrect a deleted task or clobber concurrent
351 // edits to the task definition.
352 const markRunning = (id: ScheduledTaskId, startedAtIso: string) =>
353 sql`
354 UPDATE scheduled_tasks
355 SET updated_at = ${startedAtIso},
356 last_run_at = ${startedAtIso},
357 last_run_status = 'running',
358 last_run_error = NULL
359 WHERE task_id = ${id}
360 `.pipe(
361 Effect.mapError((cause) =>
362 taskError("Could not mark schedule task as running.", { taskId: id, cause }),
363 ),
364 );
365​
366 const markCompleted = (input: {
367 readonly id: ScheduledTaskId;
368 readonly completedAtIso: string;
369 readonly nextRunAtIso: string | null;
370 readonly status: "succeeded" | "failed";
371 readonly error: string | null;
372 readonly startedAtIso: string;
373 }) =>
374 sql`
375 UPDATE scheduled_tasks
376 SET updated_at = ${input.completedAtIso},
377 next_run_at = ${input.nextRunAtIso},
378 last_run_status = ${input.status},
379 last_run_error = ${input.error},
380 run_count = run_count + 1
381 WHERE task_id = ${input.id}
382 AND last_run_status = 'running'
383 AND last_run_at = ${input.startedAtIso}
384 `.pipe(
385 Effect.mapError((cause) =>
386 taskError("Could not record schedule task run.", { taskId: input.id, cause }),
387 ),
388 );
389​
390 // Best-effort escape hatch: if anything fails between markRunning and
391 // markCompleted, write a full terminal record so runDueTasks neither skips
392 // the task forever (it filters out 'running' rows) nor re-fires it
393 // immediately: the dispatch may already have gone out, so next_run_at must
394 // advance and run_count must count the attempt.
395 const releaseStuckRun = (task: ScheduledTask, message: string) =>
396 Effect.gen(function* () {
397 const now = yield* localNow;
398 // Compute the next occurrence from the current row so a schedule
399 // edited while the run was in flight is honoured; fall back to the
400 // run's snapshot only if the re-read itself fails.
401 const reread = yield* Effect.result(findTask(task.id));
402 if (Result.isSuccess(reread) && reread.success === null) return; // deleted — nothing to release
403 const source = Result.isSuccess(reread) && reread.success !== null ? reread.success : task;
404 yield* sql`
405 UPDATE scheduled_tasks
406 SET last_run_status = 'failed',
407 last_run_error = ${message},
408 next_run_at = ${nextRunAt(source, now)},
409 updated_at = ${iso(now)},
410 run_count = run_count + 1
411 WHERE task_id = ${task.id} AND last_run_status = 'running'
412 `;
413 yield* notifyChanged;
414 }).pipe(
415 Effect.catch((cause) =>
416 Effect.logWarning("Could not release stuck schedule task run", {
417 taskId: task.id,
418 cause,
419 }),
420 ),
421 );
422​
423 const runTask = Effect.fn("ScheduledTaskService.runTask")(function* (
424 task: ScheduledTask,
425 trigger: "scheduled" | "manual",
426 ) {
427 const reserved = yield* Ref.modify(activeRuns, (active) => {
428 if (active.has(task.id)) return [false, active] as const;
429 const next = new Set(active);
430 next.add(task.id);
431 return [true, next] as const;
432 });
433 if (!reserved) {
434 if (trigger === "manual") {
435 return yield* taskError("Schedule task is already running.", { taskId: task.id });
436 }
437 return task;
438 }
439​
440 return yield* Effect.gen(function* () {
441 const startedAt = yield* localNow;
442 const startedAtIso = iso(startedAt);
443​
444 // The in-memory snapshot may be stale: re-read before touching run
445 // state. The task may have been deleted, paused, or postponed since
446 // the poll loaded it — none of those may fire.
447 const active = yield* findTask(task.id);
448 if (active === null) {
449 // A manual run on a just-deleted task must fail loudly, not report
450 // a successful run that never dispatched.
451 if (trigger === "manual") {
452 return yield* taskError("Schedule task not found.", { taskId: task.id });
453 }
454 return task;
455 }
456 if (
457 trigger === "scheduled" &&
458 (!active.enabled ||
459 active.nextRunAt === null ||
460 DateTime.toEpochMillis(DateTime.makeUnsafe(active.nextRunAt)) >
461 DateTime.toEpochMillis(startedAt))
462 ) {
463 return active;
464 }
465​
466 yield* markRunning(active.id, startedAtIso);
467 yield* notifyChanged;
468​
469 const fireKey = `${active.id}:${DateTime.toEpochMillis(startedAt)}:${trigger}`;
470 const commandId = CommandId.make(`scheduled-task:${fireKey}`);
471 const messageId = MessageId.make(`scheduled-task-message:${fireKey}`);
472 // Dispatch from the fresh row so prompt/model/binding edits made
473 // after the poll read are honoured.
474 const prompt = automationPrompt(active);
475​
476 // Effect.exit (not Effect.result) so defects and interruptions in the
477 // dispatch are also captured and recorded as a failed run instead of
478 // aborting before markCompleted.
479 const result =
480 active.threadId === null
481 ? yield* Effect.exit(
482 threadLaunch.launch({
483 commandId,
484 projectId: active.projectId,
485 title: active.title,
486 modelSelection: active.modelSelection,
487 runtimeMode: active.runtimeMode,
488 interactionMode: active.interactionMode,
489 workspaceStrategy: active.workspaceStrategy,
490 initialMessage: {
491 messageId,
492 text: prompt,
493 attachments: [],
494 },
495 createdBy: active.createdBy,
496 creationSource: active.creationSource,
497 }),
498 )
499 : yield* Effect.exit(
500 threadManagement.sendToThread({
501 projectId: active.projectId,
502 commandId,
503 threadId: ThreadId.make(active.threadId),
504 messageId,
505 text: prompt,
506 attachments: [],
507 modelSelection: active.modelSelection,
508 mode: "auto",
509 createdBy: active.createdBy,
510 creationSource: active.creationSource,
511 }),
512 );
513​
514 const completedAt = yield* localNow;
515 const runSucceeded = result._tag === "Success";
516 const lastRunStatus = runSucceeded ? ("succeeded" as const) : ("failed" as const);
517 const lastRunError = runSucceeded ? null : errorMessage(result.cause);
518 // Re-read the task so the next run is computed from the schedule as it
519 // is *now* (the user may have edited or deleted it while we ran).
520 const current = yield* findTask(task.id);
521 const scheduleSource = current ?? task;
522 const completed: ScheduledTask = {
523 ...scheduleSource,
524 updatedAt: iso(completedAt),
525 lastRunAt: startedAtIso,
526 nextRunAt: nextRunAt(scheduleSource, completedAt),
527 lastRunStatus,
528 lastRunError,
529 runCount: scheduleSource.runCount + 1,
530 };
531 if (current !== null) {
532 // startedAtIso in the guard ensures this writes only to the row this
533 // run marked as running — a task deleted mid-run and recreated with
534 // the same id (idempotent commandId replay) must not be stamped.
535 yield* markCompleted({
536 id: task.id,
537 completedAtIso: completed.updatedAt,
538 nextRunAtIso: completed.nextRunAt,
539 status: lastRunStatus,
540 error: lastRunError,
541 startedAtIso,
542 });
543 yield* notifyChanged;
544 }
545 return completed;
546 }).pipe(
547 Effect.onError((cause) => releaseStuckRun(task, errorMessage(cause))),
548 Effect.ensuring(
549 Ref.update(activeRuns, (active) => {
550 const next = new Set(active);
551 next.delete(task.id);
552 return next;
553 }),
554 ),
555 );
556 });
557​
558 // A due fixed-time run that is long past its slot (server was off or
559 // asleep) is skipped and re-aimed at its next occurrence, not fired late.
560 const rescheduleMissedRun = Effect.fn("ScheduledTaskService.rescheduleMissedRun")(function* (
561 task: ScheduledTask,
562 now: DateTime.DateTime,
563 ) {
564 const next = nextRunAt(task, now);
565 yield* Effect.logInfo("Skipping missed schedule task run", {
566 taskId: task.id,
567 missedRunAt: task.nextRunAt,
568 rescheduledTo: next,
569 });
570 yield* sql`
571 UPDATE scheduled_tasks
572 SET next_run_at = ${next},
573 updated_at = ${iso(now)}
574 WHERE task_id = ${task.id}
575 `.pipe(
576 Effect.mapError((cause) =>
577 taskError("Could not reschedule missed schedule task run.", { taskId: task.id, cause }),
578 ),
579 );
580 yield* notifyChanged;
581 });
582​
583 const runDueTasks = Effect.fn("ScheduledTaskService.runDueTasks")(function* () {
584 const tasks = yield* listTasksLenient().pipe(
585 Effect.mapError((cause) => taskError("Could not list schedule tasks.", { cause })),
586 );
587 const now = yield* localNow;
588 const nowEpochMillis = DateTime.toEpochMillis(now);
589 const due = tasks.flatMap((task) => {
590 if (!task.enabled || task.nextRunAt === null || task.lastRunStatus === "running") {
591 return [];
592 }
593 const dueAt = DateTime.makeUnsafe(task.nextRunAt);
594 return DateTime.toEpochMillis(dueAt) <= nowEpochMillis ? [{ task, dueAt }] : [];
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);