feat: scheduled tasks (automations) (#3638)
Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
4e28472e91
commit
8d7bfec473
25 files changed
+2767
-52
No files matched your search
@@ -16,10 +16,17 @@ import {
|
||||
type OrchestratorMcpDelegateTaskInput,
|
||||
type OrchestratorMcpDelegateTaskResult,
|
||||
type OrchestratorMcpInteractionMode,
|
||||
type OrchestratorMcpDeleteScheduledTaskInput,
|
||||
type OrchestratorMcpDeleteScheduledTaskResult,
|
||||
type OrchestratorMcpListScheduledTasksResult,
|
||||
type OrchestratorMcpRuntimeMode,
|
||||
type OrchestratorMcpScheduledTask,
|
||||
type OrchestratorMcpScheduleTaskInput,
|
||||
type OrchestratorMcpScheduleTaskResult,
|
||||
type OrchestratorMcpTarget,
|
||||
type OrchestratorMcpTaskCancelInput,
|
||||
type OrchestratorMcpTaskCancelResult,
|
||||
type OrchestratorMcpUpdateScheduledTaskInput,
|
||||
type OrchestratorMcpThreadDetail,
|
||||
type OrchestratorMcpThreadInterruptInput,
|
||||
type OrchestratorMcpThreadInterruptResult,
|
||||
@@ -37,6 +44,8 @@ import {
|
||||
type ProviderInteractionMode,
|
||||
ProviderInstanceId,
|
||||
type RuntimeMode,
|
||||
type ScheduledTask,
|
||||
type ScheduledTaskUpsertInput,
|
||||
type ServerProvider,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -59,6 +68,7 @@ import {
|
||||
ThreadManagementService,
|
||||
} from "../orchestration-v2/ThreadManagementService.ts";
|
||||
import { ProviderRegistry } from "../provider/Services/ProviderRegistry.ts";
|
||||
import { ScheduledTaskService } from "../scheduledTasks/ScheduledTaskService.ts";
|
||||
import type { McpInvocationScope } from "./McpInvocationContext.ts";
|
||||
|
||||
const DEFAULT_WAIT_TIMEOUT_MS = 10 * 60 * 1_000;
|
||||
@@ -98,6 +108,21 @@ export interface OrchestratorMcpServiceShape {
|
||||
scope: McpInvocationScope,
|
||||
input: OrchestratorMcpCreateThreadsInput,
|
||||
) => Effect.Effect<OrchestratorMcpCreateThreadsResult, OrchestratorMcpFailure>;
|
||||
readonly scheduleTask: (
|
||||
scope: McpInvocationScope,
|
||||
input: OrchestratorMcpScheduleTaskInput,
|
||||
) => Effect.Effect<OrchestratorMcpScheduleTaskResult, OrchestratorMcpFailure>;
|
||||
readonly listScheduledTasks: (
|
||||
scope: McpInvocationScope,
|
||||
) => Effect.Effect<OrchestratorMcpListScheduledTasksResult, OrchestratorMcpFailure>;
|
||||
readonly updateScheduledTask: (
|
||||
scope: McpInvocationScope,
|
||||
input: OrchestratorMcpUpdateScheduledTaskInput,
|
||||
) => Effect.Effect<OrchestratorMcpScheduleTaskResult, OrchestratorMcpFailure>;
|
||||
readonly deleteScheduledTask: (
|
||||
scope: McpInvocationScope,
|
||||
input: OrchestratorMcpDeleteScheduledTaskInput,
|
||||
) => Effect.Effect<OrchestratorMcpDeleteScheduledTaskResult, OrchestratorMcpFailure>;
|
||||
readonly listThreads: (
|
||||
scope: McpInvocationScope,
|
||||
input: OrchestratorMcpThreadListInput,
|
||||
@@ -135,6 +160,33 @@ function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
/**
|
||||
* Workspace strategy for a scheduled task created/updated over MCP: bound runs
|
||||
* post into the existing thread (the strategy is unused, keep root); unbound
|
||||
* runs launch a fresh worktree per run.
|
||||
*/
|
||||
function scheduledTaskWorkspaceStrategy(
|
||||
boundToThread: boolean,
|
||||
): ScheduledTask["workspaceStrategy"] {
|
||||
return boundToThread
|
||||
? { type: "root" }
|
||||
: { type: "worktree", baseRef: "main", startFromOrigin: true };
|
||||
}
|
||||
|
||||
function scheduledTaskSummary(task: ScheduledTask): OrchestratorMcpScheduledTask {
|
||||
return {
|
||||
scheduledTaskId: task.id,
|
||||
title: task.title,
|
||||
prompt: task.prompt,
|
||||
enabled: task.enabled,
|
||||
projectId: task.projectId,
|
||||
boundThreadId: task.threadId,
|
||||
schedule: task.schedule,
|
||||
nextRunAt: task.nextRunAt,
|
||||
lastRunStatus: task.lastRunStatus,
|
||||
};
|
||||
}
|
||||
|
||||
function providerConstraints(
|
||||
provider: ServerProvider | undefined,
|
||||
supportsOrchestrationV2: boolean,
|
||||
@@ -491,6 +543,7 @@ const make = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const threadManagement = yield* ThreadManagementService;
|
||||
const providerRegistry = yield* ProviderRegistry;
|
||||
const scheduledTasks = yield* ScheduledTaskService;
|
||||
|
||||
const requireCapability = (scope: McpInvocationScope) =>
|
||||
scope.capabilities.has("orchestration")
|
||||
@@ -695,7 +748,153 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
}).pipe(Effect.timeoutOption(Duration.millis(timeoutMs)));
|
||||
|
||||
// Load a single scheduled task and enforce that it belongs to the calling
|
||||
// thread's project, so agents can only read/mutate tasks in their own scope.
|
||||
const loadScopedScheduledTask = (
|
||||
projectId: ScheduledTask["projectId"],
|
||||
scheduledTaskId: ScheduledTask["id"],
|
||||
): Effect.Effect<ScheduledTask, OrchestratorMcpFailure> =>
|
||||
Effect.gen(function* () {
|
||||
const { tasks } = yield* scheduledTasks
|
||||
.list()
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
failure("orchestration_error", `Could not load scheduled task: ${error.message}`),
|
||||
),
|
||||
);
|
||||
const task = tasks.find((candidate) => candidate.id === scheduledTaskId);
|
||||
if (task === undefined || task.projectId !== projectId) {
|
||||
return yield* failure(
|
||||
"task_not_found",
|
||||
`Scheduled task ${scheduledTaskId} was not found in the calling project.`,
|
||||
);
|
||||
}
|
||||
return task;
|
||||
});
|
||||
|
||||
return OrchestratorMcpService.of({
|
||||
scheduleTask: (scope, input) =>
|
||||
Effect.gen(function* () {
|
||||
yield* requireCapability(scope);
|
||||
const parent = yield* loadProjection(scope.threadId);
|
||||
const bindToCurrentThread = input.bindToCurrentThread ?? true;
|
||||
const derivedTitle = input.prompt.split("\n")[0]?.trim() ?? "";
|
||||
const title =
|
||||
input.title ?? (derivedTitle.length > 0 ? derivedTitle.slice(0, 80) : "Scheduled task");
|
||||
const upsertInput: ScheduledTaskUpsertInput = {
|
||||
title,
|
||||
prompt: input.prompt,
|
||||
enabled: input.enabled ?? true,
|
||||
schedule: input.schedule,
|
||||
projectId: parent.thread.projectId,
|
||||
threadId: bindToCurrentThread ? scope.threadId : null,
|
||||
workspaceStrategy: scheduledTaskWorkspaceStrategy(bindToCurrentThread),
|
||||
modelSelection: parent.thread.modelSelection,
|
||||
runtimeMode: parent.thread.runtimeMode,
|
||||
interactionMode: parent.thread.interactionMode,
|
||||
createdBy: "agent",
|
||||
creationSource: "mcp",
|
||||
// Scope the idempotency key by provider session so two callers
|
||||
// reusing the same clientRequestId cannot collide on one task row.
|
||||
...(input.clientRequestId === undefined
|
||||
? {}
|
||||
: {
|
||||
commandId: stableCommandId({
|
||||
scope,
|
||||
requestKey: input.clientRequestId,
|
||||
operation: "schedule-task",
|
||||
}),
|
||||
}),
|
||||
};
|
||||
const { task } = yield* scheduledTasks
|
||||
.upsert(upsertInput)
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
failure("orchestration_error", `Could not schedule task: ${error.message}`),
|
||||
),
|
||||
);
|
||||
return scheduledTaskSummary(task);
|
||||
}),
|
||||
listScheduledTasks: (scope) =>
|
||||
Effect.gen(function* () {
|
||||
yield* requireCapability(scope);
|
||||
const parent = yield* loadProjection(scope.threadId);
|
||||
const { tasks } = yield* scheduledTasks
|
||||
.list()
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
failure("orchestration_error", `Could not list scheduled tasks: ${error.message}`),
|
||||
),
|
||||
);
|
||||
// Only expose tasks belonging to the calling thread's project.
|
||||
return {
|
||||
tasks: tasks
|
||||
.filter((task) => task.projectId === parent.thread.projectId)
|
||||
.map(scheduledTaskSummary),
|
||||
};
|
||||
}),
|
||||
updateScheduledTask: (scope, input) =>
|
||||
Effect.gen(function* () {
|
||||
yield* requireCapability(scope);
|
||||
const parent = yield* loadProjection(scope.threadId);
|
||||
const existing = yield* loadScopedScheduledTask(
|
||||
parent.thread.projectId,
|
||||
input.scheduledTaskId,
|
||||
);
|
||||
const threadId =
|
||||
input.bindToCurrentThread === undefined
|
||||
? existing.threadId
|
||||
: input.bindToCurrentThread
|
||||
? scope.threadId
|
||||
: null;
|
||||
// Rebinding changes where runs execute, so the workspace strategy must
|
||||
// follow: unbinding a root-strategy task would otherwise run loose
|
||||
// prompts in the shared project checkout.
|
||||
const workspaceStrategy =
|
||||
input.bindToCurrentThread === undefined
|
||||
? existing.workspaceStrategy
|
||||
: scheduledTaskWorkspaceStrategy(input.bindToCurrentThread);
|
||||
const upsertInput: ScheduledTaskUpsertInput = {
|
||||
id: existing.id,
|
||||
title: input.title ?? existing.title,
|
||||
prompt: input.prompt ?? existing.prompt,
|
||||
enabled: input.enabled ?? existing.enabled,
|
||||
schedule: input.schedule ?? existing.schedule,
|
||||
projectId: existing.projectId,
|
||||
threadId,
|
||||
workspaceStrategy,
|
||||
modelSelection: existing.modelSelection,
|
||||
runtimeMode: existing.runtimeMode,
|
||||
interactionMode: existing.interactionMode,
|
||||
createdBy: existing.createdBy,
|
||||
creationSource: existing.creationSource,
|
||||
};
|
||||
const { task } = yield* scheduledTasks
|
||||
.upsert(upsertInput)
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
failure("orchestration_error", `Could not update scheduled task: ${error.message}`),
|
||||
),
|
||||
);
|
||||
return scheduledTaskSummary(task);
|
||||
}),
|
||||
deleteScheduledTask: (scope, input) =>
|
||||
Effect.gen(function* () {
|
||||
yield* requireCapability(scope);
|
||||
const parent = yield* loadProjection(scope.threadId);
|
||||
const existing = yield* loadScopedScheduledTask(
|
||||
parent.thread.projectId,
|
||||
input.scheduledTaskId,
|
||||
);
|
||||
yield* scheduledTasks
|
||||
.delete({ id: existing.id })
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
failure("orchestration_error", `Could not delete scheduled task: ${error.message}`),
|
||||
),
|
||||
);
|
||||
return { scheduledTaskId: existing.id, deleted: true };
|
||||
}),
|
||||
capabilities: (scope) =>
|
||||
Effect.gen(function* () {
|
||||
yield* requireCapability(scope);
|
||||
@@ -733,6 +932,7 @@ const make = Effect.gen(function* () {
|
||||
batchThreadCreation: true,
|
||||
threadManagement: true,
|
||||
incrementalThreadRead: true,
|
||||
scheduledTasks: true,
|
||||
maxBatchThreads: 20,
|
||||
},
|
||||
};
|
||||
@@ -1190,5 +1390,5 @@ const make = Effect.gen(function* () {
|
||||
export const layer: Layer.Layer<
|
||||
OrchestratorMcpService,
|
||||
never,
|
||||
Crypto.Crypto | ThreadManagementService | ProviderRegistry
|
||||
Crypto.Crypto | ThreadManagementService | ProviderRegistry | ScheduledTaskService
|
||||
> = Layer.effect(OrchestratorMcpService, make);
|
||||
@@ -3,6 +3,7 @@ import { describe, expect, it } from "@effect/vitest";
|
||||
import {
|
||||
CommandId,
|
||||
EnvironmentId,
|
||||
IsoDateTime,
|
||||
MessageId,
|
||||
type ModelSelection,
|
||||
type OrchestrationV2ProviderCapabilities,
|
||||
@@ -23,6 +24,9 @@ import {
|
||||
ProviderInstanceId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
type ScheduledTask,
|
||||
ScheduledTaskId,
|
||||
type ScheduledTaskUpsertInput,
|
||||
type ServerProvider,
|
||||
ThreadId,
|
||||
TurnItemId,
|
||||
@@ -50,6 +54,7 @@ import { makeLayer as makeProviderAdapterRegistryLayer } from "../orchestration-
|
||||
import { checkpointWorkspace } from "../orchestration-v2/testkit/ReplayFixtureWorkspace.ts";
|
||||
import { makeOrchestratorV2ReplayLayerWithRegistry } from "../orchestration-v2/testkit/ProviderReplayHarness.ts";
|
||||
import { makeProviderRegistryLayer } from "../provider/testUtils/providerRegistryMock.ts";
|
||||
import { ScheduledTaskService } from "../scheduledTasks/ScheduledTaskService.ts";
|
||||
import * as McpHttpServer from "./McpHttpServer.ts";
|
||||
import * as McpInvocationContext from "./McpInvocationContext.ts";
|
||||
|
||||
@@ -344,6 +349,33 @@ const client = McpSchema.McpServerClient.of({
|
||||
getClient: Effect.die("unused"),
|
||||
});
|
||||
|
||||
/** Build a persisted-looking ScheduledTask from an upsert input for the in-memory stub. */
|
||||
function scheduledTaskFromUpsert(input: ScheduledTaskUpsertInput): ScheduledTask {
|
||||
const timestamp = IsoDateTime.make("2026-07-01T09:00:00.000Z");
|
||||
return {
|
||||
id: input.id ?? ScheduledTaskId.make(`scheduled-task:${input.commandId ?? "stub"}`),
|
||||
title: input.title,
|
||||
prompt: input.prompt,
|
||||
enabled: input.enabled,
|
||||
schedule: input.schedule,
|
||||
projectId: input.projectId,
|
||||
threadId: input.threadId ?? null,
|
||||
workspaceStrategy: input.workspaceStrategy,
|
||||
modelSelection: input.modelSelection,
|
||||
runtimeMode: input.runtimeMode,
|
||||
interactionMode: input.interactionMode,
|
||||
createdBy: input.createdBy ?? "user",
|
||||
creationSource: input.creationSource ?? "web",
|
||||
createdAt: timestamp,
|
||||
updatedAt: timestamp,
|
||||
nextRunAt: null,
|
||||
lastRunAt: null,
|
||||
lastRunStatus: "never",
|
||||
lastRunError: null,
|
||||
runCount: 0,
|
||||
};
|
||||
}
|
||||
|
||||
describe("orchestrator MCP toolkit", () => {
|
||||
it.live(
|
||||
"delegates cross-provider tasks, polls and cancels children, and creates ordinary threads",
|
||||
@@ -410,10 +442,37 @@ describe("orchestrator MCP toolkit", () => {
|
||||
model: "opencode/test",
|
||||
}),
|
||||
]);
|
||||
// In-memory ScheduledTaskService stub so the schedule/list/update/
|
||||
// delete tools can be exercised without SQL/launch wiring.
|
||||
const scheduledStore = yield* Ref.make<ReadonlyArray<ScheduledTask>>([]);
|
||||
const scheduledTaskStubLayer = Layer.succeed(
|
||||
ScheduledTaskService,
|
||||
ScheduledTaskService.of({
|
||||
list: () => Ref.get(scheduledStore).pipe(Effect.map((tasks) => ({ tasks }))),
|
||||
subscribeList: () => Stream.empty,
|
||||
upsert: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const task = scheduledTaskFromUpsert(input);
|
||||
yield* Ref.update(scheduledStore, (all) => [
|
||||
...all.filter((candidate) => candidate.id !== task.id),
|
||||
task,
|
||||
]);
|
||||
return { task };
|
||||
}),
|
||||
setEnabled: () =>
|
||||
Effect.die("ScheduledTaskService.setEnabled is unused in this test"),
|
||||
delete: (input) =>
|
||||
Ref.update(scheduledStore, (all) =>
|
||||
all.filter((candidate) => candidate.id !== input.id),
|
||||
).pipe(Effect.as({ id: input.id })),
|
||||
runNow: () => Effect.die("ScheduledTaskService.runNow is unused in this test"),
|
||||
}),
|
||||
);
|
||||
const testLayer = McpHttpServer.OrchestratorToolkitRegistrationLive.pipe(
|
||||
Layer.provideMerge(McpServer.McpServer.layer),
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provide(providerRegistryLayer),
|
||||
Layer.provide(scheduledTaskStubLayer),
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
@@ -524,6 +583,63 @@ describe("orchestrator MCP toolkit", () => {
|
||||
]),
|
||||
});
|
||||
|
||||
const scheduleTool = server.tools.find(({ tool }) => tool.name === "schedule_task");
|
||||
expect(scheduleTool?.tool.annotations?.destructiveHint).toBe(true);
|
||||
const scheduleCall = yield* invoke("schedule_task", {
|
||||
prompt: "wake up in this thread and say hello",
|
||||
schedule: { type: "interval", everyMs: 60_000 },
|
||||
clientRequestId: "schedule-hello-1",
|
||||
});
|
||||
expect(scheduleCall.isError).toBe(false);
|
||||
expect(scheduleCall.structuredContent).toMatchObject({
|
||||
// Defaults to binding the calling thread.
|
||||
boundThreadId: parentThreadId,
|
||||
projectId,
|
||||
enabled: true,
|
||||
schedule: { type: "interval", everyMs: 60_000 },
|
||||
// Title is derived from the prompt when omitted.
|
||||
title: "wake up in this thread and say hello",
|
||||
});
|
||||
const scheduledTaskId = (scheduleCall.structuredContent as { scheduledTaskId: string })
|
||||
.scheduledTaskId;
|
||||
const storedAfterCreate = yield* Ref.get(scheduledStore);
|
||||
expect(storedAfterCreate).toHaveLength(1);
|
||||
expect(storedAfterCreate[0]).toMatchObject({
|
||||
threadId: parentThreadId,
|
||||
projectId,
|
||||
createdBy: "agent",
|
||||
creationSource: "mcp",
|
||||
// Inherits the parent thread's model selection.
|
||||
modelSelection: codexSelection,
|
||||
});
|
||||
|
||||
// list_scheduled_tasks returns the task scoped to this project.
|
||||
const scheduledListCall = yield* invoke("list_scheduled_tasks", {});
|
||||
expect(scheduledListCall.isError).toBe(false);
|
||||
expect(scheduledListCall.structuredContent).toMatchObject({
|
||||
tasks: [{ scheduledTaskId, boundThreadId: parentThreadId }],
|
||||
});
|
||||
|
||||
// update_scheduled_task pauses without deleting.
|
||||
const scheduledUpdateCall = yield* invoke("update_scheduled_task", {
|
||||
scheduledTaskId,
|
||||
enabled: false,
|
||||
});
|
||||
expect(scheduledUpdateCall.isError).toBe(false);
|
||||
expect(scheduledUpdateCall.structuredContent).toMatchObject({
|
||||
scheduledTaskId,
|
||||
enabled: false,
|
||||
});
|
||||
|
||||
// delete_scheduled_task removes it entirely.
|
||||
const scheduledDeleteCall = yield* invoke("delete_scheduled_task", { scheduledTaskId });
|
||||
expect(scheduledDeleteCall.isError).toBe(false);
|
||||
expect(scheduledDeleteCall.structuredContent).toMatchObject({
|
||||
scheduledTaskId,
|
||||
deleted: true,
|
||||
});
|
||||
expect(yield* Ref.get(scheduledStore)).toHaveLength(0);
|
||||
|
||||
const delegatedCall = yield* invoke("delegate_task", {
|
||||
task: delegatedPrompt,
|
||||
target: {
|
||||
|
||||
@@ -29,6 +29,30 @@ const handlers = {
|
||||
const service = yield* OrchestratorMcpService;
|
||||
return yield* service.cancelTask(scope, input);
|
||||
}),
|
||||
schedule_task: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const scope = yield* McpInvocationContext;
|
||||
const service = yield* OrchestratorMcpService;
|
||||
return yield* service.scheduleTask(scope, input);
|
||||
}),
|
||||
list_scheduled_tasks: () =>
|
||||
Effect.gen(function* () {
|
||||
const scope = yield* McpInvocationContext;
|
||||
const service = yield* OrchestratorMcpService;
|
||||
return yield* service.listScheduledTasks(scope);
|
||||
}),
|
||||
update_scheduled_task: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const scope = yield* McpInvocationContext;
|
||||
const service = yield* OrchestratorMcpService;
|
||||
return yield* service.updateScheduledTask(scope, input);
|
||||
}),
|
||||
delete_scheduled_task: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const scope = yield* McpInvocationContext;
|
||||
const service = yield* OrchestratorMcpService;
|
||||
return yield* service.deleteScheduledTask(scope, input);
|
||||
}),
|
||||
create_threads: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const scope = yield* McpInvocationContext;
|
||||
|
||||
@@ -5,9 +5,15 @@ import {
|
||||
OrchestratorMcpCreateThreadsResult,
|
||||
OrchestratorMcpDelegateTaskInput,
|
||||
OrchestratorMcpDelegateTaskResult,
|
||||
OrchestratorMcpDeleteScheduledTaskInput,
|
||||
OrchestratorMcpDeleteScheduledTaskResult,
|
||||
OrchestratorMcpFailure,
|
||||
OrchestratorMcpListScheduledTasksResult,
|
||||
OrchestratorMcpScheduleTaskInput,
|
||||
OrchestratorMcpScheduleTaskResult,
|
||||
OrchestratorMcpTaskCancelInput,
|
||||
OrchestratorMcpTaskCancelResult,
|
||||
OrchestratorMcpUpdateScheduledTaskInput,
|
||||
OrchestratorMcpTaskStatusInput,
|
||||
OrchestratorMcpThreadInterruptInput,
|
||||
OrchestratorMcpThreadInterruptResult,
|
||||
@@ -80,6 +86,56 @@ export const TaskCancelTool = Tool.make("task_cancel", {
|
||||
.annotate(Tool.Title, "Cancel delegated task")
|
||||
.annotate(Tool.Destructive, true);
|
||||
|
||||
export const ScheduleTaskTool = Tool.make("schedule_task", {
|
||||
description:
|
||||
"Create a recurring scheduled task that automatically runs a prompt on a schedule. Use this to set up autonomous recurring work — the app's scheduler fires it even when no turn is active. By default (bindToCurrentThread=true) each run posts into THIS thread, which is how you 'wake up' and continue here on an interval or at a fixed time; set bindToCurrentThread=false to launch a fresh thread each run instead. Provider, model, and runtime settings inherit from the calling thread. Schedule is either {type:'interval', everyMs} (e.g. everyMs=60000 for every minute) or {type:'fixed_time', timeOfDay:'HH:MM', weekdays?:[0-6] where 0=Sunday}.",
|
||||
parameters: OrchestratorMcpScheduleTaskInput,
|
||||
success: OrchestratorMcpScheduleTaskResult,
|
||||
failure: OrchestratorMcpFailure,
|
||||
failureMode: "return",
|
||||
dependencies,
|
||||
})
|
||||
.annotate(Tool.Title, "Schedule a recurring task")
|
||||
.annotate(Tool.Destructive, true)
|
||||
.annotate(Tool.OpenWorld, true);
|
||||
|
||||
export const ListScheduledTasksTool = Tool.make("list_scheduled_tasks", {
|
||||
description:
|
||||
"List the recurring scheduled tasks in the calling thread's project, including their id, schedule, prompt, enabled state, bound thread, next run time, and last run status. Use the returned scheduledTaskId with update_scheduled_task or delete_scheduled_task.",
|
||||
success: OrchestratorMcpListScheduledTasksResult,
|
||||
failure: OrchestratorMcpFailure,
|
||||
failureMode: "return",
|
||||
dependencies,
|
||||
})
|
||||
.annotate(Tool.Title, "List scheduled tasks")
|
||||
.annotate(Tool.Readonly, true)
|
||||
.annotate(Tool.Destructive, false)
|
||||
.annotate(Tool.Idempotent, true);
|
||||
|
||||
export const UpdateScheduledTaskTool = Tool.make("update_scheduled_task", {
|
||||
description:
|
||||
"Update an existing scheduled task by scheduledTaskId (from list_scheduled_tasks). Only the provided fields change; omit a field to leave it as-is. Use enabled=false to pause a task without deleting it. Set bindToCurrentThread to move the task between posting into this thread and launching a fresh thread per run.",
|
||||
parameters: OrchestratorMcpUpdateScheduledTaskInput,
|
||||
success: OrchestratorMcpScheduleTaskResult,
|
||||
failure: OrchestratorMcpFailure,
|
||||
failureMode: "return",
|
||||
dependencies,
|
||||
})
|
||||
.annotate(Tool.Title, "Update a scheduled task")
|
||||
.annotate(Tool.Destructive, true);
|
||||
|
||||
export const DeleteScheduledTaskTool = Tool.make("delete_scheduled_task", {
|
||||
description:
|
||||
"Permanently delete a scheduled task by scheduledTaskId (from list_scheduled_tasks). The task stops running immediately. To keep it but stop runs, use update_scheduled_task with enabled=false instead.",
|
||||
parameters: OrchestratorMcpDeleteScheduledTaskInput,
|
||||
success: OrchestratorMcpDeleteScheduledTaskResult,
|
||||
failure: OrchestratorMcpFailure,
|
||||
failureMode: "return",
|
||||
dependencies,
|
||||
})
|
||||
.annotate(Tool.Title, "Delete a scheduled task")
|
||||
.annotate(Tool.Destructive, true);
|
||||
|
||||
export const CreateThreadsTool = Tool.make("create_threads", {
|
||||
description:
|
||||
"Create one or more ordinary top-level T3 V2 threads. Each entry may have its own prompt, title, provider instance or driver, model, runtime mode, and interaction mode. Omitted provider/model/settings inherit from the calling thread; entries without prompts create empty threads.",
|
||||
@@ -178,6 +234,10 @@ export const OrchestratorToolkit = Toolkit.make(
|
||||
DelegateTaskTool,
|
||||
TaskStatusTool,
|
||||
TaskCancelTool,
|
||||
ScheduleTaskTool,
|
||||
ListScheduledTasksTool,
|
||||
UpdateScheduledTaskTool,
|
||||
DeleteScheduledTaskTool,
|
||||
CreateThreadsTool,
|
||||
ThreadStartTool,
|
||||
ThreadListTool,
|
||||
|
||||
@@ -39,6 +39,7 @@ import { layer as threadLaunchServiceLayer } from "./ThreadLaunchService.ts";
|
||||
import { layer as threadLifecycleServiceLayer } from "./ThreadLifecycleService.ts";
|
||||
import { layer as threadForkServiceLayer } from "./ThreadForkService.ts";
|
||||
import { layer as turnItemPositionStoreLayer } from "./TurnItemPositionStore.ts";
|
||||
import { layer as scheduledTaskServiceLayer } from "../scheduledTasks/ScheduledTaskService.ts";
|
||||
|
||||
export const ProjectServiceLayerLive = projectServiceLayer.pipe(
|
||||
Layer.provide(Layer.merge(ProjectionProjectRepositoryLive, OrchestrationLayerLive)),
|
||||
@@ -224,6 +225,9 @@ const threadLaunchProvided = threadLaunchServiceLayer.pipe(
|
||||
const threadLifecycleProvided = threadLifecycleServiceLayer.pipe(
|
||||
Layer.provide(threadManagementProvided),
|
||||
);
|
||||
const scheduledTaskProvided = scheduledTaskServiceLayer.pipe(
|
||||
Layer.provide(Layer.mergeAll(threadLaunchProvided, threadManagementProvided)),
|
||||
);
|
||||
|
||||
export const OrchestrationV2LayerLive = Layer.mergeAll(
|
||||
orchestratorProvided,
|
||||
@@ -240,4 +244,5 @@ export const OrchestrationV2ProductionLayerLive = Layer.mergeAll(
|
||||
ProjectServiceLayerLive,
|
||||
threadLaunchProvided,
|
||||
threadLifecycleProvided,
|
||||
scheduledTaskProvided,
|
||||
);
|
||||
@@ -53,7 +53,6 @@ import Migration0037 from "./Migrations/037_ProjectionTurnsKeysetIndex.ts";
|
||||
import Migration0038 from "./Migrations/038_ProjectionThreadsPinOrderKey.ts";
|
||||
import Migration0039 from "./Migrations/039_ProjectionProjectsDefaultThreadEnvMode.ts";
|
||||
import Migration0040 from "./Migrations/040_ProjectionProjectFaviconPath.ts";
|
||||
import Migration037V2 from "./Migrations/037_OrchestrationV2ThreadLaunchWorkflows.ts";
|
||||
import Migration033V2 from "./Migrations/033_OrchestrationV2.ts";
|
||||
import Migration034V2 from "./Migrations/034_OrchestrationV2Subagents.ts";
|
||||
import Migration035V2 from "./Migrations/035_OrchestrationV2Foundation.ts";
|
||||
@@ -61,6 +60,7 @@ import Migration036V2 from "./Migrations/036_OrchestrationV2ProviderSessionBindi
|
||||
import Migration037V2 from "./Migrations/037_OrchestrationV2ThreadLaunchWorkflows.ts";
|
||||
import Migration038V2 from "./Migrations/038_ApplicationEventSource.ts";
|
||||
import Migration039V2 from "./Migrations/039_OrchestrationV2EffectCancellation.ts";
|
||||
import Migration040V2 from "./Migrations/040_ScheduledTasks.ts";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -110,7 +110,6 @@ export const migrationEntries = [
|
||||
[35, "ProjectionThreadTitleRegeneration", Migration0035],
|
||||
[36, "ProjectionThreadsPinned", Migration0036],
|
||||
[37, "ProjectionTurnsKeysetIndex", Migration0037],
|
||||
<<<<<<< HEAD
|
||||
[38, "ProjectionThreadsPinOrderKey", Migration0038],
|
||||
[39, "ProjectionProjectsDefaultThreadEnvMode", Migration0039],
|
||||
[40, "ProjectionProjectFaviconPath", Migration0040],
|
||||
@@ -119,26 +118,9 @@ export const migrationEntries = [
|
||||
[43, "OrchestrationV2Foundation", Migration035V2],
|
||||
[44, "OrchestrationV2ProviderSessionBindings", Migration036V2],
|
||||
[45, "OrchestrationV2ThreadLaunchWorkflows", Migration037V2],
|
||||
=======
|
||||
[38, "OrchestrationV2", Migration033V2],
|
||||
[39, "OrchestrationV2Subagents", Migration034V2],
|
||||
[40, "OrchestrationV2Foundation", Migration035V2],
|
||||
[41, "OrchestrationV2ProviderSessionBindings", Migration036V2],
|
||||
[42, "OrchestrationV2ThreadLaunchWorkflows", Migration037V2],
|
||||
<<<<<<< HEAD
|
||||
=======
|
||||
[37, "OrchestrationV2", Migration0026V2],
|
||||
[38, "OrchestrationV2Subagents", Migration0034V2],
|
||||
[39, "OrchestrationV2Foundation", Migration0035V2],
|
||||
[40, "OrchestrationV2ProviderSessionBindings", Migration036V2],
|
||||
[41, "OrchestrationV2ThreadLaunchWorkflows", Migration037V2],
|
||||
[42, "ApplicationEventSource", Migration038V2],
|
||||
>>>>>>> 56f9a4b262 (Integrate orchestration v2 with the application runtime)
|
||||
>>>>>>> f38dbfd84c (Integrate orchestration v2 with the application runtime)
|
||||
=======
|
||||
[43, "ApplicationEventSource", Migration038V2],
|
||||
[44, "OrchestrationV2EffectCancellation", Migration039V2],
|
||||
>>>>>>> 799e032fe9 (Integrate orchestration V2 controls and process recovery)
|
||||
[46, "ApplicationEventSource", Migration038V2],
|
||||
[47, "OrchestrationV2EffectCancellation", Migration039V2],
|
||||
[48, "ScheduledTasks", Migration040V2],
|
||||
] as const;
|
||||
|
||||
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
CREATE TABLE IF NOT EXISTS scheduled_tasks (
|
||||
task_id TEXT PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
prompt TEXT NOT NULL,
|
||||
enabled INTEGER NOT NULL,
|
||||
schedule_json TEXT NOT NULL,
|
||||
project_id TEXT NOT NULL,
|
||||
thread_id TEXT,
|
||||
workspace_strategy_json TEXT NOT NULL,
|
||||
model_selection_json TEXT NOT NULL,
|
||||
runtime_mode TEXT NOT NULL,
|
||||
interaction_mode TEXT NOT NULL,
|
||||
created_by TEXT NOT NULL,
|
||||
creation_source TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL,
|
||||
next_run_at TEXT,
|
||||
last_run_at TEXT,
|
||||
last_run_status TEXT NOT NULL,
|
||||
last_run_error TEXT,
|
||||
run_count INTEGER NOT NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
CREATE INDEX IF NOT EXISTS idx_scheduled_tasks_due
|
||||
ON scheduled_tasks(enabled, next_run_at)
|
||||
WHERE enabled = 1 AND next_run_at IS NOT NULL
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
CREATE INDEX IF NOT EXISTS idx_scheduled_tasks_project
|
||||
ON scheduled_tasks(project_id, updated_at)
|
||||
`;
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
|
||||
import {
|
||||
isMissedFixedTimeRun,
|
||||
isSameSchedule,
|
||||
nextScheduledRunAt,
|
||||
parseTimeOfDay,
|
||||
} from "./Schedule.ts";
|
||||
|
||||
describe("scheduled task schedule calculation", () => {
|
||||
it("parses 24-hour times", () => {
|
||||
expect(parseTimeOfDay("09:30")).toEqual({ hour: 9, minute: 30 });
|
||||
expect(parseTimeOfDay("23:59")).toEqual({ hour: 23, minute: 59 });
|
||||
expect(parseTimeOfDay("25:00")).toBeNull();
|
||||
});
|
||||
|
||||
it("calculates interval schedules from the supplied instant", () => {
|
||||
const next = nextScheduledRunAt(
|
||||
{ type: "interval", everyMs: 5 * 60_000 },
|
||||
DateTime.makeUnsafe("2026-07-01T16:00:00.000Z"),
|
||||
);
|
||||
expect(next ? DateTime.formatIso(DateTime.toUtc(next)) : null).toBe("2026-07-01T16:05:00.000Z");
|
||||
});
|
||||
|
||||
it("skips to the next matching fixed-time weekday", () => {
|
||||
const next = nextScheduledRunAt(
|
||||
{ type: "fixed_time", timeOfDay: "09:00", weekdays: [1, 2, 3, 4, 5] },
|
||||
DateTime.makeZonedUnsafe(
|
||||
{
|
||||
year: 2026,
|
||||
month: 7,
|
||||
day: 3,
|
||||
hour: 10,
|
||||
minute: 0,
|
||||
second: 0,
|
||||
millisecond: 0,
|
||||
},
|
||||
{ timeZone: "America/Los_Angeles", adjustForTimeZone: true },
|
||||
),
|
||||
);
|
||||
const parts = next ? DateTime.toParts(next) : null;
|
||||
expect(parts?.weekDay).toBe(1);
|
||||
expect(parts?.hour).toBe(9);
|
||||
expect(parts?.minute).toBe(0);
|
||||
});
|
||||
|
||||
it("skips fixed-time runs missed by more than the grace window", () => {
|
||||
const fixedTime = { type: "fixed_time", timeOfDay: "09:00" } as const;
|
||||
const dueAt = DateTime.makeUnsafe("2026-07-01T09:00:00.000Z");
|
||||
const withinGrace = DateTime.makeUnsafe("2026-07-01T09:05:00.000Z");
|
||||
const pastGrace = DateTime.makeUnsafe("2026-07-01T15:00:00.000Z");
|
||||
// A run only slightly late (poll jitter, short sleep) still fires.
|
||||
expect(isMissedFixedTimeRun(fixedTime, dueAt, withinGrace)).toBe(false);
|
||||
// A run hours past its slot is skipped and rescheduled instead.
|
||||
expect(isMissedFixedTimeRun(fixedTime, dueAt, pastGrace)).toBe(true);
|
||||
// Interval schedules always catch up with a single run, never skip.
|
||||
expect(isMissedFixedTimeRun({ type: "interval", everyMs: 60_000 }, dueAt, pastGrace)).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("compares schedules structurally", () => {
|
||||
expect(
|
||||
isSameSchedule({ type: "interval", everyMs: 60_000 }, { type: "interval", everyMs: 60_000 }),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isSameSchedule({ type: "interval", everyMs: 60_000 }, { type: "interval", everyMs: 30_000 }),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isSameSchedule(
|
||||
{ type: "fixed_time", timeOfDay: "09:00", weekdays: [1, 2] },
|
||||
{ type: "fixed_time", timeOfDay: "09:00", weekdays: [1, 2] },
|
||||
),
|
||||
).toBe(true);
|
||||
// Weekday masks are sets: order and duplicates do not change firing.
|
||||
expect(
|
||||
isSameSchedule(
|
||||
{ type: "fixed_time", timeOfDay: "09:00", weekdays: [5, 1] },
|
||||
{ type: "fixed_time", timeOfDay: "09:00", weekdays: [1, 5, 5] },
|
||||
),
|
||||
).toBe(true);
|
||||
// Omitted, empty, and all-seven masks all mean daily.
|
||||
expect(
|
||||
isSameSchedule(
|
||||
{ type: "fixed_time", timeOfDay: "09:00" },
|
||||
{ type: "fixed_time", timeOfDay: "09:00", weekdays: [0, 1, 2, 3, 4, 5, 6] },
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isSameSchedule(
|
||||
{ type: "fixed_time", timeOfDay: "09:00", weekdays: [] },
|
||||
{ type: "fixed_time", timeOfDay: "09:00" },
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isSameSchedule(
|
||||
{ type: "fixed_time", timeOfDay: "09:00", weekdays: [1, 2] },
|
||||
{ type: "fixed_time", timeOfDay: "09:00", weekdays: [1, 3] },
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isSameSchedule(
|
||||
{ type: "fixed_time", timeOfDay: "09:00" },
|
||||
{ type: "fixed_time", timeOfDay: "09:30" },
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isSameSchedule(
|
||||
{ type: "interval", everyMs: 60_000 },
|
||||
{ type: "fixed_time", timeOfDay: "09:00" },
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
import type { ScheduledTaskSchedule } from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
|
||||
const MINUTE_MS = 60_000;
|
||||
|
||||
export function parseTimeOfDay(value: string): { hour: number; minute: number } | null {
|
||||
const match = /^([01]?\d|2[0-3]):([0-5]\d)$/.exec(value.trim());
|
||||
if (!match) return null;
|
||||
return { hour: Number(match[1]), minute: Number(match[2]) };
|
||||
}
|
||||
|
||||
export function nextScheduledRunAt(
|
||||
schedule: ScheduledTaskSchedule,
|
||||
from: DateTime.DateTime,
|
||||
): DateTime.DateTime | null {
|
||||
if (schedule.type === "interval") {
|
||||
return DateTime.add(from, { milliseconds: schedule.everyMs });
|
||||
}
|
||||
|
||||
const time = parseTimeOfDay(schedule.timeOfDay);
|
||||
if (time === null) return null;
|
||||
const weekdays =
|
||||
schedule.weekdays && schedule.weekdays.length > 0 ? new Set(schedule.weekdays) : null;
|
||||
for (let offset = 0; offset <= 7; offset += 1) {
|
||||
const candidate = DateTime.setParts(DateTime.add(from, { days: offset }), {
|
||||
hour: time.hour,
|
||||
minute: time.minute,
|
||||
second: 0,
|
||||
millisecond: 0,
|
||||
});
|
||||
if (DateTime.toEpochMillis(candidate) <= DateTime.toEpochMillis(from)) continue;
|
||||
if (weekdays !== null && !weekdays.has(DateTime.toParts(candidate).weekDay)) continue;
|
||||
return candidate;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Canonical form of a weekday mask, mirroring how `nextScheduledRunAt` reads
|
||||
* it: order and duplicates are irrelevant, and an empty/omitted mask means the
|
||||
* same as explicitly listing all seven days — daily.
|
||||
*/
|
||||
function weekdayKey(weekdays: ReadonlyArray<number> | undefined): string {
|
||||
const unique = [...new Set(weekdays ?? [])].toSorted((x, y) => x - y);
|
||||
if (unique.length === 0 || unique.length === 7) return "daily";
|
||||
return unique.join(",");
|
||||
}
|
||||
|
||||
/** Semantic equality for schedules: true iff both fire at the same times. */
|
||||
export function isSameSchedule(a: ScheduledTaskSchedule, b: ScheduledTaskSchedule): boolean {
|
||||
if (a.type === "interval") {
|
||||
return b.type === "interval" && a.everyMs === b.everyMs;
|
||||
}
|
||||
return (
|
||||
b.type === "fixed_time" &&
|
||||
a.timeOfDay === b.timeOfDay &&
|
||||
weekdayKey(a.weekdays) === weekdayKey(b.weekdays)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* How late a fixed-time run may fire before it counts as missed. Covers poll
|
||||
* jitter and short sleeps, while a server booted hours after the slot skips
|
||||
* to the next occurrence instead of firing stale work at a random time.
|
||||
*/
|
||||
export const MISSED_FIXED_TIME_GRACE_MS = 10 * MINUTE_MS;
|
||||
|
||||
/**
|
||||
* True when a due fixed-time run was missed by more than the grace window and
|
||||
* should be rescheduled to its next occurrence instead of firing now.
|
||||
* Interval schedules are never considered missed: an overdue interval task
|
||||
* catching up with a single run is the desired behaviour.
|
||||
*/
|
||||
export function isMissedFixedTimeRun(
|
||||
schedule: ScheduledTaskSchedule,
|
||||
dueAt: DateTime.DateTime,
|
||||
now: DateTime.DateTime,
|
||||
): boolean {
|
||||
if (schedule.type !== "fixed_time") return false;
|
||||
return DateTime.toEpochMillis(now) - DateTime.toEpochMillis(dueAt) > MISSED_FIXED_TIME_GRACE_MS;
|
||||
}
|
||||
|
||||
export function describeSchedule(schedule: ScheduledTaskSchedule): string {
|
||||
if (schedule.type === "interval") {
|
||||
const minutes = schedule.everyMs / MINUTE_MS;
|
||||
if (Number.isInteger(minutes)) {
|
||||
return `Every ${minutes === 1 ? "minute" : `${minutes} minutes`}`;
|
||||
}
|
||||
return `Every ${Math.round(schedule.everyMs / 1000)} seconds`;
|
||||
}
|
||||
|
||||
const weekdayCount = schedule.weekdays?.length ?? 0;
|
||||
const days =
|
||||
weekdayCount === 0
|
||||
? "day"
|
||||
: weekdayCount === 5 && schedule.weekdays?.every((day) => day >= 1 && day <= 5)
|
||||
? "weekday"
|
||||
: "selected day";
|
||||
return `At ${schedule.timeOfDay} every ${days}`;
|
||||
}
|
||||
@@ -0,0 +1,799 @@
|
||||
import {
|
||||
CommandId,
|
||||
MessageId,
|
||||
ScheduledTask,
|
||||
ScheduledTaskError,
|
||||
ScheduledTaskId,
|
||||
ThreadId,
|
||||
type ScheduledTaskDeleteInput,
|
||||
type ScheduledTaskDeleteResult,
|
||||
type ScheduledTaskListResult,
|
||||
type ScheduledTaskMutationResult,
|
||||
type ScheduledTaskRunNowInput,
|
||||
type ScheduledTaskRunNowResult,
|
||||
type ScheduledTaskSetEnabledInput,
|
||||
type ScheduledTaskUpsertInput,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts";
|
||||
import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
|
||||
import { isMissedFixedTimeRun, isSameSchedule, nextScheduledRunAt } from "./Schedule.ts";
|
||||
|
||||
const decodeTask = Schema.decodeUnknownEffect(ScheduledTask);
|
||||
const decodeScheduleJson = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(ScheduledTask.fields.schedule),
|
||||
);
|
||||
const decodeWorkspaceStrategyJson = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(ScheduledTask.fields.workspaceStrategy),
|
||||
);
|
||||
const decodeModelSelectionJson = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(ScheduledTask.fields.modelSelection),
|
||||
);
|
||||
|
||||
interface ScheduledTaskRow {
|
||||
readonly task_id: string;
|
||||
readonly title: string;
|
||||
readonly prompt: string;
|
||||
readonly enabled: number;
|
||||
readonly schedule_json: string;
|
||||
readonly project_id: string;
|
||||
readonly thread_id: string | null;
|
||||
readonly workspace_strategy_json: string;
|
||||
readonly model_selection_json: string;
|
||||
readonly runtime_mode: string;
|
||||
readonly interaction_mode: string;
|
||||
readonly created_by: string;
|
||||
readonly creation_source: string;
|
||||
readonly created_at: string;
|
||||
readonly updated_at: string;
|
||||
readonly next_run_at: string | null;
|
||||
readonly last_run_at: string | null;
|
||||
readonly last_run_status: string;
|
||||
readonly last_run_error: string | null;
|
||||
readonly run_count: number;
|
||||
}
|
||||
|
||||
export class ScheduledTaskService extends Context.Service<
|
||||
ScheduledTaskService,
|
||||
{
|
||||
readonly list: () => Effect.Effect<ScheduledTaskListResult, ScheduledTaskError>;
|
||||
/** Emits the full task list on subscribe and again after every change (CRUD, run transitions, reschedules). */
|
||||
readonly subscribeList: () => Stream.Stream<ScheduledTaskListResult, ScheduledTaskError>;
|
||||
readonly upsert: (
|
||||
input: ScheduledTaskUpsertInput,
|
||||
) => Effect.Effect<ScheduledTaskMutationResult, ScheduledTaskError>;
|
||||
/** Partial update flipping only the enabled flag; never touches other fields. */
|
||||
readonly setEnabled: (
|
||||
input: ScheduledTaskSetEnabledInput,
|
||||
) => Effect.Effect<ScheduledTaskMutationResult, ScheduledTaskError>;
|
||||
readonly delete: (
|
||||
input: ScheduledTaskDeleteInput,
|
||||
) => Effect.Effect<ScheduledTaskDeleteResult, ScheduledTaskError>;
|
||||
readonly runNow: (
|
||||
input: ScheduledTaskRunNowInput,
|
||||
) => Effect.Effect<ScheduledTaskRunNowResult, ScheduledTaskError>;
|
||||
}
|
||||
>()("t3/scheduledTasks/ScheduledTaskService") {}
|
||||
|
||||
function taskError(message: string, input?: { taskId?: ScheduledTaskId; cause?: unknown }) {
|
||||
return new ScheduledTaskError({
|
||||
message,
|
||||
...(input?.taskId === undefined ? {} : { taskId: input.taskId }),
|
||||
...(input?.cause === undefined ? {} : { cause: input.cause }),
|
||||
});
|
||||
}
|
||||
|
||||
function automationPrompt(task: ScheduledTask): string {
|
||||
return `[Triggered by schedule task: ${task.title}]\n\n${task.prompt}`;
|
||||
}
|
||||
|
||||
function iso(value: DateTime.DateTime): string {
|
||||
return DateTime.formatIso(DateTime.toUtc(value));
|
||||
}
|
||||
|
||||
const localNow = DateTime.withCurrentZoneLocal(DateTime.nowInCurrentZone);
|
||||
|
||||
function nextRunAt(
|
||||
task: Pick<ScheduledTask, "enabled" | "schedule">,
|
||||
from: DateTime.DateTime,
|
||||
): string | null {
|
||||
if (!task.enabled) return null;
|
||||
const next = nextScheduledRunAt(task.schedule, from);
|
||||
return next === null ? null : iso(next);
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
if (Cause.isCause(error)) return Cause.pretty(error);
|
||||
if (error instanceof Error) return error.message;
|
||||
return String(error);
|
||||
}
|
||||
|
||||
const decodeRow = (row: ScheduledTaskRow) =>
|
||||
Effect.gen(function* () {
|
||||
const id = ScheduledTaskId.make(row.task_id);
|
||||
const schedule = yield* decodeScheduleJson(row.schedule_json);
|
||||
const workspaceStrategy = yield* decodeWorkspaceStrategyJson(row.workspace_strategy_json);
|
||||
const modelSelection = yield* decodeModelSelectionJson(row.model_selection_json);
|
||||
return yield* decodeTask({
|
||||
id,
|
||||
title: row.title,
|
||||
prompt: row.prompt,
|
||||
enabled: row.enabled === 1,
|
||||
schedule,
|
||||
projectId: row.project_id,
|
||||
threadId: row.thread_id,
|
||||
workspaceStrategy,
|
||||
modelSelection,
|
||||
runtimeMode: row.runtime_mode,
|
||||
interactionMode: row.interaction_mode,
|
||||
createdBy: row.created_by,
|
||||
creationSource: row.creation_source,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
nextRunAt: row.next_run_at,
|
||||
lastRunAt: row.last_run_at,
|
||||
lastRunStatus: row.last_run_status,
|
||||
lastRunError: row.last_run_error,
|
||||
runCount: row.run_count,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
taskError("Could not decode schedule task row.", {
|
||||
taskId: ScheduledTaskId.make(row.task_id),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
export const layer = Layer.effect(
|
||||
ScheduledTaskService,
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService;
|
||||
const threadManagement = yield* ThreadManagementService.ThreadManagementService;
|
||||
const activeRuns = yield* Ref.make<ReadonlySet<ScheduledTaskId>>(new Set());
|
||||
// Sliding(1) coalesces the dirty-signal: every notification triggers a
|
||||
// full list() re-emit anyway, so a slow subscriber only ever needs the
|
||||
// latest signal — an unbounded backlog would just grow memory.
|
||||
const changesPubSub = yield* PubSub.sliding<void>(1);
|
||||
const notifyChanged = PubSub.publish(changesPubSub, undefined).pipe(Effect.asVoid);
|
||||
|
||||
const selectAllRows = () => sql<ScheduledTaskRow>`
|
||||
SELECT
|
||||
task_id,
|
||||
title,
|
||||
prompt,
|
||||
enabled,
|
||||
schedule_json,
|
||||
project_id,
|
||||
thread_id,
|
||||
workspace_strategy_json,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
created_by,
|
||||
creation_source,
|
||||
created_at,
|
||||
updated_at,
|
||||
next_run_at,
|
||||
last_run_at,
|
||||
last_run_status,
|
||||
last_run_error,
|
||||
run_count
|
||||
FROM scheduled_tasks
|
||||
ORDER BY updated_at DESC, task_id ASC
|
||||
`;
|
||||
|
||||
// Strict decode for the API surface: a corrupt row is a visible error.
|
||||
const listRows = Effect.fn("ScheduledTaskService.listRows")(function* () {
|
||||
const rows = yield* selectAllRows();
|
||||
return yield* Effect.forEach(rows, decodeRow, { concurrency: 1 });
|
||||
});
|
||||
|
||||
// Lenient decode for the scheduler: one corrupt row must never halt the
|
||||
// poll loop or crash recovery for every other task — skip it and log.
|
||||
const listTasksLenient = Effect.fn("ScheduledTaskService.listTasksLenient")(function* () {
|
||||
const rows = yield* selectAllRows();
|
||||
const tasks: ScheduledTask[] = [];
|
||||
for (const row of rows) {
|
||||
const decoded = yield* Effect.result(decodeRow(row));
|
||||
if (Result.isSuccess(decoded)) {
|
||||
tasks.push(decoded.success);
|
||||
} else {
|
||||
yield* Effect.logWarning("Skipping undecodable schedule task row", {
|
||||
taskId: row.task_id,
|
||||
cause: decoded.failure,
|
||||
});
|
||||
}
|
||||
}
|
||||
return tasks;
|
||||
});
|
||||
|
||||
const getRows = (id: ScheduledTaskId) => sql<ScheduledTaskRow>`
|
||||
SELECT
|
||||
task_id,
|
||||
title,
|
||||
prompt,
|
||||
enabled,
|
||||
schedule_json,
|
||||
project_id,
|
||||
thread_id,
|
||||
workspace_strategy_json,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
created_by,
|
||||
creation_source,
|
||||
created_at,
|
||||
updated_at,
|
||||
next_run_at,
|
||||
last_run_at,
|
||||
last_run_status,
|
||||
last_run_error,
|
||||
run_count
|
||||
FROM scheduled_tasks
|
||||
WHERE task_id = ${id}
|
||||
`;
|
||||
|
||||
/** Load a task, returning `null` when it does not exist; real load/decode failures propagate. */
|
||||
const findTask = Effect.fn("ScheduledTaskService.findTask")(function* (id: ScheduledTaskId) {
|
||||
const rows = yield* getRows(id).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
taskError("Could not load schedule task.", { taskId: id, cause }),
|
||||
),
|
||||
);
|
||||
const row = rows[0];
|
||||
if (row === undefined) return null;
|
||||
return yield* decodeRow(row);
|
||||
});
|
||||
|
||||
const loadTask = Effect.fn("ScheduledTaskService.loadTask")(function* (id: ScheduledTaskId) {
|
||||
const task = yield* findTask(id);
|
||||
if (task === null) {
|
||||
return yield* taskError("Schedule task not found.", { taskId: id });
|
||||
}
|
||||
return task;
|
||||
});
|
||||
|
||||
// Run-state columns (last_run_*, run_count) are intentionally absent from
|
||||
// the conflict clause: they are owned by the run transitions below, and a
|
||||
// concurrent settings save must not overwrite an in-flight increment.
|
||||
const saveTask = (task: ScheduledTask) =>
|
||||
sql`
|
||||
INSERT INTO scheduled_tasks (
|
||||
task_id,
|
||||
title,
|
||||
prompt,
|
||||
enabled,
|
||||
schedule_json,
|
||||
project_id,
|
||||
thread_id,
|
||||
workspace_strategy_json,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
created_by,
|
||||
creation_source,
|
||||
created_at,
|
||||
updated_at,
|
||||
next_run_at,
|
||||
last_run_at,
|
||||
last_run_status,
|
||||
last_run_error,
|
||||
run_count
|
||||
)
|
||||
VALUES (
|
||||
${task.id},
|
||||
${task.title},
|
||||
${task.prompt},
|
||||
${task.enabled ? 1 : 0},
|
||||
${JSON.stringify(task.schedule)},
|
||||
${task.projectId},
|
||||
${task.threadId},
|
||||
${JSON.stringify(task.workspaceStrategy)},
|
||||
${JSON.stringify(task.modelSelection)},
|
||||
${task.runtimeMode},
|
||||
${task.interactionMode},
|
||||
${task.createdBy},
|
||||
${task.creationSource},
|
||||
${task.createdAt},
|
||||
${task.updatedAt},
|
||||
${task.nextRunAt},
|
||||
${task.lastRunAt},
|
||||
${task.lastRunStatus},
|
||||
${task.lastRunError},
|
||||
${task.runCount}
|
||||
)
|
||||
ON CONFLICT (task_id)
|
||||
DO UPDATE SET
|
||||
title = excluded.title,
|
||||
prompt = excluded.prompt,
|
||||
enabled = excluded.enabled,
|
||||
schedule_json = excluded.schedule_json,
|
||||
project_id = excluded.project_id,
|
||||
thread_id = excluded.thread_id,
|
||||
workspace_strategy_json = excluded.workspace_strategy_json,
|
||||
model_selection_json = excluded.model_selection_json,
|
||||
runtime_mode = excluded.runtime_mode,
|
||||
interaction_mode = excluded.interaction_mode,
|
||||
creation_source = excluded.creation_source,
|
||||
updated_at = excluded.updated_at,
|
||||
next_run_at = excluded.next_run_at
|
||||
`.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
taskError("Could not save schedule task.", { taskId: task.id, cause }),
|
||||
),
|
||||
);
|
||||
|
||||
const deleteRow = (id: ScheduledTaskId) =>
|
||||
sql`DELETE FROM scheduled_tasks WHERE task_id = ${id}`.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
taskError("Could not delete schedule task.", { taskId: id, cause }),
|
||||
),
|
||||
);
|
||||
|
||||
// Run-state transitions use targeted UPDATEs (never the full-row upsert) so
|
||||
// a completing run cannot resurrect a deleted task or clobber concurrent
|
||||
// edits to the task definition.
|
||||
const markRunning = (id: ScheduledTaskId, startedAtIso: string) =>
|
||||
sql`
|
||||
UPDATE scheduled_tasks
|
||||
SET updated_at = ${startedAtIso},
|
||||
last_run_at = ${startedAtIso},
|
||||
last_run_status = 'running',
|
||||
last_run_error = NULL
|
||||
WHERE task_id = ${id}
|
||||
`.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
taskError("Could not mark schedule task as running.", { taskId: id, cause }),
|
||||
),
|
||||
);
|
||||
|
||||
const markCompleted = (input: {
|
||||
readonly id: ScheduledTaskId;
|
||||
readonly completedAtIso: string;
|
||||
readonly nextRunAtIso: string | null;
|
||||
readonly status: "succeeded" | "failed";
|
||||
readonly error: string | null;
|
||||
readonly startedAtIso: string;
|
||||
}) =>
|
||||
sql`
|
||||
UPDATE scheduled_tasks
|
||||
SET updated_at = ${input.completedAtIso},
|
||||
next_run_at = ${input.nextRunAtIso},
|
||||
last_run_status = ${input.status},
|
||||
last_run_error = ${input.error},
|
||||
run_count = run_count + 1
|
||||
WHERE task_id = ${input.id}
|
||||
AND last_run_status = 'running'
|
||||
AND last_run_at = ${input.startedAtIso}
|
||||
`.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
taskError("Could not record schedule task run.", { taskId: input.id, cause }),
|
||||
),
|
||||
);
|
||||
|
||||
// Best-effort escape hatch: if anything fails between markRunning and
|
||||
// markCompleted, write a full terminal record so runDueTasks neither skips
|
||||
// the task forever (it filters out 'running' rows) nor re-fires it
|
||||
// immediately: the dispatch may already have gone out, so next_run_at must
|
||||
// advance and run_count must count the attempt.
|
||||
const releaseStuckRun = (task: ScheduledTask, message: string) =>
|
||||
Effect.gen(function* () {
|
||||
const now = yield* localNow;
|
||||
// Compute the next occurrence from the current row so a schedule
|
||||
// edited while the run was in flight is honoured; fall back to the
|
||||
// run's snapshot only if the re-read itself fails.
|
||||
const reread = yield* Effect.result(findTask(task.id));
|
||||
if (Result.isSuccess(reread) && reread.success === null) return; // deleted — nothing to release
|
||||
const source = Result.isSuccess(reread) && reread.success !== null ? reread.success : task;
|
||||
yield* sql`
|
||||
UPDATE scheduled_tasks
|
||||
SET last_run_status = 'failed',
|
||||
last_run_error = ${message},
|
||||
next_run_at = ${nextRunAt(source, now)},
|
||||
updated_at = ${iso(now)},
|
||||
run_count = run_count + 1
|
||||
WHERE task_id = ${task.id} AND last_run_status = 'running'
|
||||
`;
|
||||
yield* notifyChanged;
|
||||
}).pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("Could not release stuck schedule task run", {
|
||||
taskId: task.id,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const runTask = Effect.fn("ScheduledTaskService.runTask")(function* (
|
||||
task: ScheduledTask,
|
||||
trigger: "scheduled" | "manual",
|
||||
) {
|
||||
const reserved = yield* Ref.modify(activeRuns, (active) => {
|
||||
if (active.has(task.id)) return [false, active] as const;
|
||||
const next = new Set(active);
|
||||
next.add(task.id);
|
||||
return [true, next] as const;
|
||||
});
|
||||
if (!reserved) {
|
||||
if (trigger === "manual") {
|
||||
return yield* taskError("Schedule task is already running.", { taskId: task.id });
|
||||
}
|
||||
return task;
|
||||
}
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const startedAt = yield* localNow;
|
||||
const startedAtIso = iso(startedAt);
|
||||
|
||||
// The in-memory snapshot may be stale: re-read before touching run
|
||||
// state. The task may have been deleted, paused, or postponed since
|
||||
// the poll loaded it — none of those may fire.
|
||||
const active = yield* findTask(task.id);
|
||||
if (active === null) {
|
||||
// A manual run on a just-deleted task must fail loudly, not report
|
||||
// a successful run that never dispatched.
|
||||
if (trigger === "manual") {
|
||||
return yield* taskError("Schedule task not found.", { taskId: task.id });
|
||||
}
|
||||
return task;
|
||||
}
|
||||
if (
|
||||
trigger === "scheduled" &&
|
||||
(!active.enabled ||
|
||||
active.nextRunAt === null ||
|
||||
DateTime.toEpochMillis(DateTime.makeUnsafe(active.nextRunAt)) >
|
||||
DateTime.toEpochMillis(startedAt))
|
||||
) {
|
||||
return active;
|
||||
}
|
||||
|
||||
yield* markRunning(active.id, startedAtIso);
|
||||
yield* notifyChanged;
|
||||
|
||||
const fireKey = `${active.id}:${DateTime.toEpochMillis(startedAt)}:${trigger}`;
|
||||
const commandId = CommandId.make(`scheduled-task:${fireKey}`);
|
||||
const messageId = MessageId.make(`scheduled-task-message:${fireKey}`);
|
||||
// Dispatch from the fresh row so prompt/model/binding edits made
|
||||
// after the poll read are honoured.
|
||||
const prompt = automationPrompt(active);
|
||||
|
||||
// Effect.exit (not Effect.result) so defects and interruptions in the
|
||||
// dispatch are also captured and recorded as a failed run instead of
|
||||
// aborting before markCompleted.
|
||||
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,
|
||||
text: prompt,
|
||||
attachments: [],
|
||||
},
|
||||
createdBy: active.createdBy,
|
||||
creationSource: active.creationSource,
|
||||
}),
|
||||
)
|
||||
: yield* Effect.exit(
|
||||
threadManagement.sendToThread({
|
||||
projectId: active.projectId,
|
||||
commandId,
|
||||
threadId: ThreadId.make(active.threadId),
|
||||
messageId,
|
||||
text: prompt,
|
||||
attachments: [],
|
||||
modelSelection: active.modelSelection,
|
||||
mode: "auto",
|
||||
createdBy: active.createdBy,
|
||||
creationSource: active.creationSource,
|
||||
}),
|
||||
);
|
||||
|
||||
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);
|
||||
// Re-read the task so the next run is computed from the schedule as it
|
||||
// is *now* (the user may have edited or deleted it while we ran).
|
||||
const current = yield* findTask(task.id);
|
||||
const scheduleSource = current ?? task;
|
||||
const completed: ScheduledTask = {
|
||||
...scheduleSource,
|
||||
updatedAt: iso(completedAt),
|
||||
lastRunAt: startedAtIso,
|
||||
nextRunAt: nextRunAt(scheduleSource, completedAt),
|
||||
lastRunStatus,
|
||||
lastRunError,
|
||||
runCount: scheduleSource.runCount + 1,
|
||||
};
|
||||
if (current !== null) {
|
||||
// startedAtIso in the guard ensures this writes only to the row this
|
||||
// run marked as running — a task deleted mid-run and recreated with
|
||||
// the same id (idempotent commandId replay) must not be stamped.
|
||||
yield* markCompleted({
|
||||
id: task.id,
|
||||
completedAtIso: completed.updatedAt,
|
||||
nextRunAtIso: completed.nextRunAt,
|
||||
status: lastRunStatus,
|
||||
error: lastRunError,
|
||||
startedAtIso,
|
||||
});
|
||||
yield* notifyChanged;
|
||||
}
|
||||
return completed;
|
||||
}).pipe(
|
||||
Effect.onError((cause) => releaseStuckRun(task, errorMessage(cause))),
|
||||
Effect.ensuring(
|
||||
Ref.update(activeRuns, (active) => {
|
||||
const next = new Set(active);
|
||||
next.delete(task.id);
|
||||
return next;
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
// A due fixed-time run that is long past its slot (server was off or
|
||||
// asleep) is skipped and re-aimed at its next occurrence, not fired late.
|
||||
const rescheduleMissedRun = Effect.fn("ScheduledTaskService.rescheduleMissedRun")(function* (
|
||||
task: ScheduledTask,
|
||||
now: DateTime.DateTime,
|
||||
) {
|
||||
const next = nextRunAt(task, now);
|
||||
yield* Effect.logInfo("Skipping missed schedule task run", {
|
||||
taskId: task.id,
|
||||
missedRunAt: task.nextRunAt,
|
||||
rescheduledTo: next,
|
||||
});
|
||||
yield* sql`
|
||||
UPDATE scheduled_tasks
|
||||
SET next_run_at = ${next},
|
||||
updated_at = ${iso(now)}
|
||||
WHERE task_id = ${task.id}
|
||||
`.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
taskError("Could not reschedule missed schedule task run.", { taskId: task.id, cause }),
|
||||
),
|
||||
);
|
||||
yield* notifyChanged;
|
||||
});
|
||||
|
||||
const runDueTasks = Effect.fn("ScheduledTaskService.runDueTasks")(function* () {
|
||||
const tasks = yield* listTasksLenient().pipe(
|
||||
Effect.mapError((cause) => taskError("Could not list schedule tasks.", { cause })),
|
||||
);
|
||||
const now = yield* localNow;
|
||||
const nowEpochMillis = DateTime.toEpochMillis(now);
|
||||
const due = tasks.flatMap((task) => {
|
||||
if (!task.enabled || task.nextRunAt === null || task.lastRunStatus === "running") {
|
||||
return [];
|
||||
}
|
||||
const dueAt = DateTime.makeUnsafe(task.nextRunAt);
|
||||
return DateTime.toEpochMillis(dueAt) <= nowEpochMillis ? [{ task, dueAt }] : [];
|
||||
});
|
||||
yield* Effect.forEach(
|
||||
due,
|
||||
({ task, dueAt }) =>
|
||||
(isMissedFixedTimeRun(task.schedule, dueAt, now)
|
||||
? rescheduleMissedRun(task, now)
|
||||
: runTask(task, "scheduled")
|
||||
).pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("Scheduled task run failed", { taskId: task.id, cause }),
|
||||
),
|
||||
),
|
||||
{ concurrency: 1, discard: true },
|
||||
);
|
||||
});
|
||||
|
||||
// Recover from a crash or hard shutdown mid-run: rows stuck in 'running'
|
||||
// would otherwise be skipped by the due-task filter forever. The dispatch
|
||||
// may already have gone out before the crash, so next_run_at must advance
|
||||
// and run_count must count the attempt — otherwise the first poll after
|
||||
// every restart re-fires the interrupted task (same rationale as
|
||||
// releaseStuckRun). Schedules are JSON, so this is per-row Effect work
|
||||
// rather than a single UPDATE.
|
||||
yield* Effect.gen(function* () {
|
||||
const rows = yield* selectAllRows();
|
||||
const stuck = rows.filter((row) => row.last_run_status === "running");
|
||||
if (stuck.length === 0) return;
|
||||
const now = yield* localNow;
|
||||
yield* Effect.forEach(
|
||||
stuck,
|
||||
(row) =>
|
||||
Effect.gen(function* () {
|
||||
const decoded = yield* Effect.result(decodeRow(row));
|
||||
if (Result.isSuccess(decoded)) {
|
||||
yield* sql`
|
||||
UPDATE scheduled_tasks
|
||||
SET last_run_status = 'failed',
|
||||
last_run_error = 'Run was interrupted by a server restart.',
|
||||
next_run_at = ${nextRunAt(decoded.success, now)},
|
||||
updated_at = ${iso(now)},
|
||||
run_count = run_count + 1
|
||||
WHERE task_id = ${row.task_id} AND last_run_status = 'running'
|
||||
`;
|
||||
return;
|
||||
}
|
||||
// The schedule cannot be decoded, so the next occurrence cannot
|
||||
// be computed — still release the row so it is not stuck in
|
||||
// 'running' (the lenient poller skips it, so it cannot re-fire).
|
||||
yield* Effect.logWarning(
|
||||
"Recovering undecodable schedule task row without rescheduling",
|
||||
{ taskId: row.task_id, cause: decoded.failure },
|
||||
);
|
||||
yield* sql`
|
||||
UPDATE scheduled_tasks
|
||||
SET last_run_status = 'failed',
|
||||
last_run_error = 'Run was interrupted by a server restart.',
|
||||
updated_at = ${iso(now)},
|
||||
run_count = run_count + 1
|
||||
WHERE task_id = ${row.task_id} AND last_run_status = 'running'
|
||||
`;
|
||||
}),
|
||||
{ concurrency: 1, discard: true },
|
||||
);
|
||||
yield* notifyChanged;
|
||||
}).pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("Could not reset interrupted schedule task runs", { cause }),
|
||||
),
|
||||
);
|
||||
|
||||
yield* runDueTasks().pipe(
|
||||
Effect.catch((cause) => Effect.logWarning("Scheduled task polling failed", { cause })),
|
||||
Effect.delay(Duration.seconds(5)),
|
||||
Effect.forever,
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
const list: ScheduledTaskService["Service"]["list"] = () =>
|
||||
listRows().pipe(
|
||||
Effect.map((tasks) => ({ tasks })),
|
||||
Effect.mapError((cause) => taskError("Could not list schedule tasks.", { cause })),
|
||||
);
|
||||
|
||||
const subscribeList: ScheduledTaskService["Service"]["subscribeList"] = () =>
|
||||
Stream.unwrap(
|
||||
Effect.gen(function* () {
|
||||
// Subscribe before taking the snapshot so a change landing between
|
||||
// the two is buffered by the subscription rather than dropped.
|
||||
const subscription = yield* PubSub.subscribe(changesPubSub);
|
||||
return Stream.concat(
|
||||
Stream.fromEffect(list()),
|
||||
Stream.fromSubscription(subscription).pipe(Stream.mapEffect(() => list())),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const upsert: ScheduledTaskService["Service"]["upsert"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const now = yield* localNow;
|
||||
const uuid =
|
||||
input.commandId === undefined
|
||||
? yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
taskError("Could not generate schedule task id.", { cause }),
|
||||
),
|
||||
)
|
||||
: null;
|
||||
const id =
|
||||
input.id ??
|
||||
ScheduledTaskId.make(
|
||||
input.commandId ? `scheduled-task:${input.commandId}` : `scheduled-task:${uuid}`,
|
||||
);
|
||||
// Look up by the *resolved* id so idempotent creates (commandId replays)
|
||||
// keep their run history, and so real load failures propagate instead
|
||||
// of silently resetting an existing row.
|
||||
const existingTask = yield* findTask(id);
|
||||
// Keep the existing next_run_at when the schedule itself is untouched:
|
||||
// editing a title or prompt must not postpone (or resurrect) a due
|
||||
// run — only schedule/enabled changes restart the clock.
|
||||
const scheduleUnchanged =
|
||||
existingTask !== null &&
|
||||
existingTask.enabled === input.enabled &&
|
||||
isSameSchedule(existingTask.schedule, input.schedule);
|
||||
const task: ScheduledTask = {
|
||||
id,
|
||||
title: input.title,
|
||||
prompt: input.prompt,
|
||||
enabled: input.enabled,
|
||||
schedule: input.schedule,
|
||||
projectId: input.projectId,
|
||||
threadId: input.threadId ?? null,
|
||||
workspaceStrategy: input.workspaceStrategy,
|
||||
modelSelection: input.modelSelection,
|
||||
runtimeMode: input.runtimeMode,
|
||||
interactionMode: input.interactionMode,
|
||||
createdBy: existingTask?.createdBy ?? input.createdBy ?? "user",
|
||||
creationSource: input.creationSource ?? "web",
|
||||
createdAt: existingTask?.createdAt ?? iso(now),
|
||||
updatedAt: iso(now),
|
||||
nextRunAt: scheduleUnchanged
|
||||
? existingTask.nextRunAt
|
||||
: nextRunAt({ enabled: input.enabled, schedule: input.schedule }, now),
|
||||
lastRunAt: existingTask?.lastRunAt ?? null,
|
||||
lastRunStatus: existingTask?.lastRunStatus ?? "never",
|
||||
lastRunError: existingTask?.lastRunError ?? null,
|
||||
runCount: existingTask?.runCount ?? 0,
|
||||
};
|
||||
yield* saveTask(task);
|
||||
yield* notifyChanged;
|
||||
return { task };
|
||||
});
|
||||
|
||||
const setEnabled: ScheduledTaskService["Service"]["setEnabled"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const existing = yield* loadTask(input.id);
|
||||
if (existing.enabled === input.enabled) return { task: existing };
|
||||
const now = yield* localNow;
|
||||
const next = nextRunAt({ enabled: input.enabled, schedule: existing.schedule }, now);
|
||||
// RETURNING so a task deleted between the load and this UPDATE is a
|
||||
// visible not-found error, not a false success.
|
||||
const updated = yield* sql<{ task_id: string }>`
|
||||
UPDATE scheduled_tasks
|
||||
SET enabled = ${input.enabled ? 1 : 0},
|
||||
next_run_at = ${next},
|
||||
updated_at = ${iso(now)}
|
||||
WHERE task_id = ${input.id}
|
||||
RETURNING task_id
|
||||
`.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
taskError("Could not update schedule task.", { taskId: input.id, cause }),
|
||||
),
|
||||
);
|
||||
if (updated.length === 0) {
|
||||
return yield* taskError("Schedule task not found.", { taskId: input.id });
|
||||
}
|
||||
yield* notifyChanged;
|
||||
return {
|
||||
task: { ...existing, enabled: input.enabled, nextRunAt: next, updatedAt: iso(now) },
|
||||
};
|
||||
});
|
||||
|
||||
const deleteTask: ScheduledTaskService["Service"]["delete"] = (input) =>
|
||||
deleteRow(input.id).pipe(Effect.andThen(notifyChanged), Effect.as({ id: input.id }));
|
||||
|
||||
const runNow: ScheduledTaskService["Service"]["runNow"] = (input: ScheduledTaskRunNowInput) =>
|
||||
Effect.gen(function* () {
|
||||
const task = yield* loadTask(input.id);
|
||||
const next = yield* runTask(task, "manual").pipe(
|
||||
Effect.mapError((cause) =>
|
||||
taskError("Could not run schedule task.", { taskId: input.id, cause }),
|
||||
),
|
||||
);
|
||||
return { task: next };
|
||||
});
|
||||
|
||||
return ScheduledTaskService.of({
|
||||
list,
|
||||
subscribeList,
|
||||
upsert,
|
||||
setEnabled,
|
||||
delete: deleteTask,
|
||||
runNow,
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -66,6 +66,7 @@ import * as Keybindings from "./keybindings.ts";
|
||||
import * as ExternalLauncher from "./process/externalLauncher.ts";
|
||||
import * as ThreadManagementService from "./orchestration-v2/ThreadManagementService.ts";
|
||||
import * as ThreadLaunchService from "./orchestration-v2/ThreadLaunchService.ts";
|
||||
import * as ScheduledTasks from "./scheduledTasks/ScheduledTaskService.ts";
|
||||
import {
|
||||
archivedShellStreamItemFromSnapshot,
|
||||
shellStreamItemFromSnapshot,
|
||||
@@ -326,6 +327,12 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
|
||||
[WS_METHODS.serverGetProcessDiagnostics, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.serverGetProcessResourceHistory, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.serverSignalProcess, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.scheduledTasksList, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.scheduledTasksSubscribe, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.scheduledTasksUpsert, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.scheduledTasksSetEnabled, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.scheduledTasksDelete, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.scheduledTasksRunNow, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.cloudGetRelayClientStatus, AuthRelayWriteScope],
|
||||
[WS_METHODS.cloudInstallRelayClient, AuthRelayWriteScope],
|
||||
[WS_METHODS.sourceControlLookupRepository, AuthOrchestrationReadScope],
|
||||
@@ -431,6 +438,7 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
),
|
||||
);
|
||||
const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService;
|
||||
const scheduledTasks = yield* ScheduledTasks.ScheduledTaskService;
|
||||
const projectService = yield* ProjectService.ProjectService;
|
||||
const checkpointDiffQuery = yield* CheckpointDiffQuery.CheckpointDiffQuery;
|
||||
const keybindings = yield* Keybindings.Keybindings;
|
||||
@@ -1013,6 +1021,33 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
"orchestration_v2.thread_id": input.threadId,
|
||||
},
|
||||
),
|
||||
[WS_METHODS.scheduledTasksList]: (_input) =>
|
||||
observeRpcEffect(WS_METHODS.scheduledTasksList, scheduledTasks.list(), {
|
||||
"rpc.aggregate": "scheduledTasks",
|
||||
}),
|
||||
[WS_METHODS.scheduledTasksSubscribe]: (_input) =>
|
||||
observeRpcStream(WS_METHODS.scheduledTasksSubscribe, scheduledTasks.subscribeList(), {
|
||||
"rpc.aggregate": "scheduledTasks",
|
||||
}),
|
||||
[WS_METHODS.scheduledTasksUpsert]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.scheduledTasksUpsert, scheduledTasks.upsert(input), {
|
||||
"rpc.aggregate": "scheduledTasks",
|
||||
}),
|
||||
[WS_METHODS.scheduledTasksSetEnabled]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.scheduledTasksSetEnabled, scheduledTasks.setEnabled(input), {
|
||||
"rpc.aggregate": "scheduledTasks",
|
||||
"scheduled_task.id": input.id,
|
||||
}),
|
||||
[WS_METHODS.scheduledTasksDelete]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.scheduledTasksDelete, scheduledTasks.delete(input), {
|
||||
"rpc.aggregate": "scheduledTasks",
|
||||
"scheduled_task.id": input.id,
|
||||
}),
|
||||
[WS_METHODS.scheduledTasksRunNow]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.scheduledTasksRunNow, scheduledTasks.runNow(input), {
|
||||
"rpc.aggregate": "scheduledTasks",
|
||||
"scheduled_task.id": input.id,
|
||||
}),
|
||||
[WS_METHODS.serverGetConfig]: (_input) =>
|
||||
observeRpcEffect(WS_METHODS.serverGetConfig, loadServerConfig, {
|
||||
"rpc.aggregate": "server",
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
import { CalendarClockIcon, PlayIcon, Settings2Icon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import type { EnvironmentId, ScheduledTask, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
|
||||
import { cn } from "../../lib/utils";
|
||||
import { relativeLabel, scheduleLabel } from "../settings/ScheduledTasksSettings";
|
||||
import { useEnvironmentQuery } from "../../state/query";
|
||||
import { serverEnvironment } from "../../state/server";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { Button } from "../ui/button";
|
||||
import { Switch } from "../ui/switch";
|
||||
import { stackedThreadToast, toastManager } from "../ui/toast";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import {
|
||||
THREAD_DETAILS_PANEL_ICON_ACTION_CLASS,
|
||||
THREAD_DETAILS_PANEL_ICON_CLASS,
|
||||
} from "./threadDetailsPanelStyles";
|
||||
|
||||
const STATUS_DOT_CLASS: Record<ScheduledTask["lastRunStatus"], string> = {
|
||||
never: "bg-muted-foreground/40",
|
||||
running: "animate-pulse bg-sky-500",
|
||||
succeeded: "bg-emerald-500",
|
||||
failed: "bg-destructive",
|
||||
};
|
||||
|
||||
/**
|
||||
* Thread details panel section listing the automations (scheduled tasks) bound
|
||||
* to this thread. Fed by the live scheduled-task subscription, so run status
|
||||
* and next-run times update as the scheduler works — no manual refresh.
|
||||
* Renders nothing when the thread has no bound automations.
|
||||
*/
|
||||
export function ThreadAutomationsPanel(props: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: ThreadId;
|
||||
}) {
|
||||
const tasksQuery = useEnvironmentQuery(
|
||||
serverEnvironment.scheduledTasksLive({ environmentId: props.environmentId, input: {} }),
|
||||
);
|
||||
const setTaskEnabled = useAtomCommand(serverEnvironment.setScheduledTaskEnabled, {
|
||||
label: "thread automation toggle",
|
||||
});
|
||||
const runTaskNow = useAtomCommand(serverEnvironment.runScheduledTaskNow, {
|
||||
label: "thread automation run now",
|
||||
});
|
||||
const navigate = useNavigate();
|
||||
const [busyTaskId, setBusyTaskId] = useState<string | null>(null);
|
||||
|
||||
const boundTasks = (tasksQuery.data?.tasks ?? []).filter(
|
||||
(task) => task.threadId === props.threadId,
|
||||
);
|
||||
// A load error must not look like "no automations" — this thread may have
|
||||
// tasks whose controls would silently vanish. Only hide the section when we
|
||||
// positively know there is nothing bound to it.
|
||||
if (tasksQuery.error === null && boundTasks.length === 0) return null;
|
||||
|
||||
const reportFailure = (title: string, error: unknown) => {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title,
|
||||
description: error instanceof Error ? error.message : String(error),
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const toggleEnabled = async (task: ScheduledTask, enabled: boolean) => {
|
||||
if (busyTaskId !== null) return;
|
||||
setBusyTaskId(task.id);
|
||||
// Partial update: only the enabled flag changes, so a toggle can never
|
||||
// revert concurrent edits made to the task elsewhere.
|
||||
const result = await setTaskEnabled({
|
||||
environmentId: props.environmentId,
|
||||
input: { id: task.id, enabled },
|
||||
});
|
||||
setBusyTaskId(null);
|
||||
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
|
||||
reportFailure("Could not update automation", squashAtomCommandFailure(result));
|
||||
}
|
||||
};
|
||||
|
||||
const runNow = async (task: ScheduledTask) => {
|
||||
if (busyTaskId !== null) return;
|
||||
setBusyTaskId(task.id);
|
||||
const result = await runTaskNow({
|
||||
environmentId: props.environmentId,
|
||||
input: { id: task.id },
|
||||
});
|
||||
setBusyTaskId(null);
|
||||
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
|
||||
reportFailure("Could not run automation", squashAtomCommandFailure(result));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<section
|
||||
aria-labelledby="thread-details-automations-heading"
|
||||
className="border-t border-border/65 px-2 pb-2.5 pt-2"
|
||||
data-thread-automations-panel
|
||||
>
|
||||
<div className="mb-1 flex min-h-8 items-center justify-between gap-2 px-2">
|
||||
<h3
|
||||
id="thread-details-automations-heading"
|
||||
className="text-[11px] font-medium text-muted-foreground"
|
||||
>
|
||||
Automations
|
||||
</h3>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className={THREAD_DETAILS_PANEL_ICON_ACTION_CLASS}
|
||||
aria-label="Manage schedule tasks"
|
||||
onClick={() => void navigate({ to: "/settings/scheduled-tasks" })}
|
||||
>
|
||||
<Settings2Icon className="size-3.5" />
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup>Manage schedule tasks</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
{tasksQuery.error !== null ? (
|
||||
<p className="px-2.5 py-1.5 text-[11px] text-destructive">
|
||||
Could not load automations: {tasksQuery.error}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<ul className="m-0 list-none p-0">
|
||||
{boundTasks.map((task) => (
|
||||
<li key={task.id} className="group flex items-center gap-2.5 rounded-lg px-2.5 py-1.5">
|
||||
<CalendarClockIcon className={THREAD_DETAILS_PANEL_ICON_CLASS} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span
|
||||
className={cn(
|
||||
"size-1.5 shrink-0 rounded-full",
|
||||
STATUS_DOT_CLASS[task.lastRunStatus],
|
||||
)}
|
||||
aria-hidden
|
||||
/>
|
||||
<span className="truncate text-[13px] font-medium text-foreground/80">
|
||||
{task.title}
|
||||
</span>
|
||||
</div>
|
||||
<p className="truncate text-[11px] text-muted-foreground">
|
||||
{scheduleLabel(task.schedule)}
|
||||
{task.enabled && task.nextRunAt !== null
|
||||
? ` · next ${relativeLabel(task.nextRunAt)}`
|
||||
: task.enabled
|
||||
? ""
|
||||
: " · paused"}
|
||||
</p>
|
||||
</div>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className={THREAD_DETAILS_PANEL_ICON_ACTION_CLASS}
|
||||
aria-label={`Run ${task.title} now`}
|
||||
disabled={busyTaskId !== null || task.lastRunStatus === "running"}
|
||||
onClick={() => void runNow(task)}
|
||||
>
|
||||
<PlayIcon className="size-3.5" />
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup>Run now</TooltipPopup>
|
||||
</Tooltip>
|
||||
<Switch
|
||||
checked={task.enabled}
|
||||
disabled={busyTaskId !== null}
|
||||
aria-label={task.enabled ? `Pause ${task.title}` : `Resume ${task.title}`}
|
||||
onCheckedChange={(enabled) => void toggleEnabled(task, enabled)}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import ProjectScriptsControl, {
|
||||
import { Button } from "../ui/button";
|
||||
import { cn } from "../../lib/utils";
|
||||
import { OpenInPicker } from "./OpenInPicker";
|
||||
import { ThreadAutomationsPanel } from "./ThreadAutomationsPanel";
|
||||
import { ThreadRelationshipsPanel } from "./ThreadRelationshipsControl";
|
||||
|
||||
interface VersionMismatchIssue {
|
||||
@@ -235,6 +236,10 @@ export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) {
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{!props.draftId ? (
|
||||
<ThreadAutomationsPanel environmentId={props.environmentId} threadId={props.threadId} />
|
||||
) : null}
|
||||
|
||||
{!props.draftId ? (
|
||||
<ThreadRelationshipsPanel environmentId={props.environmentId} threadId={props.threadId} />
|
||||
) : null}
|
||||
|
||||
@@ -0,0 +1,740 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { Clock3Icon, PencilIcon, PlayIcon, PlusIcon, Trash2Icon } from "lucide-react";
|
||||
import { type ReactNode, useCallback, useEffect, useMemo, useState } from "react";
|
||||
import type {
|
||||
ModelSelection,
|
||||
OrchestrationV2ThreadLaunchWorkspaceStrategy,
|
||||
ProjectId,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
ScheduledTask,
|
||||
ScheduledTaskId,
|
||||
ScheduledTaskSchedule,
|
||||
ScheduledTaskUpsertInput,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { ProviderInstanceId } from "@t3tools/contracts";
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
|
||||
import { cn } from "../../lib/utils";
|
||||
import { formatRelativeTime } from "../../timestampFormat";
|
||||
import { usePrimarySettings } from "../../hooks/useSettings";
|
||||
import { getCustomModelOptionsByInstance } from "../../modelSelection";
|
||||
import {
|
||||
applyProviderInstanceSettings,
|
||||
deriveProviderInstanceEntries,
|
||||
sortProviderInstanceEntries,
|
||||
} from "../../providerInstances";
|
||||
import { usePrimaryEnvironment } from "../../state/environments";
|
||||
import { useProjects } from "../../state/entities";
|
||||
import { useEnvironmentQuery } from "../../state/query";
|
||||
import { primaryServerProvidersAtom, serverEnvironment } from "../../state/server";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { ProviderModelPicker } from "../chat/ProviderModelPicker";
|
||||
import { Badge } from "../ui/badge";
|
||||
import { Button } from "../ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogPanel,
|
||||
DialogPopup,
|
||||
DialogTitle,
|
||||
} from "../ui/dialog";
|
||||
import { Input } from "../ui/input";
|
||||
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
|
||||
import { Switch } from "../ui/switch";
|
||||
import { Textarea } from "../ui/textarea";
|
||||
import { stackedThreadToast, toastManager } from "../ui/toast";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import { SettingsPageContainer, SettingsSection, useRelativeTimeTick } from "./settingsLayout";
|
||||
|
||||
type ScheduleMode = "fixed" | "interval";
|
||||
type WorkspaceMode = "root" | "worktree" | "existing_worktree";
|
||||
|
||||
interface DraftState {
|
||||
readonly editingId: string | null;
|
||||
readonly title: string;
|
||||
readonly prompt: string;
|
||||
readonly enabled: boolean;
|
||||
readonly scheduleMode: ScheduleMode;
|
||||
readonly intervalMinutes: string;
|
||||
readonly timeOfDay: string;
|
||||
readonly weekdays: ReadonlySet<number>;
|
||||
readonly projectId: string;
|
||||
readonly threadId: string;
|
||||
readonly workspaceMode: WorkspaceMode;
|
||||
readonly baseRef: string;
|
||||
readonly existingWorktreePath: string;
|
||||
readonly modelKey: string;
|
||||
/** Not editable in the dialog, but preserved so editing an agent-created task keeps its modes. */
|
||||
readonly runtimeMode: RuntimeMode;
|
||||
readonly interactionMode: ProviderInteractionMode;
|
||||
/**
|
||||
* The task's original model selection. The picker only edits
|
||||
* `instanceId:model`; keeping the source object preserves provider options
|
||||
* (reasoning, temperature, …) when the model itself is left unchanged.
|
||||
*/
|
||||
readonly baseModelSelection: ModelSelection | null;
|
||||
}
|
||||
|
||||
/** JS day-of-week (0 = Sunday) rendered Monday-first, matching how people read a week. */
|
||||
const WEEKDAY_ORDER = [1, 2, 3, 4, 5, 6, 0] as const;
|
||||
const WEEKDAY_LABELS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] as const;
|
||||
const WEEKDAY_SHORT = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] as const;
|
||||
const ALL_WEEKDAYS: ReadonlySet<number> = new Set([0, 1, 2, 3, 4, 5, 6]);
|
||||
|
||||
const WORKSPACE_MODE_LABELS: Record<WorkspaceMode, string> = {
|
||||
worktree: "Create a new worktree",
|
||||
root: "Use the project checkout",
|
||||
existing_worktree: "Use a specific checkout",
|
||||
};
|
||||
|
||||
const EMPTY_DRAFT: DraftState = {
|
||||
editingId: null,
|
||||
title: "",
|
||||
prompt: "",
|
||||
enabled: true,
|
||||
scheduleMode: "fixed",
|
||||
intervalMinutes: "15",
|
||||
timeOfDay: "09:00",
|
||||
weekdays: new Set([1, 2, 3, 4, 5]),
|
||||
projectId: "",
|
||||
threadId: "",
|
||||
workspaceMode: "worktree",
|
||||
baseRef: "main",
|
||||
existingWorktreePath: "",
|
||||
modelKey: "",
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
baseModelSelection: null,
|
||||
};
|
||||
|
||||
/** Labelled field: a caption sitting above its control. */
|
||||
function Field({
|
||||
label,
|
||||
hint,
|
||||
htmlFor,
|
||||
children,
|
||||
}: {
|
||||
label: string;
|
||||
hint?: string;
|
||||
htmlFor?: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-1.5">
|
||||
<label
|
||||
className="flex items-baseline justify-between gap-2 text-xs font-medium text-foreground"
|
||||
htmlFor={htmlFor}
|
||||
>
|
||||
<span>{label}</span>
|
||||
{hint ? (
|
||||
<span className="font-normal text-[11px] text-muted-foreground/80">{hint}</span>
|
||||
) : null}
|
||||
</label>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function modelKey(selection: ModelSelection): string {
|
||||
return `${selection.instanceId}:${selection.model}`;
|
||||
}
|
||||
|
||||
function splitModelKey(value: string): ModelSelection | null {
|
||||
const index = value.indexOf(":");
|
||||
if (index <= 0 || index === value.length - 1) return null;
|
||||
return {
|
||||
instanceId: ProviderInstanceId.make(value.slice(0, index)),
|
||||
model: value.slice(index + 1),
|
||||
};
|
||||
}
|
||||
|
||||
function scheduleFromDraft(draft: DraftState): ScheduledTaskSchedule {
|
||||
if (draft.scheduleMode === "interval") {
|
||||
const minutes = Math.max(1, Number.parseInt(draft.intervalMinutes, 10) || 1);
|
||||
return { type: "interval", everyMs: minutes * 60_000 };
|
||||
}
|
||||
const selectedEveryDay = draft.weekdays.size === 0 || draft.weekdays.size === 7;
|
||||
return {
|
||||
type: "fixed_time",
|
||||
timeOfDay: draft.timeOfDay || "09:00",
|
||||
...(selectedEveryDay ? {} : { weekdays: [...draft.weekdays].toSorted() }),
|
||||
};
|
||||
}
|
||||
|
||||
export function scheduleLabel(schedule: ScheduledTaskSchedule): string {
|
||||
if (schedule.type === "interval") {
|
||||
const minutes = schedule.everyMs / 60_000;
|
||||
return Number.isInteger(minutes)
|
||||
? `Every ${minutes} min`
|
||||
: `Every ${Math.round(schedule.everyMs / 1000)} sec`;
|
||||
}
|
||||
const weekdays = schedule.weekdays ?? [];
|
||||
const days =
|
||||
weekdays.length === 0
|
||||
? "Daily"
|
||||
: weekdays.length === 5 && weekdays.every((day) => day >= 1 && day <= 5)
|
||||
? "Weekdays"
|
||||
: weekdays.map((day) => WEEKDAY_LABELS[day]).join(", ");
|
||||
return `${days} at ${schedule.timeOfDay}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Human label for a run timestamp. `formatRelativeTime` only handles the
|
||||
* past, and `nextRunAt` is a future instant — render "in 5m" style labels
|
||||
* for upcoming runs instead of a misleading "just now".
|
||||
*/
|
||||
export function relativeLabel(value: string | null): string {
|
||||
if (!value) return "Not scheduled";
|
||||
const diffMs = new Date(value).getTime() - Date.now();
|
||||
if (diffMs <= 0) {
|
||||
const relative = formatRelativeTime(value);
|
||||
return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
|
||||
}
|
||||
const minutes = Math.ceil(diffMs / 60_000);
|
||||
if (minutes < 2) return "in under a minute";
|
||||
if (minutes < 60) return `in ${minutes}m`;
|
||||
const hours = Math.round(minutes / 60);
|
||||
if (hours < 24) return `in ${hours}h`;
|
||||
return `in ${Math.round(hours / 24)}d`;
|
||||
}
|
||||
|
||||
function taskToDraft(task: ScheduledTask): DraftState {
|
||||
const schedule = task.schedule;
|
||||
const weekdays =
|
||||
schedule.type === "fixed_time" && schedule.weekdays && schedule.weekdays.length > 0
|
||||
? new Set(schedule.weekdays)
|
||||
: new Set(ALL_WEEKDAYS);
|
||||
return {
|
||||
editingId: task.id,
|
||||
title: task.title,
|
||||
prompt: task.prompt,
|
||||
enabled: task.enabled,
|
||||
scheduleMode: schedule.type === "interval" ? "interval" : "fixed",
|
||||
intervalMinutes:
|
||||
schedule.type === "interval"
|
||||
? String(Math.max(1, Math.round(schedule.everyMs / 60_000)))
|
||||
: "15",
|
||||
timeOfDay: schedule.type === "fixed_time" ? schedule.timeOfDay : "09:00",
|
||||
weekdays,
|
||||
projectId: task.projectId,
|
||||
threadId: task.threadId ?? "",
|
||||
workspaceMode: task.workspaceStrategy.type,
|
||||
baseRef: task.workspaceStrategy.type === "worktree" ? task.workspaceStrategy.baseRef : "main",
|
||||
existingWorktreePath:
|
||||
task.workspaceStrategy.type === "existing_worktree"
|
||||
? task.workspaceStrategy.worktreePath
|
||||
: "",
|
||||
modelKey: modelKey(task.modelSelection),
|
||||
runtimeMode: task.runtimeMode,
|
||||
interactionMode: task.interactionMode,
|
||||
baseModelSelection: task.modelSelection,
|
||||
};
|
||||
}
|
||||
|
||||
function statusVariant(status: ScheduledTask["lastRunStatus"]) {
|
||||
if (status === "failed") return "error";
|
||||
if (status === "succeeded") return "success";
|
||||
if (status === "running") return "info";
|
||||
return "outline";
|
||||
}
|
||||
|
||||
export function ScheduledTasksSettings() {
|
||||
useRelativeTimeTick(15_000);
|
||||
const environment = usePrimaryEnvironment();
|
||||
const projects = useProjects();
|
||||
const settings = usePrimarySettings();
|
||||
const providers = useAtomValue(primaryServerProvidersAtom);
|
||||
// Live subscription: the server pushes a fresh list after every change
|
||||
// (CRUD, run transitions, reschedules), so no manual refresh is needed.
|
||||
const tasksQuery = useEnvironmentQuery(
|
||||
environment
|
||||
? serverEnvironment.scheduledTasksLive({
|
||||
environmentId: environment.environmentId,
|
||||
input: {},
|
||||
})
|
||||
: null,
|
||||
);
|
||||
const upsertTask = useAtomCommand(serverEnvironment.upsertScheduledTask, {
|
||||
label: "scheduled task upsert",
|
||||
});
|
||||
const deleteTask = useAtomCommand(serverEnvironment.deleteScheduledTask, {
|
||||
label: "scheduled task delete",
|
||||
});
|
||||
const runTaskNow = useAtomCommand(serverEnvironment.runScheduledTaskNow, {
|
||||
label: "scheduled task run now",
|
||||
});
|
||||
const instanceEntries = useMemo(
|
||||
() =>
|
||||
sortProviderInstanceEntries(
|
||||
applyProviderInstanceSettings(deriveProviderInstanceEntries(providers), settings),
|
||||
),
|
||||
[providers, settings],
|
||||
);
|
||||
const [draft, setDraft] = useState<DraftState>(() => EMPTY_DRAFT);
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const tasks = tasksQuery.data?.tasks ?? [];
|
||||
const selectedProjectTitle = projects.find((project) => project.id === draft.projectId)?.title;
|
||||
|
||||
// The real model picker is keyed by a `${instanceId}:${model}` string, which
|
||||
// is exactly how the draft stores its selection.
|
||||
const firstInstance = instanceEntries[0];
|
||||
const defaultModelKey =
|
||||
firstInstance && firstInstance.models[0]
|
||||
? `${firstInstance.instanceId}:${firstInstance.models[0].slug}`
|
||||
: "";
|
||||
const activeSelection = splitModelKey(draft.modelKey || defaultModelKey);
|
||||
const activeInstanceId =
|
||||
activeSelection?.instanceId ?? firstInstance?.instanceId ?? ("" as ProviderInstanceId);
|
||||
const activeModel = activeSelection?.model ?? "";
|
||||
const modelOptionsByInstance = useMemo(
|
||||
() => getCustomModelOptionsByInstance(settings, providers, activeInstanceId, activeModel),
|
||||
[settings, providers, activeInstanceId, activeModel],
|
||||
);
|
||||
|
||||
const openForCreate = useCallback(() => {
|
||||
setDraft({
|
||||
...EMPTY_DRAFT,
|
||||
projectId: projects[0]?.id ?? "",
|
||||
modelKey: defaultModelKey,
|
||||
});
|
||||
setDialogOpen(true);
|
||||
}, [defaultModelKey, projects]);
|
||||
|
||||
const openForEdit = useCallback((task: ScheduledTask) => {
|
||||
setDraft(taskToDraft(task));
|
||||
setDialogOpen(true);
|
||||
}, []);
|
||||
|
||||
const reportFailure = (title: string, error: unknown) => {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title,
|
||||
description: error instanceof Error ? error.message : String(error),
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const submit = useCallback(async () => {
|
||||
if (!environment || saving) return;
|
||||
const selection = splitModelKey(draft.modelKey || defaultModelKey);
|
||||
if (!draft.title.trim() || !draft.prompt.trim() || !draft.projectId || selection === null) {
|
||||
reportFailure("Schedule task is incomplete", "Add a title, prompt, project, and model.");
|
||||
return;
|
||||
}
|
||||
// Keep the original selection object (with provider options) when the
|
||||
// picker still points at the same instance+model.
|
||||
const modelSelection =
|
||||
draft.baseModelSelection !== null &&
|
||||
draft.baseModelSelection.instanceId === selection.instanceId &&
|
||||
draft.baseModelSelection.model === selection.model
|
||||
? draft.baseModelSelection
|
||||
: selection;
|
||||
const workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy =
|
||||
draft.workspaceMode === "root"
|
||||
? { type: "root" }
|
||||
: draft.workspaceMode === "existing_worktree"
|
||||
? { type: "existing_worktree", worktreePath: draft.existingWorktreePath.trim() }
|
||||
: { type: "worktree", baseRef: draft.baseRef.trim() || "main", startFromOrigin: true };
|
||||
const input: ScheduledTaskUpsertInput = {
|
||||
...(draft.editingId ? { id: draft.editingId as ScheduledTaskId } : {}),
|
||||
title: draft.title.trim(),
|
||||
prompt: draft.prompt.trim(),
|
||||
enabled: draft.enabled,
|
||||
schedule: scheduleFromDraft(draft),
|
||||
projectId: draft.projectId as ProjectId,
|
||||
threadId: draft.threadId ? (draft.threadId as ThreadId) : null,
|
||||
workspaceStrategy,
|
||||
modelSelection,
|
||||
runtimeMode: draft.runtimeMode,
|
||||
interactionMode: draft.interactionMode,
|
||||
creationSource: "web",
|
||||
};
|
||||
setSaving(true);
|
||||
const result = await upsertTask({ environmentId: environment.environmentId, input });
|
||||
setSaving(false);
|
||||
if (result._tag === "Failure") {
|
||||
if (!isAtomCommandInterrupted(result)) {
|
||||
reportFailure("Could not save schedule task", squashAtomCommandFailure(result));
|
||||
}
|
||||
return;
|
||||
}
|
||||
setDialogOpen(false);
|
||||
}, [defaultModelKey, draft, environment, saving, upsertTask]);
|
||||
|
||||
const handleDelete = useCallback(
|
||||
async (task: ScheduledTask) => {
|
||||
if (!environment) return;
|
||||
const result = await deleteTask({
|
||||
environmentId: environment.environmentId,
|
||||
input: { id: task.id },
|
||||
});
|
||||
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
|
||||
reportFailure("Could not delete schedule task", squashAtomCommandFailure(result));
|
||||
}
|
||||
},
|
||||
[deleteTask, environment],
|
||||
);
|
||||
|
||||
const handleRunNow = useCallback(
|
||||
async (task: ScheduledTask) => {
|
||||
if (!environment) return;
|
||||
const result = await runTaskNow({
|
||||
environmentId: environment.environmentId,
|
||||
input: { id: task.id },
|
||||
});
|
||||
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
|
||||
reportFailure("Could not run schedule task", squashAtomCommandFailure(result));
|
||||
}
|
||||
},
|
||||
[environment, runTaskNow],
|
||||
);
|
||||
|
||||
// Keep the draft pointed at a real project once projects load, so a freshly
|
||||
// opened dialog is never stuck on an empty project select.
|
||||
useEffect(() => {
|
||||
if (draft.projectId || projects.length === 0) return;
|
||||
setDraft((current) => ({
|
||||
...current,
|
||||
projectId: projects[0]?.id ?? "",
|
||||
modelKey: current.modelKey || defaultModelKey,
|
||||
}));
|
||||
}, [defaultModelKey, draft.projectId, projects]);
|
||||
|
||||
return (
|
||||
<SettingsPageContainer className="max-w-3xl">
|
||||
<SettingsSection
|
||||
title="Schedule Tasks"
|
||||
icon={<Clock3Icon className="size-3.5" />}
|
||||
headerAction={
|
||||
<Button size="xs" variant="outline" onClick={openForCreate}>
|
||||
<PlusIcon className="size-3.5" />
|
||||
New
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{tasksQuery.error ? (
|
||||
<div className="px-5 py-4 text-xs text-destructive">{tasksQuery.error}</div>
|
||||
) : tasks.length === 0 ? (
|
||||
<div className="flex flex-col items-center gap-3 px-5 py-12 text-center">
|
||||
<div className="grid size-10 place-items-center rounded-full border border-border/70 bg-muted/40 text-muted-foreground">
|
||||
<Clock3Icon className="size-4.5" />
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium text-foreground">No schedule tasks yet</p>
|
||||
<p className="mx-auto max-w-xs text-xs text-muted-foreground">
|
||||
Create one to run a prompt on a schedule — on an interval or at a fixed time.
|
||||
</p>
|
||||
</div>
|
||||
<Button size="sm" onClick={openForCreate}>
|
||||
<PlusIcon className="size-3.5" />
|
||||
New task
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="divide-y divide-border/60">
|
||||
{tasks.map((task) => (
|
||||
<div key={task.id} className="grid gap-3 px-5 py-4 sm:grid-cols-[minmax(0,1fr)_auto]">
|
||||
<div className="min-w-0 space-y-2">
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-2">
|
||||
<h3 className="truncate text-sm font-semibold text-foreground">{task.title}</h3>
|
||||
<Badge variant={task.enabled ? "success" : "outline"}>
|
||||
{task.enabled ? "Enabled" : "Paused"}
|
||||
</Badge>
|
||||
<Badge variant={statusVariant(task.lastRunStatus)}>{task.lastRunStatus}</Badge>
|
||||
</div>
|
||||
<p className="line-clamp-2 text-xs text-muted-foreground">{task.prompt}</p>
|
||||
<div className="flex flex-wrap gap-x-4 gap-y-1 text-[11px] text-muted-foreground/80">
|
||||
<span>{scheduleLabel(task.schedule)}</span>
|
||||
<span>Next: {relativeLabel(task.nextRunAt)}</span>
|
||||
<span>Runs: {task.runCount}</span>
|
||||
</div>
|
||||
{task.lastRunError ? (
|
||||
<p className="text-[11px] text-destructive">{task.lastRunError}</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex items-start gap-1">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
size="icon-sm"
|
||||
variant="ghost"
|
||||
aria-label={`Run ${task.title}`}
|
||||
onClick={() => void handleRunNow(task)}
|
||||
>
|
||||
<PlayIcon className="size-4" />
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup>Run now</TooltipPopup>
|
||||
</Tooltip>
|
||||
<Button
|
||||
size="icon-sm"
|
||||
variant="ghost"
|
||||
aria-label={`Edit ${task.title}`}
|
||||
onClick={() => openForEdit(task)}
|
||||
>
|
||||
<PencilIcon className="size-4" />
|
||||
</Button>
|
||||
<Button
|
||||
size="icon-sm"
|
||||
variant="ghost"
|
||||
aria-label={`Delete ${task.title}`}
|
||||
onClick={() => void handleDelete(task)}
|
||||
>
|
||||
<Trash2Icon className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</SettingsSection>
|
||||
|
||||
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||
<DialogPopup className="max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{draft.editingId ? "Edit task" : "New task"}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Run a prompt automatically — on an interval or at a fixed time.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<DialogPanel className="space-y-5">
|
||||
<Field label="Name" htmlFor="scheduled-task-title">
|
||||
<Input
|
||||
id="scheduled-task-title"
|
||||
placeholder="e.g. Check for Sentry issues"
|
||||
value={draft.title}
|
||||
onChange={(event) =>
|
||||
setDraft((current) => ({ ...current, title: event.target.value }))
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<Field label="Project">
|
||||
<Select
|
||||
value={draft.projectId}
|
||||
onValueChange={(projectId) =>
|
||||
setDraft((current) => ({ ...current, projectId: projectId ?? "" }))
|
||||
}
|
||||
>
|
||||
<SelectTrigger size="sm">
|
||||
<SelectValue placeholder="Select a project">{selectedProjectTitle}</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectPopup>
|
||||
{projects.map((project) => (
|
||||
<SelectItem key={project.id} value={project.id}>
|
||||
{project.title}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
</Field>
|
||||
|
||||
<Field label="Workspace">
|
||||
<Select
|
||||
value={draft.workspaceMode}
|
||||
onValueChange={(value) =>
|
||||
setDraft((current) => ({ ...current, workspaceMode: value as WorkspaceMode }))
|
||||
}
|
||||
>
|
||||
<SelectTrigger size="sm">
|
||||
<SelectValue>{WORKSPACE_MODE_LABELS[draft.workspaceMode]}</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectPopup>
|
||||
<SelectItem value="worktree">Create a new worktree</SelectItem>
|
||||
<SelectItem value="root">Use the project checkout</SelectItem>
|
||||
<SelectItem value="existing_worktree">Use a specific checkout</SelectItem>
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
</Field>
|
||||
</div>
|
||||
|
||||
{draft.workspaceMode === "worktree" ? (
|
||||
<Field label="Base ref" htmlFor="scheduled-task-base-ref">
|
||||
<Input
|
||||
id="scheduled-task-base-ref"
|
||||
value={draft.baseRef}
|
||||
placeholder="main"
|
||||
onChange={(event) =>
|
||||
setDraft((current) => ({ ...current, baseRef: event.target.value }))
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
) : null}
|
||||
{draft.workspaceMode === "existing_worktree" ? (
|
||||
<Field label="Checkout path" htmlFor="scheduled-task-checkout">
|
||||
<Input
|
||||
id="scheduled-task-checkout"
|
||||
value={draft.existingWorktreePath}
|
||||
placeholder="/path/to/checkout"
|
||||
onChange={(event) =>
|
||||
setDraft((current) => ({
|
||||
...current,
|
||||
existingWorktreePath: event.target.value,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
) : null}
|
||||
|
||||
<Field label="Prompt" htmlFor="scheduled-task-prompt">
|
||||
<Textarea
|
||||
id="scheduled-task-prompt"
|
||||
placeholder="What should the agent do each time this runs?"
|
||||
value={draft.prompt}
|
||||
onChange={(event) =>
|
||||
setDraft((current) => ({ ...current, prompt: event.target.value }))
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Field label="Model">
|
||||
<ProviderModelPicker
|
||||
activeInstanceId={activeInstanceId}
|
||||
model={activeModel}
|
||||
lockedProvider={null}
|
||||
instanceEntries={instanceEntries}
|
||||
modelOptionsByInstance={modelOptionsByInstance}
|
||||
triggerVariant="outline"
|
||||
triggerClassName="w-full max-w-none justify-between text-foreground/90 hover:text-foreground"
|
||||
onInstanceModelChange={(instanceId, model) =>
|
||||
setDraft((current) => ({ ...current, modelKey: `${instanceId}:${model}` }))
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="text-xs font-medium text-foreground">Schedule</span>
|
||||
<div className="inline-flex items-center gap-0.5 rounded-lg border border-border/70 bg-muted/40 p-0.5">
|
||||
{(
|
||||
[
|
||||
["fixed", "Daily"],
|
||||
["interval", "Interval"],
|
||||
] as const
|
||||
).map(([mode, label]) => (
|
||||
<button
|
||||
key={mode}
|
||||
type="button"
|
||||
aria-pressed={draft.scheduleMode === mode}
|
||||
className={cn(
|
||||
"rounded-md px-2.5 py-1 text-xs font-medium transition-colors",
|
||||
draft.scheduleMode === mode
|
||||
? "bg-background text-foreground shadow-xs"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
onClick={() => setDraft((current) => ({ ...current, scheduleMode: mode }))}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{draft.scheduleMode === "fixed" ? (
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground">Run at</span>
|
||||
<Input
|
||||
type="time"
|
||||
nativeInput
|
||||
className="w-32"
|
||||
value={draft.timeOfDay}
|
||||
onChange={(event) =>
|
||||
setDraft((current) => ({ ...current, timeOfDay: event.target.value }))
|
||||
}
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">on</span>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{WEEKDAY_ORDER.map((day) => {
|
||||
const selected = draft.weekdays.has(day);
|
||||
return (
|
||||
<button
|
||||
key={day}
|
||||
type="button"
|
||||
aria-pressed={selected}
|
||||
aria-label={WEEKDAY_LABELS[day]}
|
||||
className={cn(
|
||||
"grid size-8 place-items-center rounded-full border text-[11px] font-semibold transition-colors",
|
||||
selected
|
||||
? "border-primary bg-primary text-primary-foreground shadow-xs"
|
||||
: "border-border text-muted-foreground hover:bg-accent hover:text-foreground",
|
||||
)}
|
||||
onClick={() =>
|
||||
setDraft((current) => {
|
||||
const weekdays = new Set(current.weekdays);
|
||||
if (weekdays.has(day)) {
|
||||
// Keep at least one day selected: an empty set
|
||||
// would silently persist as a daily schedule.
|
||||
if (weekdays.size === 1) return current;
|
||||
weekdays.delete(day);
|
||||
} else {
|
||||
weekdays.add(day);
|
||||
}
|
||||
return { ...current, weekdays };
|
||||
})
|
||||
}
|
||||
>
|
||||
{WEEKDAY_SHORT[day]}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground">Run every</span>
|
||||
<Input
|
||||
type="number"
|
||||
nativeInput
|
||||
min={1}
|
||||
className="w-24"
|
||||
value={draft.intervalMinutes}
|
||||
onChange={(event) =>
|
||||
setDraft((current) => ({ ...current, intervalMinutes: event.target.value }))
|
||||
}
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">minutes</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between gap-3 rounded-lg border border-border/60 bg-muted/20 px-3 py-2.5">
|
||||
<div className="min-w-0">
|
||||
<div className="text-xs font-medium">Enabled</div>
|
||||
<div className="text-[11px] text-muted-foreground">
|
||||
Disabled tasks stay saved but do not run.
|
||||
</div>
|
||||
</div>
|
||||
<Switch
|
||||
checked={draft.enabled}
|
||||
onCheckedChange={(enabled) => setDraft((current) => ({ ...current, enabled }))}
|
||||
/>
|
||||
</div>
|
||||
</DialogPanel>
|
||||
|
||||
<DialogFooter>
|
||||
<DialogClose render={<Button variant="outline" size="sm" />}>Cancel</DialogClose>
|
||||
<Button size="sm" disabled={saving} onClick={() => void submit()}>
|
||||
{draft.editingId ? "Save task" : "Create task"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
</SettingsPageContainer>
|
||||
);
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
ArchiveIcon,
|
||||
ArrowLeftIcon,
|
||||
BotIcon,
|
||||
CalendarClockIcon,
|
||||
GitBranchIcon,
|
||||
KeyboardIcon,
|
||||
Link2Icon,
|
||||
@@ -51,6 +52,7 @@ const SETTINGS_SECTION_ICONS: Readonly<
|
||||
"/settings/providers": BotIcon,
|
||||
"/settings/source-control": GitBranchIcon,
|
||||
"/settings/connections": Link2Icon,
|
||||
"/settings/scheduled-tasks": CalendarClockIcon,
|
||||
"/settings/archived": ArchiveIcon,
|
||||
};
|
||||
|
||||
@@ -58,16 +60,15 @@ export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
|
||||
label: string;
|
||||
to: SettingsPath;
|
||||
icon: ComponentType<{ className?: string }>;
|
||||
}> = (Object.keys(SETTINGS_SECTION_LABELS) as SettingsPath[]).map((to) => ({
|
||||
to,
|
||||
label: SETTINGS_SECTION_LABELS[to],
|
||||
icon: SETTINGS_SECTION_ICONS[to],
|
||||
}));
|
||||
|
||||
function SettingsSectionIcon({ to }: { to: SettingsPath }) {
|
||||
const Icon = SETTINGS_SECTION_ICONS[to];
|
||||
return <Icon className="mt-0.5 size-3.5 shrink-0 text-sidebar-muted-foreground/60" />;
|
||||
}
|
||||
}> = [
|
||||
{ label: "General", to: "/settings/general", icon: Settings2Icon },
|
||||
{ label: "Keybindings", to: "/settings/keybindings", icon: KeyboardIcon },
|
||||
{ label: "Providers", to: "/settings/providers", icon: BotIcon },
|
||||
{ label: "Schedule Tasks", to: "/settings/scheduled-tasks", icon: CalendarClockIcon },
|
||||
{ label: "Source Control", to: "/settings/source-control", icon: GitBranchIcon },
|
||||
{ label: "Connections", to: "/settings/connections", icon: Link2Icon },
|
||||
{ label: "Archive", to: "/settings/archived", icon: ArchiveIcon },
|
||||
];
|
||||
|
||||
export function SettingsSidebarNav({ pathname }: { pathname: string }) {
|
||||
const navigate = useNavigate();
|
||||
|
||||
@@ -3,6 +3,7 @@ export type SettingsPath =
|
||||
| "/settings/appearance"
|
||||
| "/settings/keybindings"
|
||||
| "/settings/providers"
|
||||
| "/settings/scheduled-tasks"
|
||||
| "/settings/source-control"
|
||||
| "/settings/connections"
|
||||
| "/settings/archived";
|
||||
|
||||
@@ -16,6 +16,7 @@ import { Route as ConnectRouteImport } from './routes/connect'
|
||||
import { Route as ChatRouteImport } from './routes/_chat'
|
||||
import { Route as ChatIndexRouteImport } from './routes/_chat.index'
|
||||
import { Route as SettingsSourceControlRouteImport } from './routes/settings.source-control'
|
||||
import { Route as SettingsScheduledTasksRouteImport } from './routes/settings.scheduled-tasks'
|
||||
import { Route as SettingsProvidersRouteImport } from './routes/settings.providers'
|
||||
import { Route as SettingsKeybindingsRouteImport } from './routes/settings.keybindings'
|
||||
import { Route as SettingsGeneralRouteImport } from './routes/settings.general'
|
||||
@@ -67,6 +68,11 @@ const SettingsSourceControlRoute = SettingsSourceControlRouteImport.update({
|
||||
path: '/source-control',
|
||||
getParentRoute: () => SettingsRoute,
|
||||
} as any)
|
||||
const SettingsScheduledTasksRoute = SettingsScheduledTasksRouteImport.update({
|
||||
id: '/scheduled-tasks',
|
||||
path: '/scheduled-tasks',
|
||||
getParentRoute: () => SettingsRoute,
|
||||
} as any)
|
||||
const SettingsProvidersRoute = SettingsProvidersRouteImport.update({
|
||||
id: '/providers',
|
||||
path: '/providers',
|
||||
@@ -155,6 +161,7 @@ export interface FileRoutesByFullPath {
|
||||
'/settings/general': typeof SettingsGeneralRoute
|
||||
'/settings/keybindings': typeof SettingsKeybindingsRoute
|
||||
'/settings/providers': typeof SettingsProvidersRoute
|
||||
'/settings/scheduled-tasks': typeof SettingsScheduledTasksRoute
|
||||
'/settings/source-control': typeof SettingsSourceControlRoute
|
||||
'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
|
||||
'/draft/$draftId': typeof ChatDraftDraftIdRoute
|
||||
@@ -178,6 +185,7 @@ export interface FileRoutesByTo {
|
||||
'/settings/general': typeof SettingsGeneralRoute
|
||||
'/settings/keybindings': typeof SettingsKeybindingsRoute
|
||||
'/settings/providers': typeof SettingsProvidersRoute
|
||||
'/settings/scheduled-tasks': typeof SettingsScheduledTasksRoute
|
||||
'/settings/source-control': typeof SettingsSourceControlRoute
|
||||
'/': typeof ChatIndexRoute
|
||||
'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
|
||||
@@ -204,6 +212,7 @@ export interface FileRoutesById {
|
||||
'/settings/general': typeof SettingsGeneralRoute
|
||||
'/settings/keybindings': typeof SettingsKeybindingsRoute
|
||||
'/settings/providers': typeof SettingsProvidersRoute
|
||||
'/settings/scheduled-tasks': typeof SettingsScheduledTasksRoute
|
||||
'/settings/source-control': typeof SettingsSourceControlRoute
|
||||
'/_chat/': typeof ChatIndexRoute
|
||||
'/_chat/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
|
||||
@@ -231,6 +240,7 @@ export interface FileRouteTypes {
|
||||
| '/settings/general'
|
||||
| '/settings/keybindings'
|
||||
| '/settings/providers'
|
||||
| '/settings/scheduled-tasks'
|
||||
| '/settings/source-control'
|
||||
| '/$environmentId/$threadId'
|
||||
| '/draft/$draftId'
|
||||
@@ -254,6 +264,7 @@ export interface FileRouteTypes {
|
||||
| '/settings/general'
|
||||
| '/settings/keybindings'
|
||||
| '/settings/providers'
|
||||
| '/settings/scheduled-tasks'
|
||||
| '/settings/source-control'
|
||||
| '/'
|
||||
| '/$environmentId/$threadId'
|
||||
@@ -279,6 +290,7 @@ export interface FileRouteTypes {
|
||||
| '/settings/general'
|
||||
| '/settings/keybindings'
|
||||
| '/settings/providers'
|
||||
| '/settings/scheduled-tasks'
|
||||
| '/settings/source-control'
|
||||
| '/_chat/'
|
||||
| '/_chat/$environmentId/$threadId'
|
||||
@@ -350,6 +362,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof SettingsSourceControlRouteImport
|
||||
parentRoute: typeof SettingsRoute
|
||||
}
|
||||
'/settings/scheduled-tasks': {
|
||||
id: '/settings/scheduled-tasks'
|
||||
path: '/scheduled-tasks'
|
||||
fullPath: '/settings/scheduled-tasks'
|
||||
preLoaderRoute: typeof SettingsScheduledTasksRouteImport
|
||||
parentRoute: typeof SettingsRoute
|
||||
}
|
||||
'/settings/providers': {
|
||||
id: '/settings/providers'
|
||||
path: '/providers'
|
||||
@@ -469,6 +488,7 @@ interface SettingsRouteChildren {
|
||||
SettingsGeneralRoute: typeof SettingsGeneralRoute
|
||||
SettingsKeybindingsRoute: typeof SettingsKeybindingsRoute
|
||||
SettingsProvidersRoute: typeof SettingsProvidersRoute
|
||||
SettingsScheduledTasksRoute: typeof SettingsScheduledTasksRoute
|
||||
SettingsSourceControlRoute: typeof SettingsSourceControlRoute
|
||||
}
|
||||
|
||||
@@ -480,6 +500,7 @@ const SettingsRouteChildren: SettingsRouteChildren = {
|
||||
SettingsGeneralRoute: SettingsGeneralRoute,
|
||||
SettingsKeybindingsRoute: SettingsKeybindingsRoute,
|
||||
SettingsProvidersRoute: SettingsProvidersRoute,
|
||||
SettingsScheduledTasksRoute: SettingsScheduledTasksRoute,
|
||||
SettingsSourceControlRoute: SettingsSourceControlRoute,
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
|
||||
import { ScheduledTasksSettings } from "../components/settings/ScheduledTasksSettings";
|
||||
|
||||
export const Route = createFileRoute("/settings/scheduled-tasks")({
|
||||
component: ScheduledTasksSettings,
|
||||
});
|
||||
@@ -45,6 +45,7 @@ export type EnvironmentSubscriptionRpcTag =
|
||||
| typeof WS_METHODS.subscribeAuthAccess
|
||||
| typeof WS_METHODS.subscribeServerConfig
|
||||
| typeof WS_METHODS.subscribeServerLifecycle
|
||||
| typeof WS_METHODS.scheduledTasksSubscribe
|
||||
| typeof WS_METHODS.subscribeTerminalEvents
|
||||
| typeof WS_METHODS.subscribeTerminalMetadata
|
||||
| typeof WS_METHODS.subscribePreviewEvents
|
||||
|
||||
@@ -697,15 +697,10 @@ export function createServerEnvironmentAtoms<R, E>(
|
||||
label: "environment-data:server:process-resource-history",
|
||||
tag: WS_METHODS.serverGetProcessResourceHistory,
|
||||
}),
|
||||
resourceTelemetry: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
|
||||
label: "environment-data:server:resource-telemetry",
|
||||
tag: WS_METHODS.subscribeResourceTelemetry,
|
||||
idleTtlMs: 0,
|
||||
}),
|
||||
resourceTelemetryHistory: createEnvironmentRpcQueryAtomFamily(runtime, {
|
||||
label: "environment-data:server:resource-telemetry-history",
|
||||
tag: WS_METHODS.serverGetResourceTelemetryHistory,
|
||||
staleTimeMs: 5_000,
|
||||
/** Live scheduled-task list: snapshot on subscribe, fresh list after every server-side change. */
|
||||
scheduledTasksLive: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
|
||||
label: "environment-data:server:scheduled-tasks:live",
|
||||
tag: WS_METHODS.scheduledTasksSubscribe,
|
||||
}),
|
||||
// A cold transcript scan is measured in seconds, so keep the result around
|
||||
// long enough that switching windows or re-rendering does not rescan.
|
||||
@@ -760,13 +755,30 @@ export function createServerEnvironmentAtoms<R, E>(
|
||||
label: "environment-data:server:signal-process",
|
||||
tag: WS_METHODS.serverSignalProcess,
|
||||
}),
|
||||
retryResourceTelemetry: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:server:retry-resource-telemetry",
|
||||
tag: WS_METHODS.serverRetryResourceTelemetry,
|
||||
concurrency: {
|
||||
mode: "singleFlight",
|
||||
key: ({ environmentId }) => environmentId,
|
||||
},
|
||||
upsertScheduledTask: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:server:scheduled-task:upsert",
|
||||
tag: WS_METHODS.scheduledTasksUpsert,
|
||||
scheduler: configScheduler,
|
||||
concurrency: configConcurrency,
|
||||
}),
|
||||
setScheduledTaskEnabled: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:server:scheduled-task:set-enabled",
|
||||
tag: WS_METHODS.scheduledTasksSetEnabled,
|
||||
scheduler: configScheduler,
|
||||
concurrency: configConcurrency,
|
||||
}),
|
||||
deleteScheduledTask: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:server:scheduled-task:delete",
|
||||
tag: WS_METHODS.scheduledTasksDelete,
|
||||
scheduler: configScheduler,
|
||||
concurrency: configConcurrency,
|
||||
}),
|
||||
// Deliberately not on the config lane: run-now blocks until the run is
|
||||
// dispatched, and a slow run must not stall settings/keybinding/provider
|
||||
// mutations (or other scheduled-task edits) queued behind it.
|
||||
runScheduledTaskNow: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:server:scheduled-task:run-now",
|
||||
tag: WS_METHODS.scheduledTasksRunNow,
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -95,6 +95,8 @@ export const RuntimeRequestId = makeEntityId("RuntimeRequestId");
|
||||
export type RuntimeRequestId = typeof RuntimeRequestId.Type;
|
||||
export const RuntimeTaskId = makeEntityId("RuntimeTaskId");
|
||||
export type RuntimeTaskId = typeof RuntimeTaskId.Type;
|
||||
export const ScheduledTaskId = makeEntityId("ScheduledTaskId");
|
||||
export type ScheduledTaskId = typeof ScheduledTaskId.Type;
|
||||
export const ApprovalRequestId = makeEntityId("ApprovalRequestId");
|
||||
export type ApprovalRequestId = typeof ApprovalRequestId.Type;
|
||||
export const CheckpointRef = makeEntityId("CheckpointRef");
|
||||
|
||||
@@ -37,4 +37,5 @@ export * from "./preview.ts";
|
||||
export * from "./previewAutomation.ts";
|
||||
export * from "./resourceTelemetry.ts";
|
||||
export * from "./usage.ts";
|
||||
export * from "./scheduledTask.ts";
|
||||
export * from "./rpc.ts";
|
||||
@@ -9,10 +9,12 @@ import {
|
||||
PositiveInt,
|
||||
ProjectId,
|
||||
RunId,
|
||||
ScheduledTaskId,
|
||||
ThreadId,
|
||||
TrimmedNonEmptyString,
|
||||
TurnItemId,
|
||||
} from "./baseSchemas.ts";
|
||||
import { ScheduledTaskRunStatus, ScheduledTaskSchedule } from "./scheduledTask.ts";
|
||||
import { ProviderInteractionMode, RuntimeMode } from "./providerPolicy.ts";
|
||||
import {
|
||||
OrchestrationV2Actor,
|
||||
@@ -363,11 +365,74 @@ export const OrchestratorMcpCapabilitiesResult = Schema.Struct({
|
||||
batchThreadCreation: Schema.Boolean,
|
||||
threadManagement: Schema.Boolean,
|
||||
incrementalThreadRead: Schema.Boolean,
|
||||
scheduledTasks: Schema.Boolean,
|
||||
maxBatchThreads: Schema.Number,
|
||||
}),
|
||||
});
|
||||
export type OrchestratorMcpCapabilitiesResult = typeof OrchestratorMcpCapabilitiesResult.Type;
|
||||
|
||||
export const OrchestratorMcpScheduleTaskInput = Schema.Struct({
|
||||
prompt: OrchestratorMcpPrompt,
|
||||
schedule: ScheduledTaskSchedule,
|
||||
title: Schema.optional(OrchestratorMcpTitle),
|
||||
enabled: Schema.optional(Schema.Boolean),
|
||||
/**
|
||||
* When true (the default), the scheduled task fires into the calling thread
|
||||
* on each run instead of launching a fresh thread. This is the recurring
|
||||
* "wake up in this thread" behaviour reserved for agent-created tasks.
|
||||
*/
|
||||
bindToCurrentThread: Schema.optional(Schema.Boolean),
|
||||
clientRequestId: Schema.optional(OrchestratorMcpClientRequestId),
|
||||
});
|
||||
export type OrchestratorMcpScheduleTaskInput = typeof OrchestratorMcpScheduleTaskInput.Type;
|
||||
|
||||
/** Summary of a scheduled task returned by the schedule/list/update tools. */
|
||||
export const OrchestratorMcpScheduledTask = Schema.Struct({
|
||||
scheduledTaskId: ScheduledTaskId,
|
||||
title: Schema.String,
|
||||
prompt: Schema.String,
|
||||
enabled: Schema.Boolean,
|
||||
projectId: ProjectId,
|
||||
boundThreadId: Schema.NullOr(ThreadId),
|
||||
schedule: ScheduledTaskSchedule,
|
||||
nextRunAt: Schema.NullOr(IsoDateTime),
|
||||
lastRunStatus: ScheduledTaskRunStatus,
|
||||
});
|
||||
export type OrchestratorMcpScheduledTask = typeof OrchestratorMcpScheduledTask.Type;
|
||||
|
||||
export const OrchestratorMcpScheduleTaskResult = OrchestratorMcpScheduledTask;
|
||||
export type OrchestratorMcpScheduleTaskResult = typeof OrchestratorMcpScheduleTaskResult.Type;
|
||||
|
||||
export const OrchestratorMcpListScheduledTasksResult = Schema.Struct({
|
||||
tasks: Schema.Array(OrchestratorMcpScheduledTask),
|
||||
});
|
||||
export type OrchestratorMcpListScheduledTasksResult =
|
||||
typeof OrchestratorMcpListScheduledTasksResult.Type;
|
||||
|
||||
export const OrchestratorMcpUpdateScheduledTaskInput = Schema.Struct({
|
||||
scheduledTaskId: ScheduledTaskId,
|
||||
prompt: Schema.optional(OrchestratorMcpPrompt),
|
||||
title: Schema.optional(OrchestratorMcpTitle),
|
||||
schedule: Schema.optional(ScheduledTaskSchedule),
|
||||
enabled: Schema.optional(Schema.Boolean),
|
||||
bindToCurrentThread: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
export type OrchestratorMcpUpdateScheduledTaskInput =
|
||||
typeof OrchestratorMcpUpdateScheduledTaskInput.Type;
|
||||
|
||||
export const OrchestratorMcpDeleteScheduledTaskInput = Schema.Struct({
|
||||
scheduledTaskId: ScheduledTaskId,
|
||||
});
|
||||
export type OrchestratorMcpDeleteScheduledTaskInput =
|
||||
typeof OrchestratorMcpDeleteScheduledTaskInput.Type;
|
||||
|
||||
export const OrchestratorMcpDeleteScheduledTaskResult = Schema.Struct({
|
||||
scheduledTaskId: ScheduledTaskId,
|
||||
deleted: Schema.Boolean,
|
||||
});
|
||||
export type OrchestratorMcpDeleteScheduledTaskResult =
|
||||
typeof OrchestratorMcpDeleteScheduledTaskResult.Type;
|
||||
|
||||
export class OrchestratorMcpFailure extends Schema.TaggedErrorClass<OrchestratorMcpFailure>()(
|
||||
"OrchestratorMcpFailure",
|
||||
{
|
||||
|
||||
@@ -172,6 +172,18 @@ import {
|
||||
} from "./resourceTelemetry.ts";
|
||||
import { UsageReadError, UsageSummary, UsageSummaryInput } from "./usage.ts";
|
||||
import { ServerSettings, ServerSettingsError, ServerSettingsPatch } from "./settings.ts";
|
||||
import {
|
||||
ScheduledTaskDeleteInput,
|
||||
ScheduledTaskDeleteResult,
|
||||
ScheduledTaskError,
|
||||
ScheduledTaskListInput,
|
||||
ScheduledTaskListResult,
|
||||
ScheduledTaskRunNowInput,
|
||||
ScheduledTaskRunNowResult,
|
||||
ScheduledTaskSetEnabledInput,
|
||||
ScheduledTaskUpsertInput,
|
||||
ScheduledTaskMutationResult,
|
||||
} from "./scheduledTask.ts";
|
||||
import {
|
||||
SourceControlCloneRepositoryInput,
|
||||
SourceControlCloneRepositoryResult,
|
||||
@@ -268,6 +280,14 @@ export const WS_METHODS = {
|
||||
serverGetBackgroundPolicy: "server.getBackgroundPolicy",
|
||||
serverGetUsageSummary: "server.getUsageSummary",
|
||||
|
||||
// Scheduled tasks
|
||||
scheduledTasksList: "scheduledTasks.list",
|
||||
scheduledTasksSubscribe: "scheduledTasks.subscribe",
|
||||
scheduledTasksUpsert: "scheduledTasks.upsert",
|
||||
scheduledTasksSetEnabled: "scheduledTasks.setEnabled",
|
||||
scheduledTasksDelete: "scheduledTasks.delete",
|
||||
scheduledTasksRunNow: "scheduledTasks.runNow",
|
||||
|
||||
// Cloud environment methods
|
||||
cloudGetRelayClientStatus: "cloud.getRelayClientStatus",
|
||||
cloudInstallRelayClient: "cloud.installRelayClient",
|
||||
@@ -973,6 +993,44 @@ export const WsSubscribeServerLifecycleRpc = Rpc.make(WS_METHODS.subscribeServer
|
||||
stream: true,
|
||||
});
|
||||
|
||||
export const WsScheduledTasksListRpc = Rpc.make(WS_METHODS.scheduledTasksList, {
|
||||
payload: ScheduledTaskListInput,
|
||||
success: ScheduledTaskListResult,
|
||||
error: Schema.Union([ScheduledTaskError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
/** Streams the full scheduled-task list: one snapshot on subscribe, then a fresh list after every change. */
|
||||
export const WsScheduledTasksSubscribeRpc = Rpc.make(WS_METHODS.scheduledTasksSubscribe, {
|
||||
payload: ScheduledTaskListInput,
|
||||
success: ScheduledTaskListResult,
|
||||
error: Schema.Union([ScheduledTaskError, EnvironmentAuthorizationError]),
|
||||
stream: true,
|
||||
});
|
||||
|
||||
export const WsScheduledTasksUpsertRpc = Rpc.make(WS_METHODS.scheduledTasksUpsert, {
|
||||
payload: ScheduledTaskUpsertInput,
|
||||
success: ScheduledTaskMutationResult,
|
||||
error: Schema.Union([ScheduledTaskError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsScheduledTasksSetEnabledRpc = Rpc.make(WS_METHODS.scheduledTasksSetEnabled, {
|
||||
payload: ScheduledTaskSetEnabledInput,
|
||||
success: ScheduledTaskMutationResult,
|
||||
error: Schema.Union([ScheduledTaskError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsScheduledTasksDeleteRpc = Rpc.make(WS_METHODS.scheduledTasksDelete, {
|
||||
payload: ScheduledTaskDeleteInput,
|
||||
success: ScheduledTaskDeleteResult,
|
||||
error: Schema.Union([ScheduledTaskError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsScheduledTasksRunNowRpc = Rpc.make(WS_METHODS.scheduledTasksRunNow, {
|
||||
payload: ScheduledTaskRunNowInput,
|
||||
success: ScheduledTaskRunNowResult,
|
||||
error: Schema.Union([ScheduledTaskError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsSubscribeAuthAccessRpc = Rpc.make(WS_METHODS.subscribeAuthAccess, {
|
||||
payload: Schema.Struct({}),
|
||||
success: AuthAccessStreamEvent,
|
||||
@@ -1013,9 +1071,12 @@ export const WsRpcGroup = RpcGroup.make(
|
||||
WsServerRetryResourceTelemetryRpc,
|
||||
WsServerGetUsageSummaryRpc,
|
||||
WsServerSignalProcessRpc,
|
||||
WsServerReportClientActivityRpc,
|
||||
WsServerReportHostPowerStateRpc,
|
||||
WsServerGetBackgroundPolicyRpc,
|
||||
WsScheduledTasksListRpc,
|
||||
WsScheduledTasksSubscribeRpc,
|
||||
WsScheduledTasksUpsertRpc,
|
||||
WsScheduledTasksSetEnabledRpc,
|
||||
WsScheduledTasksDeleteRpc,
|
||||
WsScheduledTasksRunNowRpc,
|
||||
WsCloudGetRelayClientStatusRpc,
|
||||
WsCloudInstallRelayClientRpc,
|
||||
WsPullRequestsListRpc,
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
CommandId,
|
||||
IsoDateTime,
|
||||
PositiveInt,
|
||||
ProjectId,
|
||||
ScheduledTaskId,
|
||||
ThreadId,
|
||||
TrimmedNonEmptyString,
|
||||
} from "./baseSchemas.ts";
|
||||
import { ModelSelection } from "./modelSelection.ts";
|
||||
import {
|
||||
OrchestrationV2Actor,
|
||||
OrchestrationV2CreationSource,
|
||||
OrchestrationV2ThreadLaunchWorkspaceStrategy,
|
||||
} from "./orchestrationV2.ts";
|
||||
import { ProviderInteractionMode, RuntimeMode } from "./providerPolicy.ts";
|
||||
|
||||
/** 24-hour "HH:MM" wall-clock time. Mirrors `parseTimeOfDay` on the server. */
|
||||
const TimeOfDay = TrimmedNonEmptyString.check(Schema.isPattern(/^([01]?\d|2[0-3]):([0-5]\d)$/));
|
||||
|
||||
export const ScheduledTaskSchedule = Schema.Union([
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("interval"),
|
||||
everyMs: PositiveInt,
|
||||
}),
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("fixed_time"),
|
||||
timeOfDay: TimeOfDay,
|
||||
weekdays: Schema.optional(
|
||||
Schema.Array(Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 6 }))),
|
||||
),
|
||||
}),
|
||||
]);
|
||||
export type ScheduledTaskSchedule = typeof ScheduledTaskSchedule.Type;
|
||||
|
||||
export const ScheduledTaskRunStatus = Schema.Literals(["never", "running", "succeeded", "failed"]);
|
||||
export type ScheduledTaskRunStatus = typeof ScheduledTaskRunStatus.Type;
|
||||
|
||||
export const ScheduledTask = Schema.Struct({
|
||||
id: ScheduledTaskId,
|
||||
title: TrimmedNonEmptyString,
|
||||
prompt: TrimmedNonEmptyString,
|
||||
enabled: Schema.Boolean,
|
||||
schedule: ScheduledTaskSchedule,
|
||||
projectId: ProjectId,
|
||||
threadId: Schema.NullOr(ThreadId),
|
||||
workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy,
|
||||
modelSelection: ModelSelection,
|
||||
runtimeMode: RuntimeMode,
|
||||
interactionMode: ProviderInteractionMode,
|
||||
createdBy: OrchestrationV2Actor,
|
||||
creationSource: OrchestrationV2CreationSource,
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
nextRunAt: Schema.NullOr(IsoDateTime),
|
||||
lastRunAt: Schema.NullOr(IsoDateTime),
|
||||
lastRunStatus: ScheduledTaskRunStatus,
|
||||
lastRunError: Schema.NullOr(Schema.String),
|
||||
runCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
|
||||
});
|
||||
export type ScheduledTask = typeof ScheduledTask.Type;
|
||||
|
||||
export const ScheduledTaskListInput = Schema.Struct({});
|
||||
export type ScheduledTaskListInput = typeof ScheduledTaskListInput.Type;
|
||||
|
||||
export const ScheduledTaskListResult = Schema.Struct({
|
||||
tasks: Schema.Array(ScheduledTask),
|
||||
});
|
||||
export type ScheduledTaskListResult = typeof ScheduledTaskListResult.Type;
|
||||
|
||||
export const ScheduledTaskUpsertInput = Schema.Struct({
|
||||
id: Schema.optional(ScheduledTaskId),
|
||||
commandId: Schema.optional(CommandId),
|
||||
title: TrimmedNonEmptyString,
|
||||
prompt: TrimmedNonEmptyString,
|
||||
enabled: Schema.Boolean,
|
||||
schedule: ScheduledTaskSchedule,
|
||||
projectId: ProjectId,
|
||||
threadId: Schema.optional(Schema.NullOr(ThreadId)),
|
||||
workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy,
|
||||
modelSelection: ModelSelection,
|
||||
runtimeMode: RuntimeMode,
|
||||
interactionMode: ProviderInteractionMode,
|
||||
createdBy: Schema.optional(OrchestrationV2Actor),
|
||||
creationSource: Schema.optional(OrchestrationV2CreationSource),
|
||||
});
|
||||
export type ScheduledTaskUpsertInput = typeof ScheduledTaskUpsertInput.Type;
|
||||
|
||||
/** Partial update that flips only the enabled flag — never overwrites other fields. */
|
||||
export const ScheduledTaskSetEnabledInput = Schema.Struct({
|
||||
id: ScheduledTaskId,
|
||||
enabled: Schema.Boolean,
|
||||
});
|
||||
export type ScheduledTaskSetEnabledInput = typeof ScheduledTaskSetEnabledInput.Type;
|
||||
|
||||
export const ScheduledTaskDeleteInput = Schema.Struct({
|
||||
id: ScheduledTaskId,
|
||||
});
|
||||
export type ScheduledTaskDeleteInput = typeof ScheduledTaskDeleteInput.Type;
|
||||
|
||||
export const ScheduledTaskRunNowInput = Schema.Struct({
|
||||
id: ScheduledTaskId,
|
||||
});
|
||||
export type ScheduledTaskRunNowInput = typeof ScheduledTaskRunNowInput.Type;
|
||||
|
||||
export const ScheduledTaskMutationResult = Schema.Struct({
|
||||
task: ScheduledTask,
|
||||
});
|
||||
export type ScheduledTaskMutationResult = typeof ScheduledTaskMutationResult.Type;
|
||||
|
||||
export const ScheduledTaskDeleteResult = Schema.Struct({
|
||||
id: ScheduledTaskId,
|
||||
});
|
||||
export type ScheduledTaskDeleteResult = typeof ScheduledTaskDeleteResult.Type;
|
||||
|
||||
export const ScheduledTaskRunNowResult = Schema.Struct({
|
||||
task: ScheduledTask,
|
||||
});
|
||||
export type ScheduledTaskRunNowResult = typeof ScheduledTaskRunNowResult.Type;
|
||||
|
||||
export class ScheduledTaskError extends Schema.TaggedErrorClass<ScheduledTaskError>()(
|
||||
"ScheduledTaskError",
|
||||
{
|
||||
message: Schema.String,
|
||||
taskId: Schema.optional(ScheduledTaskId),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {}
|
||||
Reference in new issue
Block a user