Skip to content

Commit ec967f3

Browse files
sbansal1999claudejuliusmarminge
authored
fix(server): run_scheduled_task_now returns the thread the run launched (pingdotgg#17458)
Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Julius Marminge <[email protected]>
1 parent 6e45544 commit ec967f3

5 files changed

Lines changed: 89 additions & 40 deletions

File tree

‎apps/server/src/mcp/toolkits/thread/handlers.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,12 +84,12 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, {
8484
code: "invalid_request",
8585
message: "The scheduled task was not found.",
8686
});
87-
const { task } = yield* scheduler
87+
const { task, threadId } = yield* scheduler
8888
.runNow({ id: input.taskId })
8989
.pipe(Effect.mapError(unavailable));
9090
return {
9191
taskId: task.id,
92-
threadId: task.threadId,
92+
threadId,
9393
lastRunStatus: task.lastRunStatus,
9494
runCount: task.runCount,
9595
nextRunAt: task.nextRunAt,

‎apps/server/src/mcp/toolkits/thread/tools.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,7 @@ const ThreadSearchTool = Tool.make("t3_thread_search", {
257257
const ScheduledTaskRunTool = Tool.make("run_scheduled_task_now", {
258258
...commandTool,
259259
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.",
261261
parameters: Schema.Struct({ taskId: ScheduledTaskId }),
262262
success: Schema.Struct({
263263
taskId: ScheduledTaskId,

‎apps/server/src/orchestration-v2/ThreadLaunchService.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -377,6 +377,7 @@ it.effect.each(
377377
projectThreads.find((candidate) => candidate.id === existing?.threadId) ??
378378
projectThreads[0];
379379
assert.isDefined(thread);
380+
assert.equal(result.threadId, thread!.id);
380381
const projection = yield* threads.getThreadProjection(thread!.id);
381382
const wire = yield* encodeThreadProjection(projection);
382383
assert.equal(wire.messages[0]?.text, task.prompt);
@@ -392,6 +393,45 @@ it.effect.each(
392393
},
393394
);
394395

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+
395435
it.effect("runs a thread-bound automation on the provider the thread uses now", () => {
396436
const harness = makeHarness({ adapters: [adapter, claudeAdapter] });
397437
const layerScheduledTasks = ScheduledTasks.layer.pipe(

‎apps/server/src/scheduledTasks/ScheduledTaskService.interval.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ it.effect.each([
9595
// Exercise completion rescheduling without starting any provider process.
9696
const completed = yield* service.runNow({ id: created.task.id });
9797
expect(completed.task.lastRunStatus).toBe("failed");
98+
expect(completed.threadId).toBeNull();
9899
expect(completed.task.runCount).toBe(1);
99100
expect(completed.task.nextRunAt).toBe(expected);
100101
expect((yield* service.list()).tasks[0]?.nextRunAt).toBe(expected);

‎apps/server/src/scheduledTasks/ScheduledTaskService.ts‎

Lines changed: 45 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -208,9 +208,13 @@ export class ScheduledTaskService extends Context.Service<
208208
) => Effect.Effect<ScheduledTaskDeleteResult, ScheduledTaskError>;
209209
/** Deletes only tasks that still target this thread, including their webhook deliveries. */
210210
readonly deleteForThread: (threadId: ThreadId) => Effect.Effect<void, ScheduledTaskError>;
211+
/** The dispatched thread, or null if dispatch failed; leaves the task's binding unchanged. */
211212
readonly runNow: (
212213
input: ScheduledTaskRunNowInput,
213-
) => Effect.Effect<ScheduledTaskRunNowResult, ScheduledTaskError>;
214+
) => Effect.Effect<
215+
ScheduledTaskRunNowResult & { readonly threadId: ThreadId | null },
216+
ScheduledTaskError
217+
>;
214218
readonly rotateWebhookToken: (
215219
input: ScheduledTaskRotateWebhookTokenInput,
216220
) => Effect.Effect<ScheduledTaskMutationResult, ScheduledTaskError>;
@@ -688,7 +692,7 @@ export const layer = Layer.effect(
688692
if (trigger !== "scheduled") {
689693
return yield* taskError("Schedule task is already running.", { taskId: task.id });
690694
}
691-
return task;
695+
return { task, threadId: null };
692696
}
693697

694698
return yield* Effect.gen(function* () {
@@ -708,7 +712,7 @@ export const layer = Layer.effect(
708712
if (trigger !== "scheduled") {
709713
return yield* taskError("Schedule task not found.", { taskId: task.id });
710714
}
711-
return task;
715+
return { task, threadId: null };
712716
}
713717
const parsedNextRunAt =
714718
active.nextRunAt === null ? Option.none() : DateTime.make(active.nextRunAt);
@@ -718,7 +722,7 @@ export const layer = Layer.effect(
718722
Option.isNone(parsedNextRunAt) ||
719723
DateTime.toEpochMillis(parsedNextRunAt.value) > DateTime.toEpochMillis(startedAt))
720724
) {
721-
return active;
725+
return { task: active, threadId: null };
722726
}
723727
// A queued delivery must not run a task that was paused, deleted and
724728
// recreated under the same id, or switched to another trigger while
@@ -753,45 +757,50 @@ export const layer = Layer.effect(
753757
const result =
754758
active.threadId === null
755759
? 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)),
773779
)
774780
: yield* Effect.exit(
775781
// The stored selection only seeds fresh threads. A bound run
776782
// 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))),
789797
);
790798

791799
const completedAt = yield* localNow;
792800
const runSucceeded = result._tag === "Success";
793801
const lastRunStatus = runSucceeded ? ("succeeded" as const) : ("failed" as const);
794802
const lastRunError = runSucceeded ? null : errorMessage(result.cause);
803+
const threadId = runSucceeded ? result.value : null;
795804
const current = yield* findTask(task.id);
796805
const scheduleSource = current ?? task;
797806
const completed: ScheduledTask = {
@@ -817,7 +826,7 @@ export const layer = Layer.effect(
817826
});
818827
yield* notifyChanged;
819828
}
820-
return completed;
829+
return { task: completed, threadId };
821830
}).pipe(
822831
Effect.onError((cause) => releaseStuckRun(task, errorMessage(cause))),
823832
Effect.ensuring(
@@ -1153,12 +1162,11 @@ export const layer = Layer.effect(
11531162
taskId: input.id,
11541163
});
11551164
}
1156-
const next = yield* runTask(task, "manual").pipe(
1165+
return yield* runTask(task, "manual").pipe(
11571166
Effect.mapError((cause) =>
11581167
taskError("Could not run schedule task.", { taskId: input.id, cause }),
11591168
),
11601169
);
1161-
return { task: next };
11621170
});
11631171

11641172
const rotateWebhookToken: ScheduledTaskService["Service"]["rotateWebhookToken"] = Effect.fn(
@@ -1605,7 +1613,7 @@ export const layer = Layer.effect(
16051613
Metrics.increment(Metrics.webhookRunsTotal, { outcome }),
16061614
]);
16071615
yield* runTask(task, "webhook", { deliveryId, prompt: rendered.prompt }).pipe(
1608-
Effect.flatMap((completed) =>
1616+
Effect.flatMap(({ task: completed }) =>
16091617
completed.lastRunStatus === "failed"
16101618
? runOutcome("failed").pipe(
16111619
Effect.andThen(markDeliveryFailed(deliveryId, "The run failed to start.")),

0 commit comments

Comments
 (0)