Skip to content

Commit 272b949

Browse files
fix: address scheduled task PR review findings
- recompute workspace strategy when update_scheduled_task rebinds a task (unbinding no longer runs prompts in the shared root checkout) - scope MCP schedule_task idempotency keys by provider session via stableCommandId so reused clientRequestIds cannot collide across callers - capture dispatch defects/interruptions with Effect.exit and release stuck 'running' rows on completion-path failures - skip dispatch when the task row was deleted after markRunning - drop run-state columns from the saveTask conflict clause so settings saves cannot revert a concurrent run_count increment - subscribe to the change PubSub before taking the snapshot so no update falls in the gap - move runScheduledTaskNow off the config command lane so a slow run cannot stall settings mutations - web: keep at least one weekday selected, preserve modelSelection options when the model is unchanged, future-aware next-run labels, and disable the save button while submitting Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent 73c43f4 commit 272b949

4 files changed

Lines changed: 124 additions & 29 deletions

File tree

‎apps/server/src/mcp/OrchestratorMcpService.ts‎

Lines changed: 31 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,19 @@ function errorMessage(error: unknown): string {
160160
return error instanceof Error ? error.message : String(error);
161161
}
162162

163+
/**
164+
* Workspace strategy for a scheduled task created/updated over MCP: bound runs
165+
* post into the existing thread (the strategy is unused, keep root); unbound
166+
* runs launch a fresh worktree per run.
167+
*/
168+
function scheduledTaskWorkspaceStrategy(
169+
boundToThread: boolean,
170+
): ScheduledTask["workspaceStrategy"] {
171+
return boundToThread
172+
? { type: "root" }
173+
: { type: "worktree", baseRef: "main", startFromOrigin: true };
174+
}
175+
163176
function scheduledTaskSummary(task: ScheduledTask): OrchestratorMcpScheduledTask {
164177
return {
165178
scheduledTaskId: task.id,
@@ -775,20 +788,23 @@ const make = Effect.gen(function* () {
775788
schedule: input.schedule,
776789
projectId: parent.thread.projectId,
777790
threadId: bindToCurrentThread ? scope.threadId : null,
778-
// When bound to the calling thread the workspace strategy is unused
779-
// (the run is sent into the existing thread); otherwise each run
780-
// launches a fresh worktree off main.
781-
workspaceStrategy: bindToCurrentThread
782-
? { type: "root" }
783-
: { type: "worktree", baseRef: "main", startFromOrigin: true },
791+
workspaceStrategy: scheduledTaskWorkspaceStrategy(bindToCurrentThread),
784792
modelSelection: parent.thread.modelSelection,
785793
runtimeMode: parent.thread.runtimeMode,
786794
interactionMode: parent.thread.interactionMode,
787795
createdBy: "agent",
788796
creationSource: "mcp",
797+
// Scope the idempotency key by provider session so two callers
798+
// reusing the same clientRequestId cannot collide on one task row.
789799
...(input.clientRequestId === undefined
790800
? {}
791-
: { commandId: CommandId.make(input.clientRequestId) }),
801+
: {
802+
commandId: stableCommandId({
803+
scope,
804+
requestKey: input.clientRequestId,
805+
operation: "schedule-task",
806+
}),
807+
}),
792808
};
793809
const { task } = yield* scheduledTasks
794810
.upsert(upsertInput)
@@ -831,6 +847,13 @@ const make = Effect.gen(function* () {
831847
: input.bindToCurrentThread
832848
? scope.threadId
833849
: null;
850+
// Rebinding changes where runs execute, so the workspace strategy must
851+
// follow: unbinding a root-strategy task would otherwise run loose
852+
// prompts in the shared project checkout.
853+
const workspaceStrategy =
854+
input.bindToCurrentThread === undefined
855+
? existing.workspaceStrategy
856+
: scheduledTaskWorkspaceStrategy(input.bindToCurrentThread);
834857
const upsertInput: ScheduledTaskUpsertInput = {
835858
id: existing.id,
836859
title: input.title ?? existing.title,
@@ -839,7 +862,7 @@ const make = Effect.gen(function* () {
839862
schedule: input.schedule ?? existing.schedule,
840863
projectId: existing.projectId,
841864
threadId,
842-
workspaceStrategy: existing.workspaceStrategy,
865+
workspaceStrategy,
843866
modelSelection: existing.modelSelection,
844867
runtimeMode: existing.runtimeMode,
845868
interactionMode: existing.interactionMode,

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

Lines changed: 43 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,9 @@ export const layer = Layer.effect(
240240
return task;
241241
});
242242

243+
// Run-state columns (last_run_*, run_count) are intentionally absent from
244+
// the conflict clause: they are owned by the run transitions below, and a
245+
// concurrent settings save must not overwrite an in-flight increment.
243246
const saveTask = (task: ScheduledTask) =>
244247
sql`
245248
INSERT INTO scheduled_tasks (
@@ -300,11 +303,7 @@ export const layer = Layer.effect(
300303
interaction_mode = excluded.interaction_mode,
301304
creation_source = excluded.creation_source,
302305
updated_at = excluded.updated_at,
303-
next_run_at = excluded.next_run_at,
304-
last_run_at = excluded.last_run_at,
305-
last_run_status = excluded.last_run_status,
306-
last_run_error = excluded.last_run_error,
307-
run_count = excluded.run_count
306+
next_run_at = excluded.next_run_at
308307
`.pipe(
309308
Effect.mapError((cause) =>
310309
taskError("Could not save schedule task.", { taskId: task.id, cause }),
@@ -356,6 +355,22 @@ export const layer = Layer.effect(
356355
),
357356
);
358357

358+
// Best-effort escape hatch: if anything fails between markRunning and
359+
// markCompleted, flip the row back to 'failed' so runDueTasks does not
360+
// skip the task forever (it filters out 'running' rows).
361+
const releaseStuckRun = (id: ScheduledTaskId, message: string) =>
362+
sql`
363+
UPDATE scheduled_tasks
364+
SET last_run_status = 'failed',
365+
last_run_error = ${message}
366+
WHERE task_id = ${id} AND last_run_status = 'running'
367+
`.pipe(
368+
Effect.andThen(notifyChanged),
369+
Effect.catch((cause) =>
370+
Effect.logWarning("Could not release stuck schedule task run", { taskId: id, cause }),
371+
),
372+
);
373+
359374
const runTask = Effect.fn("ScheduledTaskService.runTask")(function* (
360375
task: ScheduledTask,
361376
trigger: "scheduled" | "manual",
@@ -379,14 +394,23 @@ export const layer = Layer.effect(
379394
yield* markRunning(task.id, startedAtIso);
380395
yield* notifyChanged;
381396

397+
// The in-memory snapshot may be stale: if the task was deleted since
398+
// it was loaded, markRunning updated nothing — do not dispatch a run
399+
// for a task that no longer exists.
400+
const preflight = yield* findTask(task.id);
401+
if (preflight === null) return task;
402+
382403
const fireKey = `${task.id}:${DateTime.toEpochMillis(startedAt)}:${trigger}`;
383404
const commandId = CommandId.make(`scheduled-task:${fireKey}`);
384405
const messageId = MessageId.make(`scheduled-task-message:${fireKey}`);
385406
const prompt = automationPrompt(task);
386407

408+
// Effect.exit (not Effect.result) so defects and interruptions in the
409+
// dispatch are also captured and recorded as a failed run instead of
410+
// aborting before markCompleted.
387411
const result =
388412
task.threadId === null
389-
? yield* Effect.result(
413+
? yield* Effect.exit(
390414
threadLaunch.launch({
391415
commandId,
392416
projectId: task.projectId,
@@ -404,7 +428,7 @@ export const layer = Layer.effect(
404428
creationSource: task.creationSource,
405429
}),
406430
)
407-
: yield* Effect.result(
431+
: yield* Effect.exit(
408432
threadManagement.sendToThread({
409433
projectId: task.projectId,
410434
commandId,
@@ -422,7 +446,7 @@ export const layer = Layer.effect(
422446
const completedAt = yield* localNow;
423447
const runSucceeded = result._tag === "Success";
424448
const lastRunStatus = runSucceeded ? ("succeeded" as const) : ("failed" as const);
425-
const lastRunError = runSucceeded ? null : errorMessage(result.failure);
449+
const lastRunError = runSucceeded ? null : errorMessage(result.cause);
426450
// Re-read the task so the next run is computed from the schedule as it
427451
// is *now* (the user may have edited or deleted it while we ran).
428452
const current = yield* findTask(task.id);
@@ -448,6 +472,7 @@ export const layer = Layer.effect(
448472
}
449473
return completed;
450474
}).pipe(
475+
Effect.onError((cause) => releaseStuckRun(task.id, errorMessage(cause))),
451476
Effect.ensuring(
452477
Ref.update(activeRuns, (active) => {
453478
const next = new Set(active);
@@ -539,9 +564,16 @@ export const layer = Layer.effect(
539564
);
540565

541566
const subscribeList: ScheduledTaskServiceShape["subscribeList"] = () =>
542-
Stream.concat(
543-
Stream.fromEffect(list()),
544-
Stream.fromPubSub(changesPubSub).pipe(Stream.mapEffect(() => list())),
567+
Stream.unwrap(
568+
Effect.gen(function* () {
569+
// Subscribe before taking the snapshot so a change landing between
570+
// the two is buffered by the subscription rather than dropped.
571+
const subscription = yield* PubSub.subscribe(changesPubSub);
572+
return Stream.concat(
573+
Stream.fromEffect(list()),
574+
Stream.fromSubscription(subscription).pipe(Stream.mapEffect(() => list())),
575+
);
576+
}),
545577
);
546578

547579
const upsert: ScheduledTaskServiceShape["upsert"] = (input) =>

‎apps/web/src/components/settings/ScheduledTasksSettings.tsx‎

Lines changed: 47 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,12 @@ interface DraftState {
7575
/** Not editable in the dialog, but preserved so editing an agent-created task keeps its modes. */
7676
readonly runtimeMode: RuntimeMode;
7777
readonly interactionMode: ProviderInteractionMode;
78+
/**
79+
* The task's original model selection. The picker only edits
80+
* `instanceId:model`; keeping the source object preserves provider options
81+
* (reasoning, temperature, …) when the model itself is left unchanged.
82+
*/
83+
readonly baseModelSelection: ModelSelection | null;
7884
}
7985

8086
/** JS day-of-week (0 = Sunday) rendered Monday-first, matching how people read a week. */
@@ -106,6 +112,7 @@ const EMPTY_DRAFT: DraftState = {
106112
modelKey: "",
107113
runtimeMode: "full-access",
108114
interactionMode: "default",
115+
baseModelSelection: null,
109116
};
110117

111118
/** Labelled field: a caption sitting above its control. */
@@ -179,10 +186,24 @@ export function scheduleLabel(schedule: ScheduledTaskSchedule): string {
179186
return `${days} at ${schedule.timeOfDay}`;
180187
}
181188

189+
/**
190+
* Human label for a run timestamp. `formatRelativeTime` only handles the
191+
* past, and `nextRunAt` is a future instant — render "in 5m" style labels
192+
* for upcoming runs instead of a misleading "just now".
193+
*/
182194
export function relativeLabel(value: string | null): string {
183195
if (!value) return "Not scheduled";
184-
const relative = formatRelativeTime(value);
185-
return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
196+
const diffMs = new Date(value).getTime() - Date.now();
197+
if (diffMs <= 0) {
198+
const relative = formatRelativeTime(value);
199+
return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
200+
}
201+
const minutes = Math.ceil(diffMs / 60_000);
202+
if (minutes < 2) return "in under a minute";
203+
if (minutes < 60) return `in ${minutes}m`;
204+
const hours = Math.round(minutes / 60);
205+
if (hours < 24) return `in ${hours}h`;
206+
return `in ${Math.round(hours / 24)}d`;
186207
}
187208

188209
function taskToDraft(task: ScheduledTask): DraftState {
@@ -214,6 +235,7 @@ function taskToDraft(task: ScheduledTask): DraftState {
214235
modelKey: modelKey(task.modelSelection),
215236
runtimeMode: task.runtimeMode,
216237
interactionMode: task.interactionMode,
238+
baseModelSelection: task.modelSelection,
217239
};
218240
}
219241

@@ -258,6 +280,7 @@ export function ScheduledTasksSettings() {
258280
);
259281
const [draft, setDraft] = useState<DraftState>(() => EMPTY_DRAFT);
260282
const [dialogOpen, setDialogOpen] = useState(false);
283+
const [saving, setSaving] = useState(false);
261284
const tasks = tasksQuery.data?.tasks ?? [];
262285
const selectedProjectTitle = projects.find((project) => project.id === draft.projectId)?.title;
263286

@@ -302,12 +325,20 @@ export function ScheduledTasksSettings() {
302325
};
303326

304327
const submit = useCallback(async () => {
305-
if (!environment) return;
328+
if (!environment || saving) return;
306329
const selection = splitModelKey(draft.modelKey || defaultModelKey);
307330
if (!draft.title.trim() || !draft.prompt.trim() || !draft.projectId || selection === null) {
308331
reportFailure("Schedule task is incomplete", "Add a title, prompt, project, and model.");
309332
return;
310333
}
334+
// Keep the original selection object (with provider options) when the
335+
// picker still points at the same instance+model.
336+
const modelSelection =
337+
draft.baseModelSelection !== null &&
338+
draft.baseModelSelection.instanceId === selection.instanceId &&
339+
draft.baseModelSelection.model === selection.model
340+
? draft.baseModelSelection
341+
: selection;
311342
const workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy =
312343
draft.workspaceMode === "root"
313344
? { type: "root" }
@@ -323,20 +354,22 @@ export function ScheduledTasksSettings() {
323354
projectId: draft.projectId as ProjectId,
324355
threadId: draft.threadId ? (draft.threadId as ThreadId) : null,
325356
workspaceStrategy,
326-
modelSelection: selection,
357+
modelSelection,
327358
runtimeMode: draft.runtimeMode,
328359
interactionMode: draft.interactionMode,
329360
creationSource: "web",
330361
};
362+
setSaving(true);
331363
const result = await upsertTask({ environmentId: environment.environmentId, input });
364+
setSaving(false);
332365
if (result._tag === "Failure") {
333366
if (!isAtomCommandInterrupted(result)) {
334367
reportFailure("Could not save schedule task", squashAtomCommandFailure(result));
335368
}
336369
return;
337370
}
338371
setDialogOpen(false);
339-
}, [defaultModelKey, draft, environment, upsertTask]);
372+
}, [defaultModelKey, draft, environment, saving, upsertTask]);
340373

341374
const handleDelete = useCallback(
342375
async (task: ScheduledTask) => {
@@ -644,8 +677,14 @@ export function ScheduledTasksSettings() {
644677
onClick={() =>
645678
setDraft((current) => {
646679
const weekdays = new Set(current.weekdays);
647-
if (weekdays.has(day)) weekdays.delete(day);
648-
else weekdays.add(day);
680+
if (weekdays.has(day)) {
681+
// Keep at least one day selected: an empty set
682+
// would silently persist as a daily schedule.
683+
if (weekdays.size === 1) return current;
684+
weekdays.delete(day);
685+
} else {
686+
weekdays.add(day);
687+
}
649688
return { ...current, weekdays };
650689
})
651690
}
@@ -690,7 +729,7 @@ export function ScheduledTasksSettings() {
690729

691730
<DialogFooter>
692731
<DialogClose render={<Button variant="outline" size="sm" />}>Cancel</DialogClose>
693-
<Button size="sm" onClick={() => void submit()}>
732+
<Button size="sm" disabled={saving} onClick={() => void submit()}>
694733
{draft.editingId ? "Save task" : "Create task"}
695734
</Button>
696735
</DialogFooter>

‎packages/client-runtime/src/state/server.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -207,11 +207,12 @@ export function createServerEnvironmentAtoms<R, E>(
207207
scheduler: configScheduler,
208208
concurrency: configConcurrency,
209209
}),
210+
// Deliberately not on the config lane: run-now blocks until the run is
211+
// dispatched, and a slow run must not stall settings/keybinding/provider
212+
// mutations (or other scheduled-task edits) queued behind it.
210213
runScheduledTaskNow: createEnvironmentRpcCommand(runtime, {
211214
label: "environment-data:server:scheduled-task:run-now",
212215
tag: WS_METHODS.scheduledTasksRunNow,
213-
scheduler: configScheduler,
214-
concurrency: configConcurrency,
215216
}),
216217
};
217218
}

0 commit comments

Comments
 (0)