Skip to content
TypeScript

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

Satyam Bansalec967f3e823c
diff --git a/apps/server/src/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.ts
index e1bf858ca8f..fec17deae27 100644
--- a/apps/server/src/mcp/toolkits/thread/handlers.ts
+++ b/apps/server/src/mcp/toolkits/thread/handlers.ts
@@ -84,12 +84,12 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, {
code: "invalid_request",
message: "The scheduled task was not found.",
});
- const { task } = yield* scheduler
+ const { task, threadId } = yield* scheduler
.runNow({ id: input.taskId })
.pipe(Effect.mapError(unavailable));
return {
taskId: task.id,
- threadId: task.threadId,
+ threadId,
lastRunStatus: task.lastRunStatus,
runCount: task.runCount,
nextRunAt: task.nextRunAt,
diff --git a/apps/server/src/mcp/toolkits/thread/tools.ts b/apps/server/src/mcp/toolkits/thread/tools.ts
index b5fb7d6be3a..21750cbb6ea 100644
--- a/apps/server/src/mcp/toolkits/thread/tools.ts
+++ b/apps/server/src/mcp/toolkits/thread/tools.ts
@@ -257,7 +257,7 @@ const ThreadSearchTool = Tool.make("t3_thread_search", {
const ScheduledTaskRunTool = Tool.make("run_scheduled_task_now", {
...commandTool,
description:
- "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.",
+ "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.",
parameters: Schema.Struct({ taskId: ScheduledTaskId }),
success: Schema.Struct({
taskId: ScheduledTaskId,
diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
index aaaeda00f70..2d8d3cccf3d 100644
--- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
+++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
@@ -377,6 +377,7 @@ it.effect.each(
projectThreads.find((candidate) => candidate.id === existing?.threadId) ??
projectThreads[0];
assert.isDefined(thread);
+ assert.equal(result.threadId, thread!.id);
const projection = yield* threads.getThreadProjection(thread!.id);
const wire = yield* encodeThreadProjection(projection);
assert.equal(wire.messages[0]?.text, task.prompt);
@@ -392,6 +393,45 @@ it.effect.each(
},
);
+it.effect(
+ "returns no dispatched thread when sending an automation to a missing thread fails",
+ () => {
+ const harness = makeHarness();
+ const layerScheduledTasks = ScheduledTasks.layer.pipe(
+ Layer.provide(
+ Layer.mergeAll(
+ harness.layer,
+ NodeCrypto.layer,
+ Scheduler.layer,
+ Layer.mock(SecretRequests.SecretRequests)({}),
+ ),
+ ),
+ );
+ return Effect.gen(function* () {
+ const tasks = yield* ScheduledTasks.ScheduledTaskService;
+ const threadId = ThreadId.make("thread:missing");
+ const { task } = yield* tasks.upsert({
+ title: "Daily audit",
+ prompt: "Audit performance and crashes.",
+ enabled: false,
+ schedule: { type: "interval", everyMs: 60_000 },
+ projectId,
+ threadId,
+ workspaceStrategy: { type: "root" },
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ createdBy: "user",
+ creationSource: "web",
+ });
+ const result = yield* tasks.runNow({ id: task.id });
+ assert.equal(result.task.lastRunStatus, "failed");
+ assert.isNull(result.threadId);
+ assert.equal(result.task.threadId, threadId);
+ }).pipe(Effect.provide(Layer.mergeAll(harness.layer, layerScheduledTasks)));
+ },
+);
+
it.effect("runs a thread-bound automation on the provider the thread uses now", () => {
const harness = makeHarness({ adapters: [adapter, claudeAdapter] });
const layerScheduledTasks = ScheduledTasks.layer.pipe(
diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.interval.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.interval.test.ts
index 53ca5532a69..4a1a58505c5 100644
--- a/apps/server/src/scheduledTasks/ScheduledTaskService.interval.test.ts
+++ b/apps/server/src/scheduledTasks/ScheduledTaskService.interval.test.ts
@@ -95,6 +95,7 @@ it.effect.each([
// Exercise completion rescheduling without starting any provider process.
const completed = yield* service.runNow({ id: created.task.id });
expect(completed.task.lastRunStatus).toBe("failed");
+ expect(completed.threadId).toBeNull();
expect(completed.task.runCount).toBe(1);
expect(completed.task.nextRunAt).toBe(expected);
expect((yield* service.list()).tasks[0]?.nextRunAt).toBe(expected);
diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts
index 7255af89fca..d3d2ef19c6a 100644
--- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts
+++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts
@@ -208,9 +208,13 @@ export class ScheduledTaskService extends Context.Service<
) => Effect.Effect<ScheduledTaskDeleteResult, ScheduledTaskError>;
/** Deletes only tasks that still target this thread, including their webhook deliveries. */
readonly deleteForThread: (threadId: ThreadId) => Effect.Effect<void, ScheduledTaskError>;
+ /** The dispatched thread, or null if dispatch failed; leaves the task's binding unchanged. */
readonly runNow: (
input: ScheduledTaskRunNowInput,
- ) => Effect.Effect<ScheduledTaskRunNowResult, ScheduledTaskError>;
+ ) => Effect.Effect<
+ ScheduledTaskRunNowResult & { readonly threadId: ThreadId | null },
+ ScheduledTaskError
+ >;
readonly rotateWebhookToken: (
input: ScheduledTaskRotateWebhookTokenInput,
) => Effect.Effect<ScheduledTaskMutationResult, ScheduledTaskError>;
@@ -688,7 +692,7 @@ export const layer = Layer.effect(
if (trigger !== "scheduled") {
return yield* taskError("Schedule task is already running.", { taskId: task.id });
}
- return task;
+ return { task, threadId: null };
}
return yield* Effect.gen(function* () {
@@ -708,7 +712,7 @@ export const layer = Layer.effect(
if (trigger !== "scheduled") {
return yield* taskError("Schedule task not found.", { taskId: task.id });
}
- return task;
+ return { task, threadId: null };
}
const parsedNextRunAt =
active.nextRunAt === null ? Option.none() : DateTime.make(active.nextRunAt);
@@ -718,7 +722,7 @@ export const layer = Layer.effect(
Option.isNone(parsedNextRunAt) ||
DateTime.toEpochMillis(parsedNextRunAt.value) > DateTime.toEpochMillis(startedAt))
) {
- return active;
+ return { task: active, threadId: null };
}
// A queued delivery must not run a task that was paused, deleted and
// recreated under the same id, or switched to another trigger while
@@ -753,45 +757,50 @@ export const layer = Layer.effect(
const result =
active.threadId === null
? yield* Effect.exit(
- threadLaunch.launch({
- commandId,
- projectId: active.projectId,
- title: active.title,
- modelSelection: active.modelSelection,
- runtimeMode: active.runtimeMode,
- interactionMode: active.interactionMode,
- workspaceStrategy: active.workspaceStrategy,
- initialMessage: {
- messageId,
- scheduledTaskId: active.id,
- text: prompt,
- attachments: [],
- },
- createdBy: active.createdBy,
- creationSource: active.creationSource,
- }),
+ threadLaunch
+ .launch({
+ commandId,
+ projectId: active.projectId,
+ title: active.title,
+ modelSelection: active.modelSelection,
+ runtimeMode: active.runtimeMode,
+ interactionMode: active.interactionMode,
+ workspaceStrategy: active.workspaceStrategy,
+ initialMessage: {
+ messageId,
+ scheduledTaskId: active.id,
+ text: prompt,
+ attachments: [],
+ },
+ createdBy: active.createdBy,
+ creationSource: active.creationSource,
+ })
+ .pipe(Effect.map((launched) => launched.threadId)),
)
: yield* Effect.exit(
// The stored selection only seeds fresh threads. A bound run
// follows the thread's current provider, so it passes none.
- threadManagement.sendToThread({
- projectId: active.projectId,
- commandId,
- threadId: ThreadId.make(active.threadId),
- messageId,
- scheduledTaskId: active.id,
- text: prompt,
- attachments: [],
- mode: "queue",
- createdBy: active.createdBy,
- creationSource: active.creationSource,
- }),
+ threadManagement
+ .sendToThread({
+ projectId: active.projectId,
+ commandId,
+ threadId: ThreadId.make(active.threadId),
+ messageId,
+ scheduledTaskId: active.id,
+ text: prompt,
+ attachments: [],
+ mode: "queue",
+ createdBy: active.createdBy,
+ creationSource: active.creationSource,
+ })
+ .pipe(Effect.as(ThreadId.make(active.threadId))),
);
const completedAt = yield* localNow;
const runSucceeded = result._tag === "Success";
const lastRunStatus = runSucceeded ? ("succeeded" as const) : ("failed" as const);
const lastRunError = runSucceeded ? null : errorMessage(result.cause);
+ const threadId = runSucceeded ? result.value : null;
const current = yield* findTask(task.id);
const scheduleSource = current ?? task;
const completed: ScheduledTask = {
@@ -817,7 +826,7 @@ export const layer = Layer.effect(
});
yield* notifyChanged;
}
- return completed;
+ return { task: completed, threadId };
}).pipe(
Effect.onError((cause) => releaseStuckRun(task, errorMessage(cause))),
Effect.ensuring(
@@ -1153,12 +1162,11 @@ export const layer = Layer.effect(
taskId: input.id,
});
}
- const next = yield* runTask(task, "manual").pipe(
+ return yield* runTask(task, "manual").pipe(
Effect.mapError((cause) =>
taskError("Could not run schedule task.", { taskId: input.id, cause }),
),
);
- return { task: next };
});
const rotateWebhookToken: ScheduledTaskService["Service"]["rotateWebhookToken"] = Effect.fn(
@@ -1605,7 +1613,7 @@ export const layer = Layer.effect(
Metrics.increment(Metrics.webhookRunsTotal, { outcome }),
]);
yield* runTask(task, "webhook", { deliveryId, prompt: rendered.prompt }).pipe(
- Effect.flatMap((completed) =>
+ Effect.flatMap(({ task: completed }) =>
completed.lastRunStatus === "failed"
? runOutcome("failed").pipe(
Effect.andThen(markDeliveryFailed(deliveryId, "The run failed to start.")),