feat: scheduled tasks (automations) #3638
Mergedjuliusmarmingemerged 13 commits into
t3code/codex-turn-mapping fromrefs/pull/3638/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/mcp/OrchestratorMcpService.ts line 871Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -698,0 +828,21 @@828+ const threadId =829+ input.bindToCurrentThread === undefined830+ ? existing.threadId831+ : input.bindToCurrentThread832+ ? scope.threadId833+ : null;834+ const upsertInput: ScheduledTaskUpsertInput = {835+ id: existing.id,836+ title: input.title ?? existing.title,837+ prompt: input.prompt ?? existing.prompt,838+ enabled: input.enabled ?? existing.enabled,839+ schedule: input.schedule ?? existing.schedule,840+ projectId: existing.projectId,841+ threadId,842+ workspaceStrategy: existing.workspaceStrategy,843+ modelSelection: existing.modelSelection,844+ runtimeMode: existing.runtimeMode,845+ interactionMode: existing.interactionMode,846+ createdBy: existing.createdBy,847+ creationSource: existing.creationSource,848+ };apps/server/src/scheduledTasks/ScheduledTaskService.ts line 544Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +428,21 @@428+ const current = yield* findTask(task.id);429+ const scheduleSource = current ?? task;430+ const completed: ScheduledTask = {431+ ...scheduleSource,432+ updatedAt: iso(completedAt),433+ lastRunAt: startedAtIso,434+ nextRunAt: nextRunAt(scheduleSource, completedAt),435+ lastRunStatus,436+ lastRunError,437+ runCount: scheduleSource.runCount + 1,438+ };439+ if (current !== null) {440+ yield* markCompleted({441+ id: task.id,442+ completedAtIso: completed.updatedAt,443+ nextRunAtIso: completed.nextRunAt,444+ status: lastRunStatus,445+ error: lastRunError,446+ });447+ yield* notifyChanged;448+ }apps/server/src/scheduledTasks/ScheduledTaskService.ts line 744Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +571,21 @@571+ enabled: input.enabled,572+ schedule: input.schedule,573+ projectId: input.projectId,574+ threadId: input.threadId ?? null,575+ workspaceStrategy: input.workspaceStrategy,576+ modelSelection: input.modelSelection,577+ runtimeMode: input.runtimeMode,578+ interactionMode: input.interactionMode,579+ createdBy: existingTask?.createdBy ?? input.createdBy ?? "user",580+ creationSource: input.creationSource ?? "web",581+ createdAt: existingTask?.createdAt ?? iso(now),582+ updatedAt: iso(now),583+ nextRunAt: nextRunAt({ enabled: input.enabled, schedule: input.schedule }, now),584+ lastRunAt: existingTask?.lastRunAt ?? null,585+ lastRunStatus: existingTask?.lastRunStatus ?? "never",586+ lastRunError: existingTask?.lastRunError ?? null,587+ runCount: existingTask?.runCount ?? 0,588+ };589+ yield* saveTask(task);590+ yield* notifyChanged;591+ return { task };apps/web/src/components/settings/ScheduledTasksSettings.tsx line 169Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +142,21 @@142+143+function splitModelKey(value: string): ModelSelection | null {144+ const index = value.indexOf(":");145+ if (index <= 0 || index === value.length - 1) return null;146+ return {147+ instanceId: ProviderInstanceId.make(value.slice(0, index)),148+ model: value.slice(index + 1),149+ };150+}151+152+function scheduleFromDraft(draft: DraftState): ScheduledTaskSchedule {153+ if (draft.scheduleMode === "interval") {154+ const minutes = Math.max(1, Number.parseInt(draft.intervalMinutes, 10) || 1);155+ return { type: "interval", everyMs: minutes * 60_000 };156+ }157+ const selectedEveryDay = draft.weekdays.size === 0 || draft.weekdays.size === 7;158+ return {159+ type: "fixed_time",160+ timeOfDay: draft.timeOfDay || "09:00",161+ ...(selectedEveryDay ? {} : { weekdays: [...draft.weekdays].toSorted() }),162+ };apps/server/src/scheduledTasks/ScheduledTaskService.ts line 555Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +438,21 @@438+ };439+ if (current !== null) {440+ yield* markCompleted({441+ id: task.id,442+ completedAtIso: completed.updatedAt,443+ nextRunAtIso: completed.nextRunAt,444+ status: lastRunStatus,445+ error: lastRunError,446+ });447+ yield* notifyChanged;448+ }449+ return completed;450+ }).pipe(451+ Effect.ensuring(452+ Ref.update(activeRuns, (active) => {453+ const next = new Set(active);454+ next.delete(task.id);455+ return next;456+ }),457+ ),458+ );
- apps/web/src/components/settings/ScheduledTasksSettings.tsx line 60Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +40,21 @@40+ Dialog,41+ DialogClose,42+ DialogDescription,43+ DialogFooter,44+ DialogHeader,45+ DialogPanel,46+ DialogPopup,47+ DialogTitle,48+} from "../ui/dialog";49+import { Input } from "../ui/input";50+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";51+import { Switch } from "../ui/switch";52+import { Textarea } from "../ui/textarea";53+import { stackedThreadToast, toastManager } from "../ui/toast";54+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";55+import { SettingsPageContainer, SettingsSection, useRelativeTimeTick } from "./settingsLayout";56+57+type ScheduleMode = "fixed" | "interval";58+type WorkspaceMode = "root" | "worktree" | "existing_worktree";59+60+interface DraftState {packages/client-runtime/src/state/server.ts line 219Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -190,3 +195,16 @@190195 label: "environment-data:server:signal-process",191196 tag: WS_METHODS.serverSignalProcess,192197 }),198+ upsertScheduledTask: createEnvironmentRpcCommand(runtime, {199+ label: "environment-data:server:scheduled-task:upsert",200+ tag: WS_METHODS.scheduledTasksUpsert,201+ scheduler: configScheduler,202+ concurrency: configConcurrency,203+ }),204+ deleteScheduledTask: createEnvironmentRpcCommand(runtime, {205+ label: "environment-data:server:scheduled-task:delete",206+ tag: WS_METHODS.scheduledTasksDelete,207+ scheduler: configScheduler,208+ concurrency: configConcurrency,209+ }),210+ runScheduledTaskNow: createEnvironmentRpcCommand(runtime, {apps/server/src/scheduledTasks/ScheduledTaskService.ts line 541OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +521,21 @@521+ `.pipe(522+ Effect.andThen(notifyChanged),523+ Effect.catch((cause) =>524+ Effect.logWarning("Could not reset interrupted schedule task runs", { cause }),525+ ),526+ );527+528+ yield* runDueTasks().pipe(529+ Effect.catch((cause) => Effect.logWarning("Scheduled task polling failed", { cause })),530+ Effect.delay(Duration.seconds(5)),531+ Effect.forever,532+ Effect.forkScoped,533+ );534+535+ const list: ScheduledTaskServiceShape["list"] = () =>536+ listRows().pipe(537+ Effect.map((tasks) => ({ tasks })),538+ Effect.mapError((cause) => taskError("Could not list schedule tasks.", { cause })),539+ );540+541+ const subscribeList: ScheduledTaskServiceShape["subscribeList"] = () =>apps/server/src/mcp/OrchestratorMcpService.ts line 799Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -698,0 +769,21 @@769+ const title =770+ input.title ?? (derivedTitle.length > 0 ? derivedTitle.slice(0, 80) : "Scheduled task");771+ const upsertInput: ScheduledTaskUpsertInput = {772+ title,773+ prompt: input.prompt,774+ enabled: input.enabled ?? true,775+ schedule: input.schedule,776+ projectId: parent.thread.projectId,777+ threadId: bindToCurrentThread ? scope.threadId : null,778+ // When bound to the calling thread the workspace strategy is unused779+ // (the run is sent into the existing thread); otherwise each run780+ // launches a fresh worktree off main.781+ workspaceStrategy: bindToCurrentThread782+ ? { type: "root" }783+ : { type: "worktree", baseRef: "main", startFromOrigin: true },784+ modelSelection: parent.thread.modelSelection,785+ runtimeMode: parent.thread.runtimeMode,786+ interactionMode: parent.thread.interactionMode,787+ createdBy: "agent",788+ creationSource: "mcp",789+ ...(input.clientRequestId === undefinedapps/server/src/mcp/OrchestratorMcpService.ts line 842OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -698,0 +822,21 @@822+ yield* requireCapability(scope);823+ const parent = yield* loadProjection(scope.threadId);824+ const existing = yield* loadScopedScheduledTask(825+ parent.thread.projectId,826+ input.scheduledTaskId,827+ );828+ const threadId =829+ input.bindToCurrentThread === undefined830+ ? existing.threadId831+ : input.bindToCurrentThread832+ ? scope.threadId833+ : null;834+ const upsertInput: ScheduledTaskUpsertInput = {835+ id: existing.id,836+ title: input.title ?? existing.title,837+ prompt: input.prompt ?? existing.prompt,838+ enabled: input.enabled ?? existing.enabled,839+ schedule: input.schedule ?? existing.schedule,840+ projectId: existing.projectId,841+ threadId,842+ workspaceStrategy: existing.workspaceStrategy,apps/server/src/scheduledTasks/ScheduledTaskService.ts line 479Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +367,21 @@367+ return [true, next] as const;368+ });369+ if (!reserved) {370+ if (trigger === "manual") {371+ return yield* taskError("Schedule task is already running.", { taskId: task.id });372+ }373+ return task;374+ }375+376+ return yield* Effect.gen(function* () {377+ const startedAt = yield* localNow;378+ const startedAtIso = iso(startedAt);379+ yield* markRunning(task.id, startedAtIso);380+ yield* notifyChanged;381+382+ const fireKey = `${task.id}:${DateTime.toEpochMillis(startedAt)}:${trigger}`;383+ const commandId = CommandId.make(`scheduled-task:${fireKey}`);384+ const messageId = MessageId.make(`scheduled-task-message:${fireKey}`);385+ const prompt = automationPrompt(task);386+387+ const result =apps/web/src/components/settings/ScheduledTasksSettings.tsx line 194Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +162,21 @@162+ };163+}164+165+export function scheduleLabel(schedule: ScheduledTaskSchedule): string {166+ if (schedule.type === "interval") {167+ const minutes = schedule.everyMs / 60_000;168+ return Number.isInteger(minutes)169+ ? `Every ${minutes} min`170+ : `Every ${Math.round(schedule.everyMs / 1000)} sec`;171+ }172+ const weekdays = schedule.weekdays ?? [];173+ const days =174+ weekdays.length === 0175+ ? "Daily"176+ : weekdays.length === 5 && weekdays.every((day) => day >= 1 && day <= 5)177+ ? "Weekdays"178+ : weekdays.map((day) => WEEKDAY_LABELS[day]).join(", ");179+ return `${days} at ${schedule.timeOfDay}`;180+}181+182+export function relativeLabel(value: string | null): string {
- apps/server/src/scheduledTasks/ScheduledTaskService.ts line 475OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +455,21 @@455+ ...scheduleSource,456+ updatedAt: iso(completedAt),457+ lastRunAt: startedAtIso,458+ nextRunAt: nextRunAt(scheduleSource, completedAt),459+ lastRunStatus,460+ lastRunError,461+ runCount: scheduleSource.runCount + 1,462+ };463+ if (current !== null) {464+ yield* markCompleted({465+ id: task.id,466+ completedAtIso: completed.updatedAt,467+ nextRunAtIso: completed.nextRunAt,468+ status: lastRunStatus,469+ error: lastRunError,470+ });471+ yield* notifyChanged;472+ }473+ return completed;474+ }).pipe(475+ Effect.onError((cause) => releaseStuckRun(task.id, errorMessage(cause))),
- apps/server/src/scheduledTasks/ScheduledTaskService.ts lines 67 to 85OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +65,21 @@65+}66+67+export interface ScheduledTaskServiceShape {68+ readonly list: () => Effect.Effect<ScheduledTaskListResult, ScheduledTaskError>;69+ /** Emits the full task list on subscribe and again after every change (CRUD, run transitions, reschedules). */70+ readonly subscribeList: () => Stream.Stream<ScheduledTaskListResult, ScheduledTaskError>;71+ readonly upsert: (72+ input: ScheduledTaskUpsertInput,73+ ) => Effect.Effect<ScheduledTaskMutationResult, ScheduledTaskError>;74+ readonly delete: (75+ input: ScheduledTaskDeleteInput,76+ ) => Effect.Effect<ScheduledTaskDeleteResult, ScheduledTaskError>;77+ readonly runNow: (78+ input: ScheduledTaskRunNowInput,79+ ) => Effect.Effect<ScheduledTaskRunNowResult, ScheduledTaskError>;80+}81+82+export class ScheduledTaskService extends Context.Service<83+ ScheduledTaskService,84+ ScheduledTaskServiceShape85+>()("t3/scheduledTasks/ScheduledTaskService") {}
- apps/server/src/scheduledTasks/ScheduledTaskService.ts line 412Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +354,21 @@354+ taskError("Could not record schedule task run.", { taskId: input.id, cause }),355+ ),356+ );357+358+ // Best-effort escape hatch: if anything fails between markRunning and359+ // markCompleted, write a full terminal record so runDueTasks neither skips360+ // the task forever (it filters out 'running' rows) nor re-fires it361+ // immediately: the dispatch may already have gone out, so next_run_at must362+ // advance and run_count must count the attempt.363+ const releaseStuckRun = (task: ScheduledTask, message: string) =>364+ Effect.gen(function* () {365+ const now = yield* localNow;366+ yield* sql`367+ UPDATE scheduled_tasks368+ SET last_run_status = 'failed',369+ last_run_error = ${message},370+ next_run_at = ${nextRunAt(task, now)},371+ updated_at = ${iso(now)},372+ run_count = run_count + 1373+ WHERE task_id = ${task.id} AND last_run_status = 'running'374+ `;
- apps/server/src/scheduledTasks/ScheduledTaskService.ts lines 411 to 412OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +392,21 @@392+ next.add(task.id);393+ return [true, next] as const;394+ });395+ if (!reserved) {396+ if (trigger === "manual") {397+ return yield* taskError("Schedule task is already running.", { taskId: task.id });398+ }399+ return task;400+ }401+402+ return yield* Effect.gen(function* () {403+ const startedAt = yield* localNow;404+ const startedAtIso = iso(startedAt);405+ yield* markRunning(task.id, startedAtIso);406+ yield* notifyChanged;407+408+ // The in-memory snapshot may be stale: if the task was deleted since409+ // it was loaded, markRunning updated nothing — do not dispatch a run410+ // for a task that no longer exists.411+ const preflight = yield* findTask(task.id);412+ if (preflight === null) return task;apps/server/src/scheduledTasks/ScheduledTaskService.ts line 395Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +343,21 @@343+ }) =>344+ sql`345+ UPDATE scheduled_tasks346+ SET updated_at = ${input.completedAtIso},347+ next_run_at = ${input.nextRunAtIso},348+ last_run_status = ${input.status},349+ last_run_error = ${input.error},350+ run_count = run_count + 1351+ WHERE task_id = ${input.id}352+ `.pipe(353+ Effect.mapError((cause) =>354+ taskError("Could not record schedule task run.", { taskId: input.id, cause }),355+ ),356+ );357+358+ // Best-effort escape hatch: if anything fails between markRunning and359+ // markCompleted, write a full terminal record so runDueTasks neither skips360+ // the task forever (it filters out 'running' rows) nor re-fires it361+ // immediately: the dispatch may already have gone out, so next_run_at must362+ // advance and run_count must count the attempt.363+ const releaseStuckRun = (task: ScheduledTask, message: string) =>
- apps/server/src/scheduledTasks/ScheduledTaskService.ts line 550OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +530,21 @@530+ const dueAt = DateTime.makeUnsafe(task.nextRunAt);531+ return DateTime.toEpochMillis(dueAt) <= nowEpochMillis ? [{ task, dueAt }] : [];532+ });533+ yield* Effect.forEach(534+ due,535+ ({ task, dueAt }) =>536+ (isMissedFixedTimeRun(task.schedule, dueAt, now)537+ ? rescheduleMissedRun(task, now)538+ : runTask(task, "scheduled")539+ ).pipe(540+ Effect.catch((cause) =>541+ Effect.logWarning("Scheduled task run failed", { taskId: task.id, cause }),542+ ),543+ ),544+ { concurrency: 1, discard: true },545+ );546+ });547+548+ // Recover from a crash or hard shutdown mid-run: rows stuck in 'running'549+ // would otherwise be skipped by the due-task filter forever.550+ yield* sql`
- apps/server/src/scheduledTasks/ScheduledTaskService.ts line 659Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +554,21 @@554+ // rather than a single UPDATE.555+ yield* Effect.gen(function* () {556+ const tasks = yield* listRows();557+ const stuck = tasks.filter((task) => task.lastRunStatus === "running");558+ if (stuck.length === 0) return;559+ const now = yield* localNow;560+ yield* Effect.forEach(561+ stuck,562+ (task) => sql`563+ UPDATE scheduled_tasks564+ SET last_run_status = 'failed',565+ last_run_error = 'Run was interrupted by a server restart.',566+ next_run_at = ${nextRunAt(task, now)},567+ updated_at = ${iso(now)},568+ run_count = run_count + 1569+ WHERE task_id = ${task.id} AND last_run_status = 'running'570+ `,571+ { concurrency: 1, discard: true },572+ );573+ yield* notifyChanged;574+ }).pipe(
- apps/server/src/scheduledTasks/ScheduledTaskService.ts line 163OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +143,21 @@143+ lastRunError: row.last_run_error,144+ runCount: row.run_count,145+ });146+ }).pipe(147+ Effect.mapError((cause) =>148+ taskError("Could not decode schedule task row.", {149+ taskId: ScheduledTaskId.make(row.task_id),150+ cause,151+ }),152+ ),153+ );154+155+export const layer = Layer.effect(156+ ScheduledTaskService,157+ Effect.gen(function* () {158+ const sql = yield* SqlClient.SqlClient;159+ const crypto = yield* Crypto.Crypto;160+ const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService;161+ const threadManagement = yield* ThreadManagementService.ThreadManagementService;162+ const activeRuns = yield* Ref.make<ReadonlySet<ScheduledTaskId>>(new Set());163+ const changesPubSub = yield* PubSub.unbounded<void>();
- apps/server/src/scheduledTasks/ScheduledTaskService.ts line 429OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +409,21 @@409+ ) {410+ const reserved = yield* Ref.modify(activeRuns, (active) => {411+ if (active.has(task.id)) return [false, active] as const;412+ const next = new Set(active);413+ next.add(task.id);414+ return [true, next] as const;415+ });416+ if (!reserved) {417+ if (trigger === "manual") {418+ return yield* taskError("Schedule task is already running.", { taskId: task.id });419+ }420+ return task;421+ }422+423+ return yield* Effect.gen(function* () {424+ const startedAt = yield* localNow;425+ const startedAtIso = iso(startedAt);426+ yield* markRunning(task.id, startedAtIso);427+ yield* notifyChanged;428+429+ // The in-memory snapshot may be stale: if the task was deleted since
- apps/server/src/scheduledTasks/ScheduledTaskService.ts lines 535 to 542Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +494,21 @@494+ // Re-read the task so the next run is computed from the schedule as it495+ // is *now* (the user may have edited or deleted it while we ran).496+ const current = yield* findTask(task.id);497+ const scheduleSource = current ?? task;498+ const completed: ScheduledTask = {499+ ...scheduleSource,500+ updatedAt: iso(completedAt),501+ lastRunAt: startedAtIso,502+ nextRunAt: nextRunAt(scheduleSource, completedAt),503+ lastRunStatus,504+ lastRunError,505+ runCount: scheduleSource.runCount + 1,506+ };507+ if (current !== null) {508+ yield* markCompleted({509+ id: task.id,510+ completedAtIso: completed.updatedAt,511+ nextRunAtIso: completed.nextRunAt,512+ status: lastRunStatus,513+ error: lastRunError,514+ });
- apps/server/src/scheduledTasks/ScheduledTaskService.ts line 463Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +419,21 @@419+ }420+ return task;421+ }422+423+ return yield* Effect.gen(function* () {424+ const startedAt = yield* localNow;425+ const startedAtIso = iso(startedAt);426+427+ // The in-memory snapshot may be stale: re-read before touching run428+ // state. The task may have been deleted, paused, or postponed since429+ // the poll loaded it — none of those may fire.430+ const active = yield* findTask(task.id);431+ if (active === null) return task;432+ if (433+ trigger === "scheduled" &&434+ (!active.enabled ||435+ active.nextRunAt === null ||436+ DateTime.toEpochMillis(DateTime.makeUnsafe(active.nextRunAt)) >437+ DateTime.toEpochMillis(startedAt))438+ ) {439+ return active;
- apps/server/src/scheduledTasks/Schedule.ts line 58Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +27,21 @@27+ minute: time.minute,28+ second: 0,29+ millisecond: 0,30+ });31+ if (DateTime.toEpochMillis(candidate) <= DateTime.toEpochMillis(from)) continue;32+ if (weekdays !== null && !weekdays.has(DateTime.toParts(candidate).weekDay)) continue;33+ return candidate;34+ }35+ return null;36+}37+38+/** Structural equality for schedules, independent of JSON key order. */39+export function isSameSchedule(a: ScheduledTaskSchedule, b: ScheduledTaskSchedule): boolean {40+ if (a.type === "interval") {41+ return b.type === "interval" && a.everyMs === b.everyMs;42+ }43+ return (44+ b.type === "fixed_time" &&45+ a.timeOfDay === b.timeOfDay &&46+ (a.weekdays ?? []).join(",") === (b.weekdays ?? []).join(",")47+ );
- apps/server/src/scheduledTasks/Schedule.ts lines 54 to 58Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +27,21 @@27+ minute: time.minute,28+ second: 0,29+ millisecond: 0,30+ });31+ if (DateTime.toEpochMillis(candidate) <= DateTime.toEpochMillis(from)) continue;32+ if (weekdays !== null && !weekdays.has(DateTime.toParts(candidate).weekDay)) continue;33+ return candidate;34+ }35+ return null;36+}37+38+/** Structural equality for schedules, independent of JSON key order. */39+export function isSameSchedule(a: ScheduledTaskSchedule, b: ScheduledTaskSchedule): boolean {40+ if (a.type === "interval") {41+ return b.type === "interval" && a.everyMs === b.everyMs;42+ }43+ return (44+ b.type === "fixed_time" &&45+ a.timeOfDay === b.timeOfDay &&46+ (a.weekdays ?? []).join(",") === (b.weekdays ?? []).join(",")47+ );
- apps/web/src/components/chat/ThreadAutomationsPanel.tsx line 36OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +16,21 @@16+import { relativeLabel, scheduleLabel } from "../settings/ScheduledTasksSettings";17+import { useEnvironmentQuery } from "../../state/query";18+import { serverEnvironment } from "../../state/server";19+import { useAtomCommand } from "../../state/use-atom-command";20+import { Button } from "../ui/button";21+import { Switch } from "../ui/switch";22+import { stackedThreadToast, toastManager } from "../ui/toast";23+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";24+import {25+ THREAD_DETAILS_PANEL_ICON_ACTION_CLASS,26+ THREAD_DETAILS_PANEL_ICON_CLASS,27+} from "./threadDetailsPanelStyles";28+29+const STATUS_DOT_CLASS: Record<ScheduledTask["lastRunStatus"], string> = {30+ never: "bg-muted-foreground/40",31+ running: "animate-pulse bg-sky-500",32+ succeeded: "bg-emerald-500",33+ failed: "bg-destructive",34+};35+36+function upsertInputFromTask(task: ScheduledTask, enabled: boolean): ScheduledTaskUpsertInput {apps/web/src/components/chat/ThreadAutomationsPanel.tsx line 79OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +59,21 @@59+ */60+export function ThreadAutomationsPanel(props: {61+ readonly environmentId: EnvironmentId;62+ readonly threadId: ThreadId;63+}) {64+ const tasksQuery = useEnvironmentQuery(65+ serverEnvironment.scheduledTasksLive({ environmentId: props.environmentId, input: {} }),66+ );67+ const upsertTask = useAtomCommand(serverEnvironment.upsertScheduledTask, {68+ label: "thread automation toggle",69+ });70+ const runTaskNow = useAtomCommand(serverEnvironment.runScheduledTaskNow, {71+ label: "thread automation run now",72+ });73+ const navigate = useNavigate();74+ const [busyTaskId, setBusyTaskId] = useState<string | null>(null);75+76+ const boundTasks = (tasksQuery.data?.tasks ?? []).filter(77+ (task) => task.threadId === props.threadId,78+ );79+ if (boundTasks.length === 0) return null;
- apps/server/src/scheduledTasks/ScheduledTaskService.ts line 753OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +733,21 @@733+ updatedAt: iso(now),734+ nextRunAt: scheduleUnchanged735+ ? existingTask.nextRunAt736+ : 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+ yield* sql`
juliusmarminge merged thisdac514e
juliusmarminge closed this
Sign in to join this conversation.



Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID:
992a8f6e-4e8a-4d96-a549-a93a2c807b38You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands.