Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

scheduledTasksSettings.logic.ts

349 lines13.2 KB

1import { isWebhookDedupeTemplate } from "@t3tools/contracts";
2import {
3 EnvironmentId,
4 MAX_WEBHOOK_DELIVERY_AGE_MINUTES,
5 type ProjectId,
6 ScheduledTaskId,
7 type ScheduledTask,
8 type ScheduledTaskUpsertSchedule,
9 type ModelSelection,
10 type RuntimeMode,
11 type ProviderInteractionMode,
12 type ServerSettings,
13} from "@t3tools/contracts";
14import {
15 parseMaxDeliveryAge,
16 parseWebhookFilterDrafts,
17 webhookFilterDrafts,
18 webhookFilterDraftsChanged,
19 type WebhookFilterDraft,
20} from "@t3tools/client-runtime/scheduled-task-webhook";
21​
22import {
23 resolveProjectSettings,
24 type LegacyProjectSettingsFields,
25} from "@t3tools/shared/projectSettings";
26import type { ProviderInstanceEntry } from "../../providerInstances";
27​
28import type { ResolvedSettingsScope } from "./settingsScope";
29​
30export function matchesScheduledTaskScope(
31 scope: ResolvedSettingsScope,
32 environmentId: EnvironmentId,
33 projectId: ProjectId,
34): boolean {
35 if (scope.kind === "unavailable" || !scope.environmentIds.includes(environmentId)) return false;
36 if (scope.kind === "project" || scope.kind === "checkout") {
37 return scope.members.some(
38 (member) => member.environmentId === environmentId && member.id === projectId,
39 );
40 }
41 return true;
43​
44export function validateScheduledTasksSearch(raw: Record<string, unknown>) {
45 return {
46 ...(typeof raw.environmentId === "string" && raw.environmentId.trim()
47 ? { environmentId: EnvironmentId.make(raw.environmentId) }
48 : {}),
49 ...(typeof raw.taskId === "string" && raw.taskId.trim()
50 ? { taskId: ScheduledTaskId.make(raw.taskId) }
51 : {}),
52 };
54​
55export type ScheduleMode = "fixed" | "once" | "interval" | "webhook";
56export type WorkspaceMode = "root" | "worktree" | "existing_worktree";
57​
58export interface DraftState {
59 readonly editingId: string | null;
60 readonly title: string;
61 readonly prompt: string;
62 readonly enabled: boolean;
63 readonly scheduleMode: ScheduleMode;
64 readonly intervalMinutes: string;
65 readonly timeOfDay: string;
66 /** Local date and time as a `datetime-local` input value, such as 2026-11-02T15:00. */
67 readonly runAt: string;
68 /** The stored ISO run time, sent back unchanged when the field was not edited. */
69 readonly savedRunAt: string;
70 readonly weekdays: ReadonlySet<number>;
71 readonly projectId: string;
72 readonly threadId: string;
73 readonly workspaceMode: WorkspaceMode;
74 readonly baseRef: string;
75 readonly startFromOrigin: boolean;
76 readonly existingWorktreePath: string;
77 readonly modelKey: string;
78 readonly runtimeMode: RuntimeMode;
79 readonly interactionMode: ProviderInteractionMode;
80 /** Retain the source selection's provider options when the picker leaves instanceId:model unchanged. */
81 readonly baseModelSelection: ModelSelection | null;
82 readonly signatureEnabled: boolean;
83 readonly signatureHeader: string;
84 readonly signatureEncoding: "hex" | "base64";
85 readonly signaturePrefix: string;
86 /** Write-only: empty keeps the secret already stored on the server. */
87 readonly signatureSecret: string;
88 readonly maxDeliveryAgeMinutes: string;
89 readonly replayKey: string;
90 readonly coalesceKey: string;
91 readonly coalesceWindowSeconds: string;
92 readonly filters: ReadonlyArray<WebhookFilterDraft>;
93 /** The filter rows the form opened with. */
94 readonly savedFilters: ReadonlyArray<WebhookFilterDraft>;
96​
97export const WEBHOOK_SIGNATURE_DEFAULTS = {
98 signatureHeader: "x-hub-signature-256",
99 signatureEncoding: "hex",
100 signaturePrefix: "sha256=",
101} as const;
102​
103/** Formats a date as a `datetime-local` input value in the browser's time zone. */
104export function toDateTimeLocalValue(date: Date): string {
105 const pad = (value: number) => String(value).padStart(2, "0");
106 return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
108​
109export function scheduleDraftErrors(draft: DraftState) {
110 if (draft.scheduleMode === "once") {
111 const runAt = new Date(draft.runAt);
112 if (Number.isNaN(runAt.getTime()))
113 return [{ title: "Invalid run time", description: "Pick a date and time." }];
114 // A time skipped by a daylight saving change parses to a different clock time.
115 if (toDateTimeLocalValue(runAt) !== draft.runAt)
116 return [
117 { title: "Invalid run time", description: "That time does not exist in your time zone." },
118 ];
119 return [];
120 }
121 if (draft.scheduleMode !== "webhook") return [];
122 if (parseMaxDeliveryAge(draft.maxDeliveryAgeMinutes) === undefined)
123 return [
124 {
125 title: "Invalid age limit",
126 description: `Enter whole minutes from 1 to ${MAX_WEBHOOK_DELIVERY_AGE_MINUTES}, or leave it blank.`,
127 },
128 ];
129 const errors: Array<{ title: string; description: string }> = [];
130 for (const [label, value] of [
131 ["Duplicate request key", draft.replayKey],
132 ["Coalesce key", draft.coalesceKey],
133 ] as const) {
134 if (value.trim() && !isWebhookDedupeTemplate(value.trim()))
135 errors.push({
136 title: "Invalid webhook settings",
137 description: `${label} must contain a valid request placeholder.`,
138 });
139 }
140 const window = draft.coalesceWindowSeconds.trim();
141 if (window && (!Number.isInteger(Number(window)) || Number(window) < 10 || Number(window) > 3600))
142 errors.push({
143 title: "Invalid webhook settings",
144 description: "Coalesce window must be whole seconds from 10 to 3600.",
145 });
146 return errors;
148​
149export function webhookDeliveryLabel(delivery: {
150 readonly outcome: string;
151 readonly pendingWindow?: boolean | undefined;
152}) {
153 if (delivery.outcome === "accepted") return delivery.pendingWindow ? "Opened window" : "Ran";
154 const labels: Record<string, string> = {
155 dispatch_failed: "Run failed",
156 duplicate: "Duplicate",
157 coalesced: "Coalesced",
158 filtered: "Filtered",
159 rejected_signature: "Bad signature",
160 disabled: "Task paused",
161 rate_limited: "Rate limited",
162 expired: "Too old",
163 };
164 return labels[delivery.outcome] ?? delivery.outcome.replaceAll("_", " ");
166​
167export function scheduleFromDraft(draft: DraftState): ScheduledTaskUpsertSchedule | null {
168 if (scheduleDraftErrors(draft).length > 0) return null;
169 if (draft.scheduleMode === "once") {
170 const saved = draft.savedRunAt ? new Date(draft.savedRunAt) : null;
171 if (saved !== null && toDateTimeLocalValue(saved) === draft.runAt)
172 return { type: "once", runAt: draft.savedRunAt };
173 // A `datetime-local` value has no offset. In an hour that repeats when clocks go
174 // back, keep the saved time's offset; otherwise Date reads it as local time.
175 const withSavedOffset =
176 saved === null
177 ? null
178 : new Date(Date.parse(`${draft.runAt}Z`) + saved.getTimezoneOffset() * 60_000);
179 return {
180 type: "once",
181 runAt:
182 withSavedOffset !== null && toDateTimeLocalValue(withSavedOffset) === draft.runAt
183 ? withSavedOffset.toISOString()
184 : new Date(draft.runAt).toISOString(),
185 };
186 }
187 if (draft.scheduleMode === "webhook") {
188 const maxDeliveryAgeMinutes = parseMaxDeliveryAge(draft.maxDeliveryAgeMinutes);
189 const replayKey = draft.replayKey.trim();
190 const coalesceKey = draft.coalesceKey.trim();
191 const coalesceWindowSeconds = draft.coalesceWindowSeconds.trim()
192 ? Number(draft.coalesceWindowSeconds)
193 : undefined;
194 if (maxDeliveryAgeMinutes === undefined) return null;
195 const parsedFilters = parseWebhookFilterDrafts(draft.filters);
196 if (!("filters" in parsedFilters)) return null;
197 const secret = draft.signatureSecret.trim();
198 return {
199 type: "webhook",
200 signature: draft.signatureEnabled
201 ? {
202 header: draft.signatureHeader.trim(),
203 encoding: draft.signatureEncoding,
204 prefix: draft.signaturePrefix,
205 ...(secret ? { secret } : {}),
206 }
207 : null,
208 maxDeliveryAgeMinutes,
209 ...(replayKey || coalesceKey || coalesceWindowSeconds !== undefined
210 ? {
211 dedupe: {
212 ...(replayKey ? { replayKey } : {}),
213 ...(coalesceKey ? { coalesceKey } : {}),
214 ...(coalesceWindowSeconds === undefined ? {} : { coalesceWindowSeconds }),
215 },
216 }
217 : { dedupe: {} }),
218 // Only edited filters are sent; the server keeps the stored ones otherwise.
219 ...(webhookFilterDraftsChanged(draft.savedFilters, draft.filters)
220 ? { filters: parsedFilters.filters }
221 : {}),
222 };
223 }
224 if (draft.scheduleMode === "interval") {
225 const everyMs = Math.round(Number(draft.intervalMinutes) * 60_000);
226 return { type: "interval", everyMs };
227 }
228 const selectedEveryDay = draft.weekdays.size === 0 || draft.weekdays.size === 7;
229 return {
230 type: "fixed_time",
231 timeOfDay: draft.timeOfDay || "09:00",
232 ...(selectedEveryDay ? {} : { weekdays: [...draft.weekdays].toSorted() }),
233 };
235​
236export function taskToDraft(task: ScheduledTask): DraftState {
237 const schedule = task.schedule;
238 const filters = webhookFilterDrafts(schedule.type === "webhook" ? schedule.filters : undefined);
239 const weekdays =
240 schedule.type === "fixed_time" && schedule.weekdays && schedule.weekdays.length > 0
241 ? new Set(schedule.weekdays)
242 : new Set([0, 1, 2, 3, 4, 5, 6]);
243 return {
244 editingId: task.id,
245 title: task.title,
246 prompt: task.prompt,
247 enabled: task.enabled,
248 scheduleMode: schedule.type === "fixed_time" ? "fixed" : schedule.type,
249 intervalMinutes:
250 schedule.type === "interval" ? String(Math.max(1, schedule.everyMs / 60_000)) : "15",
251 timeOfDay: schedule.type === "fixed_time" ? schedule.timeOfDay : "09:00",
252 runAt: schedule.type === "once" ? toDateTimeLocalValue(new Date(schedule.runAt)) : "",
253 savedRunAt: schedule.type === "once" ? schedule.runAt : "",
254 weekdays,
255 projectId: task.projectId,
256 threadId: task.threadId ?? "",
257 workspaceMode: task.workspaceStrategy.type,
258 baseRef: task.workspaceStrategy.type === "worktree" ? task.workspaceStrategy.baseRef : "main",
259 startFromOrigin:
260 task.workspaceStrategy.type === "worktree"
261 ? (task.workspaceStrategy.startFromOrigin ?? false)
262 : true,
263 existingWorktreePath:
264 task.workspaceStrategy.type === "existing_worktree"
265 ? task.workspaceStrategy.worktreePath
266 : "",
267 modelKey: `${task.modelSelection.instanceId}:${task.modelSelection.model}`,
268 runtimeMode: task.runtimeMode,
269 interactionMode: task.interactionMode,
270 baseModelSelection: task.modelSelection,
271 ...(schedule.type === "webhook" && schedule.signature !== null
272 ? {
273 signatureEnabled: true,
274 signatureHeader: schedule.signature.header,
275 signatureEncoding: schedule.signature.encoding,
276 signaturePrefix: schedule.signature.prefix,
277 }
278 : { signatureEnabled: false, ...WEBHOOK_SIGNATURE_DEFAULTS }),
279 signatureSecret: "",
280 replayKey: schedule.type === "webhook" ? (schedule.dedupe?.replayKey ?? "") : "",
281 coalesceKey: schedule.type === "webhook" ? (schedule.dedupe?.coalesceKey ?? "") : "",
282 coalesceWindowSeconds:
283 schedule.type === "webhook" && schedule.dedupe?.coalesceWindowSeconds !== undefined
284 ? String(schedule.dedupe.coalesceWindowSeconds)
285 : "",
286 maxDeliveryAgeMinutes:
287 schedule.type === "webhook" && schedule.maxDeliveryAgeMinutes != null
288 ? String(schedule.maxDeliveryAgeMinutes)
289 : "",
290 filters,
291 savedFilters: filters,
292 };
294​
295export function scheduledTaskDefaultModel(
296 settings: ServerSettings,
297 project: (LegacyProjectSettingsFields & { readonly id: ProjectId }) | null,
298 entries: readonly ProviderInstanceEntry[],
299): ModelSelection | null {
300 const available = entries.filter(
301 (entry) =>
302 entry.enabled &&
303 entry.installed &&
304 entry.isAvailable &&
305 entry.snapshot.auth.status !== "unauthenticated",
306 );
307 const configured = resolveProjectSettings(settings, project?.id ?? null, project).settings
308 .defaultModelSelection;
309 for (const selection of [configured, settings.defaultModelSelection]) {
310 if (
311 selection &&
312 available.some(
313 (entry) =>
314 entry.instanceId === selection.instanceId &&
315 entry.models.find((model) => model.slug === selection.model)?.isLegacy !== true,
316 )
317 )
318 return selection;
319 }
320 const models = available.flatMap((entry) =>
321 entry.models
322 .filter((model) => !model.isLegacy)
323 .map((model) => ({ instanceId: entry.instanceId, model })),
324 );
325 const fallback = models.find(({ model }) => model.isDefault) ?? models[0];
326 return fallback ? { instanceId: fallback.instanceId, model: fallback.model.slug } : null;
328​
329/**
330 * A new task's project: a pinned open project, then any open one. An archived
331 * project only when Settings is scoped to it, so that scope can still save.
332 */
333export function defaultScheduledTaskProjectId<
334 TProject extends {
335 readonly id: ProjectId;
336 readonly pinnedAt?: string | null | undefined;
337 readonly archivedAt?: string | null | undefined;
338 },
339>(scopedProjects: ReadonlyArray<TProject>, scope: ResolvedSettingsScope): ProjectId | "" {
340 const open = scopedProjects.filter((project) => project.archivedAt == null);
341 const scopedToProject = scope.kind === "project" || scope.kind === "checkout";
342 return (
343 (
344 open.find((project) => project.pinnedAt != null) ??
345 open[0] ??
346 (scopedToProject ? scopedProjects[0] : undefined)
347 )?.id ?? ""
348 );