The best way to control Claude Code, Codex and more from any computer or phone
fix(server): recurring tasks keep one queued occurrence while their thread is busy (#23609)
Julius Marminge committed
Nov 11, 2026 at 15:58 UTC
1d61dd3fd6150e70a5e4c3ae0d3891df643761e1
2 files changed
+193
-2
apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts
+159
-1
@@ -1,11 +1,18 @@
1
import * as Scheduler from "../scheduling/Scheduler.ts";
2
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3
import { expect, it } from "@effect/vitest";
4
-import { ScheduledTaskUpsertInput } from "@t3tools/contracts";
4
+import {
5
+ type OrchestrationV2ConversationMessage,
6
+ type OrchestrationV2Run,
7
+ MessageId,
8
+ RunId,
9
+ ScheduledTaskUpsertInput,
10
+} from "@t3tools/contracts";
11
import * as DateTime from "effect/DateTime";
12
import * as Deferred from "effect/Deferred";
13
import * as Effect from "effect/Effect";
14
import * as Layer from "effect/Layer";
15
+import * as Ref from "effect/Ref";
16
import * as Schema from "effect/Schema";
17
import * as TestClock from "effect/testing/TestClock";
18
@@ -173,6 +180,157 @@ it.effect("keeps the task list order when a toggle or edit rewrites updated_at",
180
}).pipe(Effect.provide(SqlitePersistence.layerMemory)),
181
);
182
183
+it.effect("keeps one queued occurrence of a recurring task while its bound thread is busy", () =>
184
+ Effect.gen(function* () {
185
+ yield* TestClock.setTime(Date.parse("2026-07-01T09:00:00.000Z"));
186
+ // The bound thread's own run never finishes, so every scheduled send lands
187
+ // in its queue and stays there.
188
+ const activeRun = {
189
+ id: RunId.make("run:busy"),
190
+ status: "running",
191
+ userMessageId: MessageId.make("message:busy"),
192
+ } as OrchestrationV2Run;
193
+ const thread = yield* Ref.make<{
194
+ readonly runs: ReadonlyArray<OrchestrationV2Run>;
195
+ readonly messages: ReadonlyArray<OrchestrationV2ConversationMessage>;
196
+ }>({ runs: [activeRun], messages: [] });
197
+ const runDueWork = yield* Ref.make<Effect.Effect<void>>(Effect.void);
198
+ const layerDependencies = Layer.mergeAll(
199
+ NodeCrypto.layer,
200
+ ManagedPolicy.layerTest(),
201
+ // Capture the poll pass so the test drives each due interval directly.
202
+ Layer.mock(Scheduler.Scheduler)({
203
+ register: (name, work) =>
204
+ name !== "scheduled-tasks"
205
+ ? Effect.void
206
+ : Effect.context<Effect.Services<typeof work>>().pipe(
207
+ Effect.flatMap((context) =>
208
+ Ref.set(runDueWork, work.pipe(Effect.provideContext(context), Effect.ignore)),
209
+ ),
210
+ ),
211
+ }),
212
+ Layer.mock(ThreadLaunchService.ThreadLaunchService)({}),
213
+ Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
214
+ namedProjectsRoot: "/projects",
215
+ isScratchProject: () => Effect.succeed(false),
216
+ }),
217
+ Layer.mock(ThreadManagementService.ThreadManagementService)({
218
+ sendToThread: (input) =>
219
+ Ref.modify(thread, (current) => {
220
+ const run = {
221
+ id: RunId.make(`run:${input.messageId}`),
222
+ status: "queued",
223
+ userMessageId: input.messageId,
224
+ } as OrchestrationV2Run;
225
+ const message = {
226
+ id: input.messageId,
227
+ threadId: input.threadId,
228
+ runId: run.id,
229
+ role: "user",
230
+ text: input.text,
231
+ ...(input.scheduledTaskId === undefined
232
+ ? {}
233
+ : { scheduledTaskId: input.scheduledTaskId }),
234
+ } as OrchestrationV2ConversationMessage;
235
+ return [
236
+ {
237
+ delivery: "queued",
238
+ run,
239
+ message,
240
+ } as ThreadManagementService.ThreadManagementSendResult,
241
+ { runs: [...current.runs, run], messages: [...current.messages, message] },
242
+ ];
243
+ }),
244
+ getThreadRecords: () => Ref.get(thread).pipe(Effect.map((records) => records as never)),
245
+ getThreadShell: () =>
246
+ Effect.succeed({
247
+ projectId: "project-busy-thread",
248
+ deletedAt: null,
249
+ archivedAt: null,
250
+ } as never),
251
+ }),
252
+ Layer.mock(SecretRequests.SecretRequests)({}),
253
+ );
254
+ yield* Effect.gen(function* () {
255
+ const service = yield* ScheduledTaskService.ScheduledTaskService;
256
+ const { task } = yield* service.upsert(
257
+ yield* decodeUpsertInput({
258
+ id: "scheduled-task:busy-thread",
259
+ title: "Check progress",
260
+ prompt: "Check progress",
261
+ enabled: true,
262
+ schedule: { type: "interval", everyMs: 60_000 },
263
+ projectId: "project-busy-thread",
264
+ threadId: "thread:busy",
265
+ workspaceStrategy: { type: "root" },
266
+ modelSelection: { instanceId: "codex", model: "gpt-5.4" },
267
+ runtimeMode: "full-access",
268
+ interactionMode: "default",
269
+ }),
270
+ );
271
+
272
+ for (let interval = 0; interval < 3; interval++) {
273
+ yield* TestClock.adjust("61 seconds");
274
+ yield* Effect.flatten(Ref.get(runDueWork));
275
+ }
276
+
277
+ const queuedOccurrencesOf = (taskId: typeof task.id) =>
278
+ Ref.get(thread).pipe(
279
+ Effect.map(
280
+ ({ runs, messages }) =>
281
+ runs
282
+ .filter((run) => run.status === "queued")
283
+ .map((run) => messages.find((message) => message.id === run.userMessageId))
284
+ .filter((message) => message?.scheduledTaskId === taskId).length,
285
+ ),
286
+ );
287
+ const queuedOccurrences = queuedOccurrencesOf(task.id);
288
+ expect(yield* queuedOccurrences).toBe(1);
289
+ // Skipped intervals still move the schedule forward.
290
+ const [listed] = (yield* service.list()).tasks;
291
+ expect(Date.parse(listed?.nextRunAt ?? "")).toBeGreaterThan(
292
+ Date.parse("2026-07-01T09:03:03.000Z"),
293
+ );
294
+
295
+ // Run now is an explicit request, so it still queues behind the held one.
296
+ yield* service.runNow({ id: task.id });
297
+ expect(yield* queuedOccurrences).toBe(2);
298
+
299
+ // Once the queued copies start, the next interval sends again.
300
+ yield* Ref.update(thread, (current) => ({
301
+ ...current,
302
+ runs: current.runs.map((run) =>
303
+ run.status === "queued" ? ({ ...run, status: "running" } as OrchestrationV2Run) : run,
304
+ ),
305
+ }));
306
+ yield* TestClock.adjust("61 seconds");
307
+ yield* Effect.flatten(Ref.get(runDueWork));
308
+ expect(yield* queuedOccurrences).toBe(1);
309
+
310
+ // A one-time task's only scheduled occurrence still sends behind a queued Run now.
311
+ const { task: once } = yield* service.upsert(
312
+ yield* decodeUpsertInput({
313
+ id: "scheduled-task:busy-thread-once",
314
+ title: "Check once",
315
+ prompt: "Check once",
316
+ enabled: true,
317
+ schedule: { type: "once", runAt: "2026-07-01T09:05:00.000Z" },
318
+ projectId: "project-busy-thread",
319
+ threadId: "thread:busy",
320
+ workspaceStrategy: { type: "root" },
321
+ modelSelection: { instanceId: "codex", model: "gpt-5.4" },
322
+ runtimeMode: "full-access",
323
+ interactionMode: "default",
324
+ }),
325
+ );
326
+ yield* service.runNow({ id: once.id });
327
+ yield* TestClock.adjust("61 seconds");
328
+ yield* Effect.flatten(Ref.get(runDueWork));
329
+ expect(yield* queuedOccurrencesOf(once.id)).toBe(2);
330
+ }).pipe(Effect.provide(ScheduledTaskService.layer.pipe(Layer.provide(layerDependencies))));
331
+ }).pipe(Effect.provide(SqlitePersistence.layerMemory)),
332
+);
333
+
334
it.effect(
335
"idle polls still wake for tasks saved later, recorded due times, and beside far-future tasks",
336
() =>
apps/server/src/scheduledTasks/ScheduledTaskService.ts
+34
-1
@@ -826,6 +826,24 @@ export const layer = Layer.effect(
826
),
827
);
828
829
+ // Reads every run row but only the queued runs' messages, so the cost per
830
+ // due interval tracks the thread's run count, not its transcript.
831
+ const hasQueuedOccurrence = Effect.fn("ScheduledTaskService.hasQueuedOccurrence")(function* (
832
+ taskId: ScheduledTaskId,
833
+ threadId: ThreadId,
834
+ ) {
835
+ const { runs } = yield* threadManagement.getThreadRecords(threadId, ["runs"]);
836
+ const queued = runs.filter((run) => run.status === "queued");
837
+ if (queued.length === 0) return false;
838
+ const queuedMessageIds = new Set(queued.map((run) => run.userMessageId));
839
+ const { messages } = yield* threadManagement.getThreadRecords(threadId, ["messages"], {
840
+ messageIds: [...queuedMessageIds],
841
+ });
842
+ return messages.some(
843
+ (message) => queuedMessageIds.has(message.id) && message.scheduledTaskId === taskId,
844
+ );
845
+ });
846
+
847
// The run already started the thread, so a failed write only costs the binding.
848
// A thread deleted before the binding landed already ran its task cleanup, so apply that
849
// cleanup here; a later deletion finds the binding. An unconfirmed lookup keeps the binding.
@@ -892,6 +910,19 @@ export const layer = Layer.effect(
910
) {
911
return { task: active, threadId: null, dispatchFailed: false };
912
}
913
+ // A thread that stays busy would otherwise collect one copy of the
914
+ // prompt per interval. A failed read falls through to the normal send.
915
+ if (
916
+ trigger === "scheduled" &&
917
+ active.schedule.type !== "once" &&
918
+ active.threadId !== null &&
919
+ (yield* hasQueuedOccurrence(active.id, ThreadId.make(active.threadId)).pipe(
920
+ Effect.orElseSucceed(() => false),
921
+ ))
922
+ ) {
923
+ yield* rescheduleMissedRun(active, startedAt, "previous occurrence still queued");
924
+ return { task: active, threadId: null, dispatchFailed: false };
925
+ }
926
// Reject queued deliveries after pause, same-id recreation or trigger changes.
927
if (webhook !== undefined) {
928
const reason =
@@ -1114,10 +1145,12 @@ export const layer = Layer.effect(
1145
const rescheduleMissedRun = Effect.fn("ScheduledTaskService.rescheduleMissedRun")(function* (
1146
task: ScheduledTask,
1147
now: DateTime.DateTime,
1148
+ reason = "missed",
1149
) {
1150
const next = nextRunAt(task, now);
1119
- yield* Effect.logInfo("Skipping missed schedule task run", {
1151
+ yield* Effect.logInfo("Skipping schedule task run", {
1152
taskId: task.id,
1153
+ reason,
1154
missedRunAt: task.nextRunAt,
1155
rescheduledTo: next,
1156
});