Skip to content
Source
Sign inSign up
pingdotgg/t3code

feat: scheduled tasks (automations) #3638

Mergedjuliusmarmingemerged 13 commits intot3code/codex-turn-mapping fromrefs/pull/3638/headmerged by juliusmarminge View on GitHub

juliusmarmingecommented

Adds scheduled tasks — auto-executed prompts on a schedule, creatable by humans (settings UI) and by agents (orchestrator MCP tools). Targets the orchestrator PR (#2829) since runs dispatch through the V2 thread services.

What's included

Core

  • scheduled_tasks table (migration 040) + ScheduledTaskService with a 5s poll loop
  • A task binds to a project, runs in a new worktree / project checkout / specific checkout, with full model selection (provider instance, model, runtime + interaction modes)
  • Optional thread binding: runs post into the bound thread as a normal message with a [Triggered by schedule task: …] marker; unbound tasks launch a fresh thread per run
  • Schedules: interval (everyMs) or fixed time (HH:MM + weekday mask, contract-validated)

Semantics

  • Missed fixed-time runs (server off/asleep past a 10-min grace window) are skipped and re-aimed at the next occurrence; overdue interval runs catch up once
  • Crash-safe run state: run transitions are targeted UPDATEs (a completing run can't resurrect a deleted task or clobber concurrent edits); stale running rows reset to failed on startup
  • Idempotent creates via commandId preserve run history; runNow on an already-running task errors instead of silently succeeding

Agent surface (orchestrator MCP)

  • schedule_task, list_scheduled_tasks, update_scheduled_task, delete_scheduled_task — project-scoped; bindToCurrentThread defaults to true so an agent can "wake up every 5 minutes and check CI" in its own thread
  • capabilities now advertises scheduledTasks: true

Transport + UI

  • RPCs: scheduledTasks.list/upsert/delete/runNow + a scheduledTasks.subscribe change-stream (snapshot, then a fresh list after every change — CRUD, run transitions, reschedules)
  • Web: /settings/scheduled-tasks management page (schedule presets, weekday picker, model picker, run-now/pause) and an Automations section in the thread details panel showing tasks bound to the thread with live status, run-now, and pause controls — both fed by the subscription, no polling

Verification

  • Unit tests for schedule math (next-run calculation, weekday skip, missed-run grace) and an MCP toolkit integration test exercising all four tools
  • Typecheck + lint clean across contracts, client-runtime, server, web; CodeRabbit review pass with no findings

Known limitations (deliberate, follow-ups)

  • MCP schedule_task hardcodes baseRef: "main" for unbound tasks (needs a default-branch lookup)
  • Thread-bound fires use mode: "auto", which steers an active turn; "queue" may be the safer default
  • Run claiming is in-process only (fine for the local server; needs a DB lease if multi-instance)

🤖 Generated with Claude Code


Note

Medium Risk Runs dispatch real orchestration (thread launch/send) on a timer with in-process run claiming only; multi-instance or restart edge cases could duplicate or surprise-steer active turns when bound to a thread.

Overview Adds scheduled tasks (automations): prompts that run on an interval or fixed wall-clock schedule, persisted in a new scheduled_tasks table (migration 040) and driven by a 5s poll loop in ScheduledTaskService.

Each run either posts into a bound thread (with a schedule marker) or launches a new thread via V2 sendToThread / threadLaunch, honoring workspace strategy and inherited model/runtime settings. Fixed-time slots missed by more than a grace window are skipped and rescheduled; crash recovery clears stuck running rows and advances next_run_at so restarts do not double-fire.

Agents get orchestrator MCP tools (schedule_task, list_scheduled_tasks, update_scheduled_task, delete_scheduled_task) scoped to the caller’s project, with optional bindToCurrentThread and idempotent clientRequestId; capabilities advertise scheduledTasks: true.

Clients get WebSocket RPCs (list, subscribe, upsert, setEnabled, delete, runNow) plus live subscription atoms; the web app adds /settings/scheduled-tasks and a thread Automations panel for bound tasks.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit c19ceca8a539d77e1fa991a10bc06ca845df5fdc. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).

Note

Add scheduled tasks (automations) with UI, MCP tools, and polling execution

  • Introduces a ScheduledTask entity supporting two schedule types: interval (every N ms) and fixed_time (HH:MM with optional weekday mask), with full CRUD via WebSocket RPCs defined in scheduledTask.ts.
  • Adds ScheduledTaskService with a 5-second polling fiber, crash recovery for tasks stuck in running on restart, concurrency guards, and a 10-minute grace window for missed fixed-time runs.
  • Creates database migration 040 adding the scheduled_tasks table and indexes for due-task polling and project scoping.
  • Exposes schedule_task, list_scheduled_tasks, update_scheduled_task, and delete_scheduled_task tools in the orchestrator MCP toolkit, allowing agents to manage automations scoped to their current project.
  • Adds a ScheduledTasksSettings page at /settings/scheduled-tasks and a ThreadAutomationsPanel in thread details showing live-subscribed automations bound to the thread.
  • Risk: the polling fiber runs every 5 seconds per server process; tasks are guarded by an in-memory Ref<Set> so concurrent duplicate runs are prevented only within a single process instance.
Macroscope summarized c19ceca.
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro

      Run ID: 992a8f6e-4e8a-4d96-a549-a93a2c807b38

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests
      • Commit unit tests in branch `t3code/scheduled-tasks`

      Comment `@coderabbitai help` to get the list of available commands.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted

    3. Cursor Bugbot has reviewed your changes using high effort and found 5 potential issues.

      Autofix Details

      Bugbot Autofix prepared fixes for all 5 issues found in the latest run.

      • ✅ Fixed: Update leaves wrong workspace strategy
        • Added workspace strategy recomputation in updateScheduledTask that mirrors the create logic when bindToCurrentThread changes.
      • ✅ Fixed: Deleted task still launches run
        • Added a findTask pre-check after markRunning that aborts the run early if the task row no longer exists.
      • ✅ Fixed: Upsert can revert run count
        • Removed last_run_at, last_run_status, last_run_error, and run_count from the ON CONFLICT UPDATE clause in saveTask so concurrent markCompleted increments are preserved.
      • ✅ Fixed: Zero weekdays become daily schedule
        • Prevented deselecting the last weekday in the UI toggle handler so users cannot reach zero selected days in fixed-time mode.
      • ✅ Fixed: Run failure leaves running status
        • Added an Effect.tapCause handler after the inner gen that marks the task as failed in the database when any uncaught error occurs after markRunning.

      Create PR

      Or push these changes by commenting:

      @cursor push f988fcda45
      Preview (pingdotgg/t3code@f988fcda45)
      diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts
      --- a/apps/server/src/mcp/OrchestratorMcpService.ts
      +++ b/apps/server/src/mcp/OrchestratorMcpService.ts
      @@ -831,6 +831,12 @@
                   : input.bindToCurrentThread
                     ? scope.threadId
                     : null;
      +        const workspaceStrategy =
      +          input.bindToCurrentThread === undefined
      +            ? existing.workspaceStrategy
      +            : input.bindToCurrentThread
      +              ? { type: "root" as const }
      +              : { type: "worktree" as const, baseRef: "main", startFromOrigin: true };
               const upsertInput: ScheduledTaskUpsertInput = {
                 id: existing.id,
                 title: input.title ?? existing.title,
      @@ -839,7 +845,7 @@
                 schedule: input.schedule ?? existing.schedule,
                 projectId: existing.projectId,
                 threadId,
      -          workspaceStrategy: existing.workspaceStrategy,
      +          workspaceStrategy,
                 modelSelection: existing.modelSelection,
                 runtimeMode: existing.runtimeMode,
                 interactionMode: existing.interactionMode,
      
      diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts
      --- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts
      +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts
      @@ -300,11 +300,7 @@
                 interaction_mode = excluded.interaction_mode,
                 creation_source = excluded.creation_source,
                 updated_at = excluded.updated_at,
      -          next_run_at = excluded.next_run_at,
      -          last_run_at = excluded.last_run_at,
      -          last_run_status = excluded.last_run_status,
      -          last_run_error = excluded.last_run_error,
      -          run_count = excluded.run_count
      +          next_run_at = excluded.next_run_at
             `.pipe(
               Effect.mapError((cause) =>
                 taskError("Could not save schedule task.", { taskId: task.id, cause }),
      @@ -379,6 +375,10 @@
               yield* markRunning(task.id, startedAtIso);
               yield* notifyChanged;
       
      +        // Abort if the task was deleted before we could dispatch.
      +        const preCheck = yield* findTask(task.id);
      +        if (preCheck === null) return task;
      +
               const fireKey = `${task.id}:${DateTime.toEpochMillis(startedAt)}:${trigger}`;
               const commandId = CommandId.make(`scheduled-task:${fireKey}`);
               const messageId = MessageId.make(`scheduled-task-message:${fireKey}`);
      @@ -448,6 +448,19 @@
               }
               return completed;
             }).pipe(
      +        Effect.tapCause((cause) => {
      +          const now = DateTime.nowUnsafe();
      +          return markCompleted({
      +            id: task.id,
      +            completedAtIso: iso(now),
      +            nextRunAtIso: nextRunAt(task, now),
      +            status: "failed",
      +            error: Cause.pretty(cause),
      +          }).pipe(
      +            Effect.andThen(notifyChanged),
      +            Effect.catch(() => Effect.void),
      +          );
      +        }),
               Effect.ensuring(
                 Ref.update(activeRuns, (active) => {
                   const next = new Set(active);
      
      diff --git a/apps/web/src/components/settings/ScheduledTasksSettings.tsx b/apps/web/src/components/settings/ScheduledTasksSettings.tsx
      --- a/apps/web/src/components/settings/ScheduledTasksSettings.tsx
      +++ b/apps/web/src/components/settings/ScheduledTasksSettings.tsx
      @@ -154,11 +154,11 @@
           const minutes = Math.max(1, Number.parseInt(draft.intervalMinutes, 10) || 1);
           return { type: "interval", everyMs: minutes * 60_000 };
         }
      -  const selectedEveryDay = draft.weekdays.size === 0 || draft.weekdays.size === 7;
      +  const selectedEveryDay = draft.weekdays.size === 7;
         return {
           type: "fixed_time",
           timeOfDay: draft.timeOfDay || "09:00",
      -    ...(selectedEveryDay ? {} : { weekdays: [...draft.weekdays].toSorted() }),
      +    ...(selectedEveryDay || draft.weekdays.size === 0 ? {} : { weekdays: [...draft.weekdays].toSorted() }),
         };
       }
       
      @@ -644,8 +644,10 @@
                                 onClick={() =>
                                   setDraft((current) => {
                                     const weekdays = new Set(current.weekdays);
      -                              if (weekdays.has(day)) weekdays.delete(day);
      -                              else weekdays.add(day);
      +                              if (weekdays.has(day)) {
      +                                if (weekdays.size <= 1) return current;
      +                                weekdays.delete(day);
      +                              } else weekdays.add(day);
                                     return { ...current, weekdays };
                                   })
                                 }
      You can send follow-ups to the cloud agent here.
    4. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Needs human review

      This PR introduces a complete new feature (scheduled tasks/automations) with ~2000+ lines of new code including a new database table, scheduling service with polling/recovery logic, new MCP tools for agent task creation, 6 new API endpoints, and new UI components. New features of this scope warrant human review.

      You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    5. All review findings addressed in 272b949:

      Cursor Bugbot

      • ✅ Update leaves wrong workspace strategy — update_scheduled_task now recomputes the strategy whenever bindToCurrentThread is provided (shared scheduledTaskWorkspaceStrategy helper with schedule_task)
      • ✅ Deleted task still launches run — post-markRunning existence check; a deleted row is never dispatched
      • ✅ Upsert can revert run count — last_run_*/run_count removed from the ON CONFLICT clause; run state is owned exclusively by the targeted run-transition UPDATEs
      • ✅ Zero weekdays become daily — the last selected weekday chip can no longer be deselected
      • ✅ Run failure leaves running status — Effect.onError fallback flips a stuck running row to failed (guarded AND last_run_status = 'running'), with the startup reset as final backstop

      Macroscope

      • ✅ Effect.result misses defects/interruptions — dispatch now wrapped in Effect.exit, so defects are recorded as failed runs and markCompleted still executes
      • ✅ Unscoped clientRequestId — schedule_task now derives its idempotency key via stableCommandId (scoped by provider session + operation), matching delegate_task/create_threads
      • ✅ subscribeList snapshot gap — subscribes to the PubSub before taking the snapshot (Stream.unwrap + Stream.fromSubscription), so changes landing in between are buffered, not dropped
      • ✅ runScheduledTaskNow on the config lane — moved off the shared scheduler so a slow run-now can't stall settings/keybinding/provider mutations
      • ✅ modelSelection.options dropped on edit — the draft keeps the original selection object and reuses it when instance+model are unchanged
      • ✅ Next: just now for future timestamps — future-aware labels (in 5m / in 2h / in 3d)
      • ✅ Double-submit — save button disabled while the upsert is in flight

      Verified: typecheck clean (contracts/client-runtime/server/web), schedule unit tests + MCP toolkit integration test pass, lint clean.

      🤖 Generated with Claude Code

    6. One Effect service convention issue in the newly added ScheduledTaskService. See the inline comment.

      Posted via Macroscope — Effect Service Conventions
    7. Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

      Autofix Details

      Bugbot Autofix prepared a fix for the issue found in the latest run.

      • ✅ Fixed: Stuck run stale schedule
        • Added a fresh findTask() read inside releaseStuckRun so next_run_at is computed from the current database state rather than the stale closure snapshot, mirroring the success path's approach.

      Create PR

      Or push these changes by commenting:

      @cursor push 151d7a1d12
      Preview (pingdotgg/t3code@151d7a1d12)
      diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts
      --- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts
      +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts
      @@ -363,11 +363,15 @@
           const releaseStuckRun = (task: ScheduledTask, message: string) =>
             Effect.gen(function* () {
               const now = yield* localNow;
      +        // Re-read the task so next_run_at is derived from the current schedule,
      +        // not the potentially stale snapshot captured when the run began.
      +        const current = yield* findTask(task.id);
      +        const scheduleSource = current ?? task;
               yield* sql`
                 UPDATE scheduled_tasks
                 SET last_run_status = 'failed',
                     last_run_error = ${message},
      -              next_run_at = ${nextRunAt(task, now)},
      +              next_run_at = ${nextRunAt(scheduleSource, now)},
                     updated_at = ${iso(now)},
                     run_count = run_count + 1
                 WHERE task_id = ${task.id} AND last_run_status = 'running'
      You can send follow-ups to the cloud agent here.
    8. Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

      There are 2 total unresolved issues (including 1 from previous review).

      Autofix Details

      Bugbot Autofix prepared a fix for the issue found in the latest run.

      • ✅ Fixed: Decode failure blocks stuck recovery
        • Replaced listRows() (which decodes all rows) with a targeted SQL query fetching only stuck rows (WHERE last_run_status = 'running'), and moved decode error handling to per-row scope so one corrupt row cannot block recovery of others.

      Create PR

      Or push these changes by commenting:

      @cursor push 0b61594760
      Preview (pingdotgg/t3code@0b61594760)
      diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts
      --- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts
      +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts
      @@ -551,23 +551,58 @@
           // and run_count must count the attempt — otherwise the first poll after
           // every restart re-fires the interrupted task (same rationale as
           // releaseStuckRun). Schedules are JSON, so this is per-row Effect work
      -    // rather than a single UPDATE.
      +    // rather than a single UPDATE. Only stuck rows are fetched so that
      +    // unrelated decode failures cannot block recovery.
           yield* Effect.gen(function* () {
      -      const tasks = yield* listRows();
      -      const stuck = tasks.filter((task) => task.lastRunStatus === "running");
      -      if (stuck.length === 0) return;
      +      const stuckRows = yield* sql<ScheduledTaskRow>`
      +        SELECT
      +          task_id,
      +          title,
      +          prompt,
      +          enabled,
      +          schedule_json,
      +          project_id,
      +          thread_id,
      +          workspace_strategy_json,
      +          model_selection_json,
      +          runtime_mode,
      +          interaction_mode,
      +          created_by,
      +          creation_source,
      +          created_at,
      +          updated_at,
      +          next_run_at,
      +          last_run_at,
      +          last_run_status,
      +          last_run_error,
      +          run_count
      +        FROM scheduled_tasks
      +        WHERE last_run_status = 'running'
      +      `;
      +      if (stuckRows.length === 0) return;
             const now = yield* localNow;
             yield* Effect.forEach(
      -        stuck,
      -        (task) => sql`
      -          UPDATE scheduled_tasks
      -          SET last_run_status = 'failed',
      -              last_run_error = 'Run was interrupted by a server restart.',
      -              next_run_at = ${nextRunAt(task, now)},
      -              updated_at = ${iso(now)},
      -              run_count = run_count + 1
      -          WHERE task_id = ${task.id} AND last_run_status = 'running'
      -        `,
      +        stuckRows,
      +        (row) =>
      +          Effect.gen(function* () {
      +            const task = yield* decodeRow(row);
      +            yield* sql`
      +              UPDATE scheduled_tasks
      +              SET last_run_status = 'failed',
      +                  last_run_error = 'Run was interrupted by a server restart.',
      +                  next_run_at = ${nextRunAt(task, now)},
      +                  updated_at = ${iso(now)},
      +                  run_count = run_count + 1
      +              WHERE task_id = ${task.id} AND last_run_status = 'running'
      +            `;
      +          }).pipe(
      +            Effect.catch((cause) =>
      +              Effect.logWarning("Could not recover stuck scheduled task row", {
      +                taskId: row.task_id,
      +                cause,
      +              }),
      +            ),
      +          ),
               { concurrency: 1, discard: true },
             );
             yield* notifyChanged;
      You can send follow-ups to the cloud agent here.
    9. Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

      There are 2 total unresolved issues (including 1 from previous review).

      Fix All in Cursor

      Bugbot Autofix prepared a fix for the issue found in the latest run.

      • ✅ Fixed: Schedule equality mismatches firing
        • Normalized weekdays in isSameSchedule by sorting and treating missing/empty or all-seven-days as equivalent null (every day), matching nextScheduledRunAt semantics so metadata-only upserts no longer reset next_run_at.

      Create PR

      Or push these changes by commenting:

      @cursor push 31b3b28377
      Preview (pingdotgg/t3code@31b3b28377)
      diff --git a/apps/server/src/scheduledTasks/Schedule.ts b/apps/server/src/scheduledTasks/Schedule.ts
      --- a/apps/server/src/scheduledTasks/Schedule.ts
      +++ b/apps/server/src/scheduledTasks/Schedule.ts
      @@ -35,16 +35,29 @@
         return null;
       }
       
      +/**
      + * Normalize weekdays to a canonical sorted array, treating missing/empty or
      + * all-seven-days as `null` (meaning "every day") to match `nextScheduledRunAt`
      + * semantics.
      + */
      +function normalizeWeekdays(weekdays: readonly number[] | undefined): readonly number[] | null {
      +  if (!weekdays || weekdays.length === 0) return null;
      +  const sorted = [...weekdays].sort((a, b) => a - b);
      +  if (sorted.length === 7) return null;
      +  return sorted;
      +}
      +
       /** Structural equality for schedules, independent of JSON key order. */
       export function isSameSchedule(a: ScheduledTaskSchedule, b: ScheduledTaskSchedule): boolean {
         if (a.type === "interval") {
           return b.type === "interval" && a.everyMs === b.everyMs;
         }
      -  return (
      -    b.type === "fixed_time" &&
      -    a.timeOfDay === b.timeOfDay &&
      -    (a.weekdays ?? []).join(",") === (b.weekdays ?? []).join(",")
      -  );
      +  if (b.type !== "fixed_time" || a.timeOfDay !== b.timeOfDay) return false;
      +  const aDays = normalizeWeekdays(a.weekdays);
      +  const bDays = normalizeWeekdays(b.weekdays);
      +  if (aDays === null && bDays === null) return true;
      +  if (aDays === null || bDays === null) return false;
      +  return aDays.length === bDays.length && aDays.every((d, i) => d === bDays[i]);
       }
       
       /**
      You can send follow-ups to the cloud agent here. Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit d851eb7b9c5f1cb0b5cf405c12da9baa405821bd. Configure [here](https://www.cursor.com/dashboard/bugbot).
    10. juliusmarminge merged thisdac514e

    11. juliusmarminge closed this

Sign in to join this conversation.