@devries-cameron20 / t3code-1 / commits / ec967f3e82
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(server): run_scheduled_task_now returns the thread the run launched (#17458)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Satyam Bansal committed Oct 20, 2026 at 10:44 UTC ec967f3e823ced78b67e88dcace4f87c71bcd32e
5 files changed +89 -40
apps/server/src/mcp/toolkits/thread/handlers.ts
+2 -2
@@ -84,12 +84,12 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, {
84 code: "invalid_request",
85 message: "The scheduled task was not found.",
86 });
87 - const { task } = yield* scheduler
87 + const { task, threadId } = yield* scheduler
88 .runNow({ id: input.taskId })
89 .pipe(Effect.mapError(unavailable));
90 return {
91 taskId: task.id,
92 - threadId: task.threadId,
92 + threadId,
93 lastRunStatus: task.lastRunStatus,
94 runCount: task.runCount,
95 nextRunAt: task.nextRunAt,
apps/server/src/mcp/toolkits/thread/tools.ts
+1 -1
@@ -257,7 +257,7 @@ const ThreadSearchTool = Tool.make("t3_thread_search", {
257 const ScheduledTaskRunTool = Tool.make("run_scheduled_task_now", {
258 ...commandTool,
259 description:
260 - "Run a scheduled task now through the existing scheduler. Requires a full-access/default caller. Each call is a new manual run; completion means dispatch/bookkeeping completed, not that the provider turn finished.",
260 + "Run a scheduled task now through the existing scheduler. Requires a full-access/default caller. Returns the thread this run dispatched to, or null if dispatch failed. Each call is a new manual run; completion means dispatch/bookkeeping completed, not that the provider turn finished.",
261 parameters: Schema.Struct({ taskId: ScheduledTaskId }),
262 success: Schema.Struct({
263 taskId: ScheduledTaskId,
apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
+40
@@ -377,6 +377,7 @@ it.effect.each(
377 projectThreads.find((candidate) => candidate.id === existing?.threadId) ??
378 projectThreads[0];
379 assert.isDefined(thread);
380 + assert.equal(result.threadId, thread!.id);
381 const projection = yield* threads.getThreadProjection(thread!.id);
382 const wire = yield* encodeThreadProjection(projection);
383 assert.equal(wire.messages[0]?.text, task.prompt);
@@ -392,6 +393,45 @@ it.effect.each(
393 },
394 );
395
396 +it.effect(
397 + "returns no dispatched thread when sending an automation to a missing thread fails",
398 + () => {
399 + const harness = makeHarness();
400 + const layerScheduledTasks = ScheduledTasks.layer.pipe(
401 + Layer.provide(
402 + Layer.mergeAll(
403 + harness.layer,
404 + NodeCrypto.layer,
405 + Scheduler.layer,
406 + Layer.mock(SecretRequests.SecretRequests)({}),
407 + ),
408 + ),
409 + );
410 + return Effect.gen(function* () {
411 + const tasks = yield* ScheduledTasks.ScheduledTaskService;
412 + const threadId = ThreadId.make("thread:missing");
413 + const { task } = yield* tasks.upsert({
414 + title: "Daily audit",
415 + prompt: "Audit performance and crashes.",
416 + enabled: false,
417 + schedule: { type: "interval", everyMs: 60_000 },
418 + projectId,
419 + threadId,
420 + workspaceStrategy: { type: "root" },
421 + modelSelection,
422 + runtimeMode: "full-access",
423 + interactionMode: "default",
424 + createdBy: "user",
425 + creationSource: "web",
426 + });
427 + const result = yield* tasks.runNow({ id: task.id });
428 + assert.equal(result.task.lastRunStatus, "failed");
429 + assert.isNull(result.threadId);
430 + assert.equal(result.task.threadId, threadId);
431 + }).pipe(Effect.provide(Layer.mergeAll(harness.layer, layerScheduledTasks)));
432 + },
433 +);
434 +
435 it.effect("runs a thread-bound automation on the provider the thread uses now", () => {
436 const harness = makeHarness({ adapters: [adapter, claudeAdapter] });
437 const layerScheduledTasks = ScheduledTasks.layer.pipe(
apps/server/src/scheduledTasks/ScheduledTaskService.interval.test.ts
+1
@@ -95,6 +95,7 @@ it.effect.each([
95 // Exercise completion rescheduling without starting any provider process.
96 const completed = yield* service.runNow({ id: created.task.id });
97 expect(completed.task.lastRunStatus).toBe("failed");
98 + expect(completed.threadId).toBeNull();
99 expect(completed.task.runCount).toBe(1);
100 expect(completed.task.nextRunAt).toBe(expected);
101 expect((yield* service.list()).tasks[0]?.nextRunAt).toBe(expected);
apps/server/src/scheduledTasks/ScheduledTaskService.ts
+45 -37
@@ -208,9 +208,13 @@ export class ScheduledTaskService extends Context.Service<
208 ) => Effect.Effect<ScheduledTaskDeleteResult, ScheduledTaskError>;
209 /** Deletes only tasks that still target this thread, including their webhook deliveries. */
210 readonly deleteForThread: (threadId: ThreadId) => Effect.Effect<void, ScheduledTaskError>;
211 + /** The dispatched thread, or null if dispatch failed; leaves the task's binding unchanged. */
212 readonly runNow: (
213 input: ScheduledTaskRunNowInput,
213 - ) => Effect.Effect<ScheduledTaskRunNowResult, ScheduledTaskError>;
214 + ) => Effect.Effect<
215 + ScheduledTaskRunNowResult & { readonly threadId: ThreadId | null },
216 + ScheduledTaskError
217 + >;
218 readonly rotateWebhookToken: (
219 input: ScheduledTaskRotateWebhookTokenInput,
220 ) => Effect.Effect<ScheduledTaskMutationResult, ScheduledTaskError>;
@@ -688,7 +692,7 @@ export const layer = Layer.effect(
692 if (trigger !== "scheduled") {
693 return yield* taskError("Schedule task is already running.", { taskId: task.id });
694 }
691 - return task;
695 + return { task, threadId: null };
696 }
697
698 return yield* Effect.gen(function* () {
@@ -708,7 +712,7 @@ export const layer = Layer.effect(
712 if (trigger !== "scheduled") {
713 return yield* taskError("Schedule task not found.", { taskId: task.id });
714 }
711 - return task;
715 + return { task, threadId: null };
716 }
717 const parsedNextRunAt =
718 active.nextRunAt === null ? Option.none() : DateTime.make(active.nextRunAt);
@@ -718,7 +722,7 @@ export const layer = Layer.effect(
722 Option.isNone(parsedNextRunAt) ||
723 DateTime.toEpochMillis(parsedNextRunAt.value) > DateTime.toEpochMillis(startedAt))
724 ) {
721 - return active;
725 + return { task: active, threadId: null };
726 }
727 // A queued delivery must not run a task that was paused, deleted and
728 // recreated under the same id, or switched to another trigger while
@@ -753,45 +757,50 @@ export const layer = Layer.effect(
757 const result =
758 active.threadId === null
759 ? yield* Effect.exit(
756 - threadLaunch.launch({
757 - commandId,
758 - projectId: active.projectId,
759 - title: active.title,
760 - modelSelection: active.modelSelection,
761 - runtimeMode: active.runtimeMode,
762 - interactionMode: active.interactionMode,
763 - workspaceStrategy: active.workspaceStrategy,
764 - initialMessage: {
765 - messageId,
766 - scheduledTaskId: active.id,
767 - text: prompt,
768 - attachments: [],
769 - },
770 - createdBy: active.createdBy,
771 - creationSource: active.creationSource,
772 - }),
760 + threadLaunch
761 + .launch({
762 + commandId,
763 + projectId: active.projectId,
764 + title: active.title,
765 + modelSelection: active.modelSelection,
766 + runtimeMode: active.runtimeMode,
767 + interactionMode: active.interactionMode,
768 + workspaceStrategy: active.workspaceStrategy,
769 + initialMessage: {
770 + messageId,
771 + scheduledTaskId: active.id,
772 + text: prompt,
773 + attachments: [],
774 + },
775 + createdBy: active.createdBy,
776 + creationSource: active.creationSource,
777 + })
778 + .pipe(Effect.map((launched) => launched.threadId)),
779 )
780 : yield* Effect.exit(
781 // The stored selection only seeds fresh threads. A bound run
782 // follows the thread's current provider, so it passes none.
777 - threadManagement.sendToThread({
778 - projectId: active.projectId,
779 - commandId,
780 - threadId: ThreadId.make(active.threadId),
781 - messageId,
782 - scheduledTaskId: active.id,
783 - text: prompt,
784 - attachments: [],
785 - mode: "queue",
786 - createdBy: active.createdBy,
787 - creationSource: active.creationSource,
788 - }),
783 + threadManagement
784 + .sendToThread({
785 + projectId: active.projectId,
786 + commandId,
787 + threadId: ThreadId.make(active.threadId),
788 + messageId,
789 + scheduledTaskId: active.id,
790 + text: prompt,
791 + attachments: [],
792 + mode: "queue",
793 + createdBy: active.createdBy,
794 + creationSource: active.creationSource,
795 + })
796 + .pipe(Effect.as(ThreadId.make(active.threadId))),
797 );
798
799 const completedAt = yield* localNow;
800 const runSucceeded = result._tag === "Success";
801 const lastRunStatus = runSucceeded ? ("succeeded" as const) : ("failed" as const);
802 const lastRunError = runSucceeded ? null : errorMessage(result.cause);
803 + const threadId = runSucceeded ? result.value : null;
804 const current = yield* findTask(task.id);
805 const scheduleSource = current ?? task;
806 const completed: ScheduledTask = {
@@ -817,7 +826,7 @@ export const layer = Layer.effect(
826 });
827 yield* notifyChanged;
828 }
820 - return completed;
829 + return { task: completed, threadId };
830 }).pipe(
831 Effect.onError((cause) => releaseStuckRun(task, errorMessage(cause))),
832 Effect.ensuring(
@@ -1153,12 +1162,11 @@ export const layer = Layer.effect(
1162 taskId: input.id,
1163 });
1164 }
1156 - const next = yield* runTask(task, "manual").pipe(
1165 + return yield* runTask(task, "manual").pipe(
1166 Effect.mapError((cause) =>
1167 taskError("Could not run schedule task.", { taskId: input.id, cause }),
1168 ),
1169 );
1161 - return { task: next };
1170 });
1171
1172 const rotateWebhookToken: ScheduledTaskService["Service"]["rotateWebhookToken"] = Effect.fn(
@@ -1605,7 +1613,7 @@ export const layer = Layer.effect(
1613 Metrics.increment(Metrics.webhookRunsTotal, { outcome }),
1614 ]);
1615 yield* runTask(task, "webhook", { deliveryId, prompt: rendered.prompt }).pipe(
1608 - Effect.flatMap((completed) =>
1616 + Effect.flatMap(({ task: completed }) =>
1617 completed.lastRunStatus === "failed"
1618 ? runOutcome("failed").pipe(
1619 Effect.andThen(markDeliveryFailed(deliveryId, "The run failed to start.")),