Skip to content

Commit 13baaa6

Browse files
feat: scheduled prompts no longer pile up, and the sidebar says what is automated
A timer task skips its tick while its previous prompt still waits or runs in the bound thread, instead of queueing another copy. The sidebar shows how many scheduled tasks are on and whether tasks or queues are paused; a click opens the task list. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 33cec46 commit 13baaa6

4 files changed

Lines changed: 180 additions & 1 deletion

File tree

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

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -406,3 +406,65 @@ it.effect("holds every due task while scheduled tasks are paused, and runs them
406406
);
407407
}).pipe(Effect.provide(SqlitePersistence.layerMemory)),
408408
);
409+
410+
it.effect("does not queue another prompt while the task's last one still waits in its thread", () =>
411+
Effect.gen(function* () {
412+
const sql = yield* SqlClient.SqlClient;
413+
const now = "2026-09-09T12:00:00.000Z";
414+
yield* insertRow(sql, { id: "bound", next: now, status: "never", enabled: 1 }, now);
415+
yield* sql`UPDATE scheduled_tasks SET thread_id = 'thread:test' WHERE task_id = 'bound'`;
416+
yield* TestClock.setTime(Date.parse(now) + 1_000);
417+
418+
const sent = yield* Ref.make(0);
419+
const delivered = yield* Deferred.make<void>();
420+
const serviceWith = (pendingMessageId: string | null) =>
421+
Layer.provideMerge(
422+
ScheduledTaskService.layer,
423+
Layer.mergeAll(
424+
Layer.mock(ThreadLaunchService.ThreadLaunchService)({}),
425+
Layer.mock(ThreadManagementService.ThreadManagementService)({
426+
getProjectThreadRecords: (() =>
427+
Effect.succeed({
428+
runs:
429+
pendingMessageId === null
430+
? []
431+
: [{ status: "queued", userMessageId: pendingMessageId }],
432+
})) as never,
433+
sendToThread: () =>
434+
Ref.update(sent, (n) => n + 1).pipe(
435+
Effect.andThen(Deferred.succeed(delivered, undefined)),
436+
Effect.andThen(Effect.die(new Error("test send failure"))),
437+
),
438+
}),
439+
Layer.mock(SecretRequests.SecretRequests)({}),
440+
NodeCrypto.layer,
441+
Scheduler.layer,
442+
),
443+
);
444+
445+
yield* Effect.scoped(
446+
Effect.gen(function* () {
447+
yield* Layer.build(serviceWith("scheduled-task-message:bound:1:scheduled"));
448+
yield* TestClock.adjust("6 seconds");
449+
assert.equal(yield* Ref.get(sent), 0);
450+
const rows = yield* sql<{ run_count: number; next_run_at: string | null }>`
451+
SELECT run_count, next_run_at FROM scheduled_tasks WHERE task_id = 'bound'
452+
`;
453+
// Skipped, not run: nothing counted, and the next tick is a full interval away.
454+
assert.equal(rows[0]?.run_count, 0);
455+
assert.isTrue((rows[0]?.next_run_at ?? "") > now);
456+
}),
457+
);
458+
459+
// Another task's prompt in the same thread does not hold this one back.
460+
yield* sql`UPDATE scheduled_tasks SET next_run_at = ${now} WHERE task_id = 'bound'`;
461+
yield* Effect.scoped(
462+
Effect.gen(function* () {
463+
yield* Layer.build(serviceWith("scheduled-task-message:other:1:scheduled"));
464+
yield* TestClock.adjust("6 seconds");
465+
yield* Deferred.await(delivered);
466+
assert.equal(yield* Ref.get(sent), 1);
467+
}),
468+
);
469+
}).pipe(Effect.provide(SqlitePersistence.layerMemory)),
470+
);

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

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,29 @@ function nextRunAt(
288288
}
289289
}
290290

291+
const SCHEDULED_MESSAGE_ID_PREFIX = "scheduled-task-message:";
292+
293+
/**
294+
* Whether a prompt this task sent earlier is still queued or running in its
295+
* thread. Scheduled prompts carry the task id in their message id.
296+
*/
297+
export function hasPendingScheduledPrompt(
298+
taskId: string,
299+
runs: ReadonlyArray<{ readonly status: string; readonly userMessageId?: string | null }>,
300+
): boolean {
301+
const prefix = `${SCHEDULED_MESSAGE_ID_PREFIX}${taskId}:`;
302+
return runs.some(
303+
(run) =>
304+
(run.status === "queued" ||
305+
run.status === "preparing" ||
306+
run.status === "starting" ||
307+
run.status === "running" ||
308+
run.status === "waiting") &&
309+
typeof run.userMessageId === "string" &&
310+
run.userMessageId.startsWith(prefix),
311+
);
312+
}
313+
291314
function errorMessage(error: unknown): string {
292315
if (Cause.isCause(error)) return Cause.pretty(error);
293316
if (error instanceof Error) return error.message;
@@ -796,6 +819,42 @@ export const layer = Layer.effect(
796819
if (reason !== null) return yield* new WebhookDeliverySkipped({ reason });
797820
}
798821

822+
// A timer keeps firing whether or not the thread kept up. Without
823+
// this, a thread busier than the task's interval collects one more
824+
// copy of the same prompt on every tick.
825+
if (trigger === "scheduled" && active.threadId !== null) {
826+
const pending = yield* Effect.exit(
827+
threadManagement.getProjectThreadRecords(
828+
{ projectId: active.projectId, threadId: ThreadId.make(active.threadId) },
829+
["runs"],
830+
),
831+
).pipe(
832+
Effect.map(
833+
(records) =>
834+
records._tag === "Success" &&
835+
hasPendingScheduledPrompt(active.id, records.value.runs),
836+
),
837+
);
838+
if (pending) {
839+
const next = nextRunAt(active, startedAt);
840+
yield* Effect.logInfo("Skipping schedule task run: its last prompt still waits", {
841+
taskId: active.id,
842+
rescheduledTo: next,
843+
});
844+
yield* sql`
845+
UPDATE scheduled_tasks
846+
SET next_run_at = ${next}
847+
WHERE task_id = ${active.id}
848+
`.pipe(
849+
Effect.mapError((cause) =>
850+
taskError("Could not reschedule schedule task.", { taskId: active.id, cause }),
851+
),
852+
);
853+
yield* notifyChanged;
854+
return { ...active, nextRunAt: next };
855+
}
856+
}
857+
799858
yield* markRunning(active.id, startedAtIso);
800859
yield* notifyChanged;
801860

@@ -806,7 +865,7 @@ export const layer = Layer.effect(
806865
? `${active.id}:${DateTime.toEpochMillis(startedAt)}:${trigger}`
807866
: `${active.id}:webhook:${webhook.deliveryId}`;
808867
const commandId = CommandId.make(`scheduled-task:${fireKey}`);
809-
const messageId = MessageId.make(`scheduled-task-message:${fireKey}`);
868+
const messageId = MessageId.make(`${SCHEDULED_MESSAGE_ID_PREFIX}${fireKey}`);
810869
// Dispatch from the fresh row so prompt/model/binding edits made
811870
// after the poll read are honoured. A webhook prompt was rendered
812871
// from the row when the request arrived.

‎apps/web/src/components/Sidebar.tsx‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,7 @@ import {
270270
type ProviderInstanceEntry,
271271
} from "../providerInstances";
272272
import { useThreadRunningTerminalIds } from "../state/terminalSessions";
273+
import { SidebarAutomationStatus } from "./SidebarAutomationStatus";
273274
import { subscribeNextWaitingThread } from "./threadNextWaitingBus";
274275
import { stackedThreadToast, toastManager } from "./ui/toast";
275276
import { Button, InlineButton } from "./ui/button";
@@ -5421,6 +5422,11 @@ export default function Sidebar() {
54215422
}
54225423
>
54235424
<SidebarGroup className="flex-1" role="presentation">
5425+
{isSearchingThreads
5426+
? null
5427+
: [...serverConfigs.keys()].map((id) => (
5428+
<SidebarAutomationStatus key={id} environmentId={id} />
5429+
))}
54245430
{!isSearchingThreads && waitingCounts.length > 0 ? (
54255431
<div
54265432
data-testid="sidebar-waiting-counts"
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import type { EnvironmentId } from "@t3tools/contracts";
2+
import { useNavigate } from "@tanstack/react-router";
3+
4+
import { useEnvironmentSettings } from "../hooks/useSettings";
5+
import { useEnvironmentQuery } from "../state/query";
6+
import { serverEnvironment } from "../state/server";
7+
8+
/**
9+
* One line in the sidebar saying what runs without the user: how many
10+
* scheduled tasks are on, and whether tasks or queues are paused. Shows
11+
* nothing when there is nothing to say. Clicking opens the task list.
12+
*/
13+
export function SidebarAutomationStatus({
14+
environmentId,
15+
}: {
16+
readonly environmentId: EnvironmentId;
17+
}) {
18+
const navigate = useNavigate();
19+
const tasks = useEnvironmentQuery(
20+
serverEnvironment.scheduledTasksLive({ environmentId, input: {} }),
21+
).data?.tasks;
22+
const tasksPaused = useEnvironmentSettings(
23+
environmentId,
24+
(settings) => settings.scheduledTasksPaused,
25+
);
26+
const queuesPaused = useEnvironmentSettings(
27+
environmentId,
28+
(settings) => settings.threadQueuesPaused,
29+
);
30+
const enabledCount = tasks?.filter((task) => task.enabled).length ?? 0;
31+
if (enabledCount === 0 && !tasksPaused && !queuesPaused) return null;
32+
const parts = [
33+
...(enabledCount > 0 || tasksPaused
34+
? [
35+
tasksPaused
36+
? `${enabledCount} ${enabledCount === 1 ? "automation" : "automations"} paused`
37+
: `${enabledCount} ${enabledCount === 1 ? "automation" : "automations"} on`,
38+
]
39+
: []),
40+
...(queuesPaused ? ["queues paused"] : []),
41+
];
42+
return (
43+
<button
44+
type="button"
45+
data-testid="sidebar-automation-status"
46+
onClick={() => void navigate({ to: "/settings/scheduled-tasks" })}
47+
className="mx-0.5 flex cursor-pointer items-center px-2 pb-1 text-left text-2xs text-muted-foreground hover:text-sidebar-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none focus-visible:ring-inset"
48+
>
49+
{parts.join(" · ")}
50+
</button>
51+
);
52+
}

0 commit comments

Comments
 (0)