diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts index 92167ef83c5ca..0bbda517000c3 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts @@ -14,6 +14,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; import * as TestClock from "effect/testing/TestClock"; import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts"; @@ -195,6 +196,8 @@ it.effect("keeps one queued occurrence of a recurring task while its bound threa readonly messages: ReadonlyArray; }>({ runs: [activeRun], messages: [] }); const runDueWork = yield* Ref.make>(Effect.void); + const sql = yield* SqlClient.SqlClient; + const outcomeDuringLookup = yield* Ref.make(false); const layerDependencies = Layer.mergeAll( NodeCrypto.layer, ManagedPolicy.layerTest(), @@ -241,7 +244,18 @@ it.effect("keeps one queued occurrence of a recurring task while its bound threa { runs: [...current.runs, run], messages: [...current.messages, message] }, ]; }), - getThreadRecords: () => Ref.get(thread).pipe(Effect.map((records) => records as never)), + getThreadRecords: (_id, fields) => + Effect.gen(function* () { + if ( + fields.some((field) => field === "messages") && + (yield* Ref.get(outcomeDuringLookup)) + ) { + yield* Ref.set(outcomeDuringLookup, false); + yield* sql`UPDATE scheduled_tasks SET last_run_status = 'failed', + last_run_error = 'Provider failed' WHERE task_id = 'scheduled-task:busy-thread'`; + } + return (yield* Ref.get(thread)) as never; + }).pipe(Effect.orDie), getThreadShell: () => Effect.succeed({ projectId: "project-busy-thread", @@ -292,6 +306,34 @@ it.effect("keeps one queued occurrence of a recurring task while its bound threa Date.parse("2026-07-01T09:03:03.000Z"), ); + yield* Ref.update(thread, (current) => ({ + ...current, + runs: current.runs.map((run) => + run.status === "queued" ? { ...run, queueHeld: true } : run, + ), + })); + yield* TestClock.adjust("61 seconds"); + yield* Effect.flatten(Ref.get(runDueWork)); + const [blocked] = (yield* service.list()).tasks; + expect(blocked?.lastRunStatus).toBe("failed"); + expect(blocked?.lastRunError).toBe( + "A previous occurrence is held in the thread queue. Resume or remove it to run this task again.", + ); + expect(yield* queuedOccurrences).toBe(1); + + // The prior run can finish while the poll is looking up its held occurrence. + yield* sql`UPDATE scheduled_tasks SET last_run_status = 'succeeded', last_run_error = NULL + WHERE task_id = ${task.id}`; + yield* Ref.set(outcomeDuringLookup, true); + yield* TestClock.adjust("61 seconds"); + yield* Effect.flatten(Ref.get(runDueWork)); + const [raced] = (yield* service.list()).tasks; + expect(raced?.lastRunStatus).toBe("failed"); + expect(raced?.lastRunError).toBe("Provider failed"); + expect(Date.parse(raced?.nextRunAt ?? "")).toBeGreaterThan( + Date.parse(blocked?.nextRunAt ?? ""), + ); + // Run now is an explicit request, so it still queues behind the held one. yield* service.runNow({ id: task.id }); expect(yield* queuedOccurrences).toBe(2); @@ -306,6 +348,9 @@ it.effect("keeps one queued occurrence of a recurring task while its bound threa yield* TestClock.adjust("61 seconds"); yield* Effect.flatten(Ref.get(runDueWork)); expect(yield* queuedOccurrences).toBe(1); + const [resumed] = (yield* service.list()).tasks; + expect(resumed?.lastRunStatus).toBe("succeeded"); + expect(resumed?.lastRunError).toBeNull(); // A one-time task's only scheduled occurrence still sends behind a queued Run now. const { task: once } = yield* service.upsert( @@ -314,7 +359,7 @@ it.effect("keeps one queued occurrence of a recurring task while its bound threa title: "Check once", prompt: "Check once", enabled: true, - schedule: { type: "once", runAt: "2026-07-01T09:05:00.000Z" }, + schedule: { type: "once", runAt: "2026-07-01T09:07:00.000Z" }, projectId: "project-busy-thread", threadId: "thread:busy", workspaceStrategy: { type: "root" }, diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts index 98a5bc040c238..051aeeac9b693 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts @@ -422,9 +422,10 @@ it.effect("thread cleanup notifies subscribers and a finishing run cannot recrea ); it.effect.each([ - { status: "failed", error: "Weekly usage limit reached" }, - { status: "interrupted", error: "The run was stopped." }, - { status: "cancelled", error: "The run was cancelled." }, + { status: "failed", error: "Weekly usage limit reached", heldWarning: false }, + { status: "failed", error: "Weekly usage limit reached", heldWarning: true }, + { status: "interrupted", error: "The run was stopped.", heldWarning: false }, + { status: "cancelled", error: "The run was cancelled.", heldWarning: false }, ] as const)("a run that ends $status after its message was accepted records it", (outcome) => Effect.gen(function* () { const projectId = ProjectId.make("project:test"); @@ -495,9 +496,15 @@ it.effect.each([ interactionMode: "default", }); yield* service.runNow({ id: task.id }); + if (outcome.heldWarning) { + const sql = yield* SqlClient.SqlClient; + yield* sql`UPDATE scheduled_tasks SET last_run_status = 'failed', + last_run_error = 'A previous occurrence is held in the thread queue. Resume or remove it to run this task again.' + WHERE task_id = ${task.id}`; + } const failed = yield* service.subscribeList().pipe( Stream.map(({ tasks }) => tasks.find((candidate) => candidate.id === task.id)), - Stream.filter((current) => current?.lastRunStatus === "failed"), + Stream.filter((current) => current?.lastRunError === outcome.error), Stream.runHead, Effect.forkChild, ); diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts index daf419c5def81..4570115a91cec 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts @@ -311,6 +311,8 @@ function iso(value: DateTime.DateTime): string { } const RUN_OUTCOME_WAIT_MS = 24 * 60 * 60 * 1_000; +const HELD_OCCURRENCE_ERROR = + "A previous occurrence is held in the thread queue. Resume or remove it to run this task again."; const UNSUCCESSFUL_RUN_ERRORS = { failed: "The run failed.", interrupted: "The run was stopped.", @@ -848,20 +850,28 @@ export const layer = Layer.effect( // Reads every run row but only the queued runs' messages, so the cost per // due interval tracks the thread's run count, not its transcript. - const hasQueuedOccurrence = Effect.fn("ScheduledTaskService.hasQueuedOccurrence")(function* ( + const queuedOccurrence = Effect.fn("ScheduledTaskService.queuedOccurrence")(function* ( taskId: ScheduledTaskId, threadId: ThreadId, ) { const { runs } = yield* threadManagement.getThreadRecords(threadId, ["runs"]); const queued = runs.filter((run) => run.status === "queued"); - if (queued.length === 0) return false; + if (queued.length === 0) return null; const queuedMessageIds = new Set(queued.map((run) => run.userMessageId)); const { messages } = yield* threadManagement.getThreadRecords(threadId, ["messages"], { messageIds: [...queuedMessageIds], }); - return messages.some( - (message) => queuedMessageIds.has(message.id) && message.scheduledTaskId === taskId, + const taskMessageIds = new Set( + messages + .filter((message) => message.scheduledTaskId === taskId) + .map((message) => message.id), ); + const occurrences = queued.filter((run) => taskMessageIds.has(run.userMessageId)); + return occurrences.some((run) => run.queueHeld === true) + ? "held" + : occurrences.length > 0 + ? "queued" + : null; }); // The run already started the thread, so a failed write only costs the binding. @@ -940,7 +950,9 @@ export const layer = Layer.effect( const updated = yield* sql` UPDATE scheduled_tasks SET last_run_status = 'failed', last_run_error = ${error} - WHERE task_id = ${taskId} AND last_run_at = ${startedAtIso} AND last_run_status = 'succeeded' + WHERE task_id = ${taskId} AND last_run_at = ${startedAtIso} + AND (last_run_status = 'succeeded' + OR (last_run_status = 'failed' AND last_run_error = ${HELD_OCCURRENCE_ERROR})) RETURNING task_id `; if (updated.length > 0) yield* notifyChanged; @@ -998,13 +1010,21 @@ export const layer = Layer.effect( if ( trigger === "scheduled" && active.schedule.type !== "once" && - active.threadId !== null && - (yield* hasQueuedOccurrence(active.id, ThreadId.make(active.threadId)).pipe( - Effect.orElseSucceed(() => false), - )) + active.threadId !== null ) { - yield* rescheduleMissedRun(active, startedAt, "previous occurrence still queued"); - return { task: active, threadId: null, dispatchFailed: false }; + const occurrence = yield* queuedOccurrence( + active.id, + ThreadId.make(active.threadId), + ).pipe(Effect.orElseSucceed(() => null)); + if (occurrence !== null) { + yield* rescheduleMissedRun( + active, + startedAt, + "previous occurrence still queued", + occurrence === "held" ? HELD_OCCURRENCE_ERROR : undefined, + ); + return { task: active, threadId: null, dispatchFailed: false }; + } } // Reject queued deliveries after pause, same-id recreation or trigger changes. if (webhook !== undefined) { @@ -1254,7 +1274,16 @@ export const layer = Layer.effect( UPDATE scheduled_tasks SET next_run_at = ${next}, updated_at = ${iso(now)} - ${runError === undefined ? sql`` : sql`, last_run_status = 'failed', last_run_error = ${runError}`} + ${ + runError === undefined + ? sql`` + : sql`, last_run_status = CASE + WHEN last_run_status IS ${task.lastRunStatus} AND last_run_error IS ${task.lastRunError} + THEN 'failed' ELSE last_run_status END, + last_run_error = CASE + WHEN last_run_status IS ${task.lastRunStatus} AND last_run_error IS ${task.lastRunError} + THEN ${runError} ELSE last_run_error END` + } WHERE task_id = ${task.id} AND next_run_at IS ${task.nextRunAt} AND last_run_at IS ${task.lastRunAt} diff --git a/scripts/scenarios/held-scheduled-occurrence.e2e.ts b/scripts/scenarios/held-scheduled-occurrence.e2e.ts new file mode 100644 index 0000000000000..7ea41711e4d16 --- /dev/null +++ b/scripts/scenarios/held-scheduled-occurrence.e2e.ts @@ -0,0 +1,78 @@ +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; + +import { T3_HOME } from "../e2e.config.ts"; +import { runPromise, test, WEB } from "./t3.ts"; + +const SettingsJson = Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)); +const decodeSettings = Schema.decodeEffect(SettingsJson); +const encodeSettings = Schema.encodeEffect(SettingsJson); + +const threadRuntimeSettings = Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const settingsPath = (yield* Path.Path).join(T3_HOME, "userdata/settings.json"); + const original = yield* fs.readFileString(settingsPath); + const settings = yield* decodeSettings(original); + return { + supervise: fs.writeFileString( + settingsPath, + yield* encodeSettings({ ...settings, defaultRuntimeMode: "approval-required" }), + ), + restore: fs.writeFileString(settingsPath, original), + }; +}); + +test( + "A recurring task reports when its queued occurrence is held", + WEB, + async ({ t3, app, screen }) => { + const settings = await runPromise(threadRuntimeSettings); + try { + // Supervised mode makes the approval recording wait for an answer, which holds its turn open. + await runPromise(settings.supervise); + const project = await t3.project("scheduled-hold"); + await t3.thread({ project, title: "Earlier work", messages: ["Start"] }); + const thread = await t3.thread({ + project, + title: "Waiting scheduled thread", + messages: ["Ask a question"], + model: "approval", + }); + + await t3.open("/settings/scheduled-tasks"); + await screen.getByRole("button", "New task").tap(); + await screen.getByRole("textbox", "Name").fill("Held recurring task"); + await screen.getByRole("combobox", "Destination").tap(); + await screen.getByRole("option", "One thread, continuing the conversation").tap(); + await screen.getByRole("combobox", "Destination thread").tap(); + await screen.getByRole("option", "Waiting scheduled thread").tap(); + await screen.getByRole("textbox", "Prompt").fill("Scheduled check prompt"); + await screen.getByRole("button", "Every interval").tap(); + await screen.getByRole("spinbutton", "Run every").fill("1"); + await screen.getByRole("button", "Create task").tap(); + + await t3.open(thread); + await screen.getByRole("button", "Approve", { exact: true }).waitFor(); + await screen + .getByRole("button", "Automation Held recurring task") + .waitFor({ timeout: 100_000 }); + // Stopping the active turn holds the queued scheduled occurrence. + await screen.getByRole("button", "Stop generation").tap(); + await screen.getByRole("button", "Resume thread").waitFor(); + await screen.getByRole("button", "Edit queued message").waitFor(); + + await app.open("/settings/scheduled-tasks"); + await expect( + screen.getByText( + "A previous occurrence is held in the thread queue. Resume or remove it to run this task again.", + ), + ).toBeVisible({ timeout: 100_000 }); + await app.screenshot("held-scheduled-task"); + } finally { + await runPromise(settings.restore); + } + }, +);