Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Let workflow schedules run on a fixed elapsed interval from an anchor (SKY-16914) (#8660)
Andrew Neilson1c3570727569
diff --git a/alembic/versions/2026_09_25_2219-762d72647b18_add_fixed_interval_cadence_to_workflow_schedules.py b/alembic/versions/2026_09_25_2219-762d72647b18_add_fixed_interval_cadence_to_workflow_schedules.pynew file mode 100644index 000000000..e729f319b--- /dev/null+++ b/alembic/versions/2026_09_25_2219-762d72647b18_add_fixed_interval_cadence_to_workflow_schedules.py@@ -0,0 +1,59 @@+"""add fixed-interval cadence to workflow_schedules++Revision ID: 762d72647b18+Revises: dc24a9eab0fb+Create Date: 2026-09-25T22:19:21.286896+00:00++"""++from typing import Sequence, Union++import sqlalchemy as sa++from alembic import op++# revision identifiers, used by Alembic.+revision: str = "762d72647b18"+down_revision: Union[str, None] = "dc24a9eab0fb"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None++CADENCE_CHECK = "ck_workflow_schedules_one_cadence"+++def upgrade() -> None:+ op.execute("SET LOCAL lock_timeout = '5s'")+ op.add_column("workflow_schedules", sa.Column("interval_seconds", sa.Integer(), nullable=True))+ op.add_column("workflow_schedules", sa.Column("first_fire_at", sa.DateTime(), nullable=True))+ op.alter_column("workflow_schedules", "cron_expression", existing_type=sa.String(), nullable=True)+ op.create_check_constraint(+ CADENCE_CHECK,+ "workflow_schedules",+ "(cron_expression IS NULL) <> (interval_seconds IS NULL) "+ "AND (interval_seconds IS NULL) = (first_fire_at IS NULL)",+ )+++def downgrade() -> None:+ live, soft_deleted = (+ op.get_bind()+ .execute(+ sa.text(+ "SELECT COUNT(*) FILTER (WHERE deleted_at IS NULL), COUNT(*) FILTER (WHERE deleted_at IS NOT NULL) "+ "FROM workflow_schedules WHERE interval_seconds IS NOT NULL"+ )+ )+ .one()+ )+ if live or soft_deleted:+ raise RuntimeError(+ f"Refusing to downgrade: workflow_schedules holds {live} live and {soft_deleted} soft-deleted interval "+ "schedules. Delete the live ones through the schedules API (which also removes their Temporal schedules), "+ "then run `DELETE FROM workflow_schedules WHERE interval_seconds IS NOT NULL AND deleted_at IS NOT NULL` "+ "and retry."+ )+ op.execute("SET LOCAL lock_timeout = '5s'")+ op.drop_constraint(CADENCE_CHECK, "workflow_schedules", type_="check")+ op.alter_column("workflow_schedules", "cron_expression", existing_type=sa.String(), nullable=False)+ op.drop_column("workflow_schedules", "first_fire_at")+ op.drop_column("workflow_schedules", "interval_seconds")diff --git a/docs/api-reference/openapi.json b/docs/api-reference/openapi.jsonindex 393d82ff8..93d54822c 100644--- a/docs/api-reference/openapi.json+++ b/docs/api-reference/openapi.json@@ -7267,7 +7267,7 @@"Schedules"],"summary": "Create a schedule for an agent",- "description": "Create a cron schedule that runs the given agent automatically with a fixed set of parameters. Returns the stored schedule and its next upcoming run times.",+ "description": "Create a cron or fixed-interval schedule that runs the given agent automatically with a fixed set of parameters. An interval schedule first runs at first_fire_at, or one interval after creation. Returns the stored schedule and its next upcoming run times.","operationId": "schedules_create","parameters": [{@@ -7397,7 +7397,7 @@"Schedules"],"summary": "Get an agent schedule by id",- "description": "Fetch one schedule belonging to an agent. Returns the schedule's cron expression, timezone, parameters, enabled state, and next upcoming run times.",+ "description": "Fetch one schedule belonging to an agent. Returns the schedule's cron expression or interval, timezone, parameters, enabled state, and next upcoming run times.","operationId": "schedules_get","parameters": [{@@ -7465,7 +7465,7 @@"Schedules"],"summary": "Update an agent schedule",- "description": "Replace a schedule's cron expression, timezone, run parameters, and enabled state. Returns the updated schedule and its next upcoming run times.",+ "description": "Replace a schedule's cron expression or interval, timezone, run parameters, and enabled state. Returns the updated schedule and its next upcoming run times.","operationId": "schedules_update","parameters": [{@@ -20960,9 +20960,39 @@"title": "Workflow Title"},"cron_expression": {- "type": "string",+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],"title": "Cron Expression"},+ "interval_seconds": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "title": "Interval Seconds"+ },+ "first_fire_at": {+ "anyOf": [+ {+ "type": "string",+ "format": "date-time"+ },+ {+ "type": "null"+ }+ ],+ "title": "First Fire At"+ },"timezone": {"type": "string","title": "Timezone"@@ -21034,7 +21064,6 @@"organization_id","workflow_permanent_id","workflow_title",- "cron_expression","timezone","enabled","created_at",@@ -32779,9 +32808,39 @@"title": "Workflow Permanent Id"},"cron_expression": {- "type": "string",+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],"title": "Cron Expression"},+ "interval_seconds": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "title": "Interval Seconds"+ },+ "first_fire_at": {+ "anyOf": [+ {+ "type": "string",+ "format": "date-time"+ },+ {+ "type": "null"+ }+ ],+ "title": "First Fire At"+ },"timezone": {"type": "string","title": "Timezone"@@ -32863,7 +32922,6 @@"workflow_schedule_id","organization_id","workflow_permanent_id",- "cron_expression","timezone","enabled","created_at",@@ -32910,9 +32968,43 @@"WorkflowScheduleUpsertRequest": {"properties": {"cron_expression": {- "type": "string",+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],"title": "Cron Expression"},+ "interval_seconds": {+ "anyOf": [+ {+ "type": "integer",+ "maximum": 2147483647.0,+ "minimum": 300.0+ },+ {+ "type": "null"+ }+ ],+ "title": "Interval Seconds",+ "description": "Fixed elapsed interval between runs, in seconds. Mutually exclusive with cron_expression."+ },+ "first_fire_at": {+ "anyOf": [+ {+ "type": "string",+ "format": "date-time"+ },+ {+ "type": "null"+ }+ ],+ "title": "First Fire At",+ "description": "First run of an interval schedule; later runs follow every interval_seconds from it. Must be in the future when changed. Defaults to one interval after creation."+ },"timezone": {"type": "string","title": "Timezone"@@ -32966,7 +33058,6 @@},"type": "object","required": [- "cron_expression","timezone"],"title": "WorkflowScheduleUpsertRequest"diff --git a/docs/cloud/building-agents/run-from-code.mdx b/docs/cloud/building-agents/run-from-code.mdxindex 6aae2f1db..57c7e266f 100644--- a/docs/cloud/building-agents/run-from-code.mdx+++ b/docs/cloud/building-agents/run-from-code.mdx@@ -315,8 +315,10 @@ curl -X POST "https://api.skyvern.com/api/v1/workflows/wpid_123456789/schedules"| Field | Type | Required | Description ||-------|------|----------|-------------|-| `cron_expression` | string | Yes | 5-field cron expression (minimum 5-minute interval) |-| `timezone` | string | Yes | IANA timezone identifier (e.g., `America/New_York`) |+| `cron_expression` | string | One of these two | 5-field cron expression (minimum 5-minute interval) |+| `interval_seconds` | integer | One of these two | Run every N seconds from `first_fire_at` (minimum 300). Runs stay exactly N seconds apart across daylight saving changes, and a paused schedule skips missed runs instead of catching up |+| `first_fire_at` | datetime | No | First run of an interval schedule, with a timezone offset. Must be in the future. Defaults to one interval after creation |+| `timezone` | string | Yes | IANA timezone identifier (e.g., `America/New_York`). For interval schedules it only affects how times are displayed || `name` | string | No | Human-readable name for the schedule || `description` | string | No | Description of what this schedule does || `parameters` | object | No | Agent parameters to pass on each run |diff --git a/fern/openapi/skyvern_openapi.json b/fern/openapi/skyvern_openapi.jsonindex f470375c5..8f354b014 100644--- a/fern/openapi/skyvern_openapi.json+++ b/fern/openapi/skyvern_openapi.json@@ -6838,7 +6838,8 @@}}}- }+ },+ "description": "Create a cron or fixed-interval schedule that runs the given agent automatically with a fixed set of parameters. An interval schedule first runs at first_fire_at, or one interval after creation. Returns the stored schedule and its next upcoming run times."},"get": {"tags": [@@ -6965,7 +6966,8 @@}}}- }+ },+ "description": "Fetch one schedule belonging to an agent. Returns the schedule's cron expression or interval, timezone, parameters, enabled state, and next upcoming run times."},"put": {"tags": [@@ -7042,7 +7044,8 @@}}}- }+ },+ "description": "Replace a schedule's cron expression or interval, timezone, run parameters, and enabled state. Returns the updated schedule and its next upcoming run times."},"delete": {"tags": [@@ -18561,9 +18564,39 @@"title": "Workflow Title"},"cron_expression": {- "type": "string",+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],"title": "Cron Expression"},+ "interval_seconds": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "title": "Interval Seconds"+ },+ "first_fire_at": {+ "anyOf": [+ {+ "type": "string",+ "format": "date-time"+ },+ {+ "type": "null"+ }+ ],+ "title": "First Fire At"+ },"timezone": {"type": "string","title": "Timezone"@@ -18635,7 +18668,6 @@"organization_id","workflow_permanent_id","workflow_title",- "cron_expression","timezone","enabled","created_at",@@ -28821,9 +28853,39 @@"title": "Workflow Permanent Id"},"cron_expression": {- "type": "string",+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],"title": "Cron Expression"},+ "interval_seconds": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "title": "Interval Seconds"+ },+ "first_fire_at": {+ "anyOf": [+ {+ "type": "string",+ "format": "date-time"+ },+ {+ "type": "null"+ }+ ],+ "title": "First Fire At"+ },"timezone": {"type": "string","title": "Timezone"@@ -28905,7 +28967,6 @@"workflow_schedule_id","organization_id","workflow_permanent_id",- "cron_expression","timezone","enabled","created_at",@@ -28952,9 +29013,43 @@"WorkflowScheduleUpsertRequest": {"properties": {"cron_expression": {- "type": "string",+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],"title": "Cron Expression"},+ "interval_seconds": {+ "anyOf": [+ {+ "type": "integer",+ "maximum": 2147483647.0,+ "minimum": 300.0+ },+ {+ "type": "null"+ }+ ],+ "title": "Interval Seconds",+ "description": "Fixed elapsed interval between runs, in seconds. Mutually exclusive with cron_expression."+ },+ "first_fire_at": {+ "anyOf": [+ {+ "type": "string",+ "format": "date-time"+ },+ {+ "type": "null"+ }+ ],+ "title": "First Fire At",+ "description": "First run of an interval schedule; later runs follow every interval_seconds from it. Must be in the future when changed. Defaults to one interval after creation."+ },"timezone": {"type": "string","title": "Timezone"@@ -29008,7 +29103,6 @@},"type": "object","required": [- "cron_expression","timezone"],"title": "WorkflowScheduleUpsertRequest"diff --git a/skyvern-frontend/src/routes/schedules/CreateOrgScheduleDialog.tsx b/skyvern-frontend/src/routes/schedules/CreateOrgScheduleDialog.tsxindex 18889325d..7259bf622 100644--- a/skyvern-frontend/src/routes/schedules/CreateOrgScheduleDialog.tsx+++ b/skyvern-frontend/src/routes/schedules/CreateOrgScheduleDialog.tsx@@ -18,11 +18,12 @@ import type {WorkflowApiResponse,Parameter,} from "@/routes/workflows/types/workflowTypes";+import { getLocalTimezone } from "@/routes/workflows/editor/panels/schedulePanel/cronUtils";import {- getLocalTimezone,- isValidCron,- meetsMinCronInterval,-} from "@/routes/workflows/editor/panels/schedulePanel/cronUtils";+ buildCadencePayload,+ isCadenceAccepted,+ type IntervalDraft,+} from "@/routes/workflows/editor/panels/schedulePanel/scheduleCadence";import { useWorkflowQuery } from "@/routes/workflows/hooks/useWorkflowQuery";import { ScheduleConfigFields } from "@/routes/workflows/components/ScheduleConfigFields";import { ScheduleParametersSection } from "@/routes/workflows/components/ScheduleParametersSection";@@ -45,6 +46,7 @@ function CreateOrgScheduleDialog({ open, onOpenChange }: Readonly<Props>) {const [selectedWorkflow, setSelectedWorkflow] =useState<WorkflowApiResponse | null>(null);const [cronExpression, setCronExpression] = useState("0 9 * * *");+ const [interval, setIntervalDraft] = useState<IntervalDraft | null>(null);const [timezone, setTimezone] = useState(getLocalTimezone);const [scheduleName, setScheduleName] = useState("");@@ -119,14 +121,14 @@ function CreateOrgScheduleDialog({ open, onOpenChange }: Readonly<Props>) {}}, [selectedWorkflowId, workflowParameters, resetParameters]);- const valid = isValidCron(cronExpression);- const cronAccepted = valid && meetsMinCronInterval(cronExpression);+ const cadenceAccepted = isCadenceAccepted(cronExpression, interval, timezone);function resetForm() {setWorkflowSearch("");setWorkflowPickerOpen(false);setSelectedWorkflow(null);setCronExpression("0 9 * * *");+ setIntervalDraft(null);setTimezone(getLocalTimezone());setScheduleName("");setScheduleDescription("");@@ -136,7 +138,7 @@ function CreateOrgScheduleDialog({ open, onOpenChange }: Readonly<Props>) {function handleSubmit() {if (!selectedWorkflow || !workflowDetailLoaded) return;const parametersValid = validateParameters();- if (!cronAccepted || !parametersValid) return;+ if (!cadenceAccepted || !parametersValid) return;const payload = buildScheduleParametersPayload(parameters,workflowParameters,@@ -145,7 +147,7 @@ function CreateOrgScheduleDialog({ open, onOpenChange }: Readonly<Props>) {{workflowPermanentId: selectedWorkflow.workflow_permanent_id,request: {- cron_expression: cronExpression,+ ...buildCadencePayload(cronExpression, interval, timezone),timezone,...(scheduleName && { name: scheduleName }),...(scheduleDescription && { description: scheduleDescription }),@@ -261,6 +263,8 @@ function CreateOrgScheduleDialog({ open, onOpenChange }: Readonly<Props>) {timezone={timezone}onCronChange={setCronExpression}onTimezoneChange={setTimezone}+ interval={interval}+ onIntervalChange={setIntervalDraft}disabled={createMutation.isPending}/></div>@@ -271,7 +275,9 @@ function CreateOrgScheduleDialog({ open, onOpenChange }: Readonly<Props>) {</Button><Buttondisabled={- !cronAccepted || !workflowDetailLoaded || createMutation.isPending+ !cadenceAccepted ||+ !workflowDetailLoaded ||+ createMutation.isPending}onClick={handleSubmit}>diff --git a/skyvern-frontend/src/routes/schedules/ScheduleDetailPage.tsx b/skyvern-frontend/src/routes/schedules/ScheduleDetailPage.tsxindex b868a3a38..4ad90718c 100644--- a/skyvern-frontend/src/routes/schedules/ScheduleDetailPage.tsx+++ b/skyvern-frontend/src/routes/schedules/ScheduleDetailPage.tsx@@ -19,12 +19,16 @@ import {useEnableScheduleMutation,useUpdateScheduleMutation,} from "./useScheduleActions";+import { formatNextRun } from "@/routes/workflows/editor/panels/schedulePanel/cronUtils";import {- cronToHumanReadable,- formatNextRun,- isValidCron,- meetsMinCronInterval,-} from "@/routes/workflows/editor/panels/schedulePanel/cronUtils";+ buildCadencePayload,+ cronBelowMinInterval,+ describeCadence,+ intervalDraftFromSeconds,+ isCadenceAccepted,+ type IntervalDraft,+ upcomingFirstRun,+} from "@/routes/workflows/editor/panels/schedulePanel/scheduleCadence";import { getErrorDetail } from "@/util/getErrorDetail";import { basicLocalTimeFormat, basicTimeFormat } from "@/util/timeFormat";import { ScheduleConfigFields } from "@/routes/workflows/components/ScheduleConfigFields";@@ -65,6 +69,7 @@ function ScheduleDetailPage() {// Edit mode stateconst [editing, setEditing] = useState(false);const [editCron, setEditCron] = useState("");+ const [editInterval, setEditInterval] = useState<IntervalDraft | null>(null);const [editTimezone, setEditTimezone] = useState("");const [editName, setEditName] = useState("");const [editDescription, setEditDescription] = useState("");@@ -84,9 +89,11 @@ function ScheduleDetailPage() {data?.schedule.parameters ?? null,);- const editValid = isValidCron(editCron);- const editIntervalTooShort = editValid && !meetsMinCronInterval(editCron);- const editCronAccepted = editValid && !editIntervalTooShort;+ const editCadenceAccepted = isCadenceAccepted(+ editCron,+ editInterval,+ editTimezone,+ );if (isLoading) {return (@@ -109,13 +116,19 @@ function ScheduleDetailPage() {}const { schedule, next_runs } = data;- const humanReadable = cronToHumanReadable(schedule.cron_expression);- const scheduleCronTooFrequent =- isValidCron(schedule.cron_expression) &&- !meetsMinCronInterval(schedule.cron_expression);+ const humanReadable = describeCadence(schedule);+ const firstRun = upcomingFirstRun(schedule.first_fire_at);+ const scheduleCronTooFrequent = cronBelowMinInterval(+ schedule.cron_expression,+ );function startEditing() {- setEditCron(schedule.cron_expression);+ setEditCron(schedule.cron_expression ?? "0 9 * * *");+ setEditInterval(+ schedule.interval_seconds+ ? intervalDraftFromSeconds(schedule.interval_seconds)+ : null,+ );setEditTimezone(schedule.timezone);setEditName(schedule.name ?? "");setEditDescription(schedule.description ?? "");@@ -133,7 +146,7 @@ function ScheduleDetailPage() {function handleSave() {if (!workflowPermanentId || !scheduleId) return;const parametersValid = validateParameters();- if (!editCronAccepted || !parametersValid) return;+ if (!editCadenceAccepted || !parametersValid) return;// Only persist explicitly-set overrides. The form is seeded from// workflow defaults, so blindly sending the whole values dict would// pin the current default into the schedule and change semantics from@@ -149,7 +162,7 @@ function ScheduleDetailPage() {request: {// `enabled` is intentionally omitted so the edit preserves whatever// the enable/disable toggle set, even if this detail query is stale.- cron_expression: editCron,+ ...buildCadencePayload(editCron, editInterval, editTimezone),timezone: editTimezone,parameters: payload,...(editName && { name: editName }),@@ -169,6 +182,8 @@ function ScheduleDetailPage() {workflow_permanent_id: schedule.workflow_permanent_id,workflow_title: "",cron_expression: schedule.cron_expression,+ interval_seconds: schedule.interval_seconds,+ first_fire_at: schedule.first_fire_at,timezone: schedule.timezone,enabled: schedule.enabled,parameters: schedule.parameters,@@ -192,6 +207,8 @@ function ScheduleDetailPage() {workflow_permanent_id: schedule.workflow_permanent_id,workflow_title: "",cron_expression: schedule.cron_expression,+ interval_seconds: schedule.interval_seconds,+ first_fire_at: schedule.first_fire_at,timezone: schedule.timezone,enabled: schedule.enabled,parameters: schedule.parameters,@@ -308,6 +325,11 @@ function ScheduleDetailPage() {timezone={editTimezone}onCronChange={setEditCron}onTimezoneChange={setEditTimezone}+ interval={editInterval}+ onIntervalChange={setEditInterval}+ intervalAnchor={+ schedule.interval_seconds ? schedule.first_fire_at : null+ }disabled={updateMutation.isPending}/>@@ -316,7 +338,7 @@ function ScheduleDetailPage() {<Buttonsize="sm"className="h-7 text-xs"- disabled={!editCronAccepted || updateMutation.isPending}+ disabled={!editCadenceAccepted || updateMutation.isPending}onClick={handleSave}>{updateMutation.isPending ? "Saving..." : "Save"}@@ -343,12 +365,22 @@ function ScheduleDetailPage() {{schedule.timezone}</span></div>- <div className="flex items-start justify-between">- <span className="text-sm text-slate-400">Cron</span>- <code className="font-mono text-xs text-slate-50">- {schedule.cron_expression}- </code>- </div>+ {schedule.cron_expression && (+ <div className="flex items-start justify-between">+ <span className="text-sm text-slate-400">Cron</span>+ <code className="font-mono text-xs text-slate-50">+ {schedule.cron_expression}+ </code>+ </div>+ )}+ {firstRun && (+ <div className="flex items-start justify-between">+ <span className="text-sm text-slate-400">First run</span>+ <span className="text-sm text-slate-50">+ {formatNextRun(firstRun, schedule.timezone)}+ </span>+ </div>+ )}{scheduleCronTooFrequent && (<div className="rounded border border-amber-600/40 bg-amber-900/20 px-2 py-1 text-xs text-amber-200">This schedule fires more often than the 5-minute minimum.diff --git a/skyvern-frontend/src/routes/schedules/SchedulesPage.tsx b/skyvern-frontend/src/routes/schedules/SchedulesPage.tsxindex a7c3c79b2..a82357598 100644--- a/skyvern-frontend/src/routes/schedules/SchedulesPage.tsx+++ b/skyvern-frontend/src/routes/schedules/SchedulesPage.tsx@@ -71,10 +71,10 @@ import {useEnableScheduleMutation,} from "./useScheduleActions";import {- cronToHumanReadable,- isValidCron,- meetsMinCronInterval,-} from "@/routes/workflows/editor/panels/schedulePanel/cronUtils";+ buildDuplicateSchedulePayload,+ cronBelowMinInterval,+ describeCadence,+} from "@/routes/workflows/editor/panels/schedulePanel/scheduleCadence";import { basicLocalTimeFormat, basicTimeFormat } from "@/util/timeFormat";import type { OrganizationScheduleItem } from "@/routes/workflows/types/scheduleTypes";import { CreateOrgScheduleDialog } from "./CreateOrgScheduleDialog";@@ -138,14 +138,14 @@ function SchedulesPage() {const totalCount = data?.total_count ?? 0;const totalPages = Math.max(1, Math.ceil(totalCount / pageSize));- // meetsMinCronInterval samples up to 2000 future fires; memoize per cron string+ // cronBelowMinInterval samples up to 2000 future fires; memoize per cron string// so unrelated re-renders (selection, dialogs) don't re-run it for every row.const cronsBelowMinInterval = useMemo(() => {const violations = new Set<string>();for (const schedule of schedules) {if (- isValidCron(schedule.cron_expression) &&- !meetsMinCronInterval(schedule.cron_expression)+ schedule.cron_expression &&+ cronBelowMinInterval(schedule.cron_expression)) {violations.add(schedule.cron_expression);}@@ -277,13 +277,10 @@ function SchedulesPage() {void runBulkOperation(selectedSchedules,(client, item) =>- client.post(`/workflows/${item.workflow_permanent_id}/schedules`, {- cron_expression: item.cron_expression,- timezone: item.timezone,- enabled: item.enabled,- parameters: item.parameters,- name: `${item.name ?? item.workflow_title} (copy)`,- }),+ client.post(+ `/workflows/${item.workflow_permanent_id}/schedules`,+ buildDuplicateSchedulePayload(item),+ ),"duplicated","duplicate",);@@ -482,13 +479,14 @@ function SchedulesPage() {<TableCell className="text-slate-400"><div className="flex items-center gap-1.5"><span className="truncate">- {cronToHumanReadable(schedule.cron_expression)}+ {describeCadence(schedule)}</span>- {cronsBelowMinInterval.has(schedule.cron_expression) && (- <Tip content="This schedule fires more often than the 5-minute minimum. Saving any change requires updating its cron expression first.">- <ExclamationTriangleIcon className="size-3.5 shrink-0 text-amber-400" />- </Tip>- )}+ {schedule.cron_expression &&+ cronsBelowMinInterval.has(schedule.cron_expression) && (+ <Tip content="This schedule fires more often than the 5-minute minimum. Saving any change requires updating its cron expression first.">+ <ExclamationTriangleIcon className="size-3.5 shrink-0 text-amber-400" />+ </Tip>+ )}</div></TableCell><TableCell className="text-slate-400">diff --git a/skyvern-frontend/src/routes/schedules/useScheduleActions.ts b/skyvern-frontend/src/routes/schedules/useScheduleActions.tsindex acb22a427..e3d4ace57 100644--- a/skyvern-frontend/src/routes/schedules/useScheduleActions.ts+++ b/skyvern-frontend/src/routes/schedules/useScheduleActions.ts@@ -8,6 +8,7 @@ import type {UpdateScheduleRequest,WorkflowScheduleResponse,} from "@/routes/workflows/types/scheduleTypes";+import { buildDuplicateSchedulePayload } from "@/routes/workflows/editor/panels/schedulePanel/scheduleCadence";function useEnableScheduleMutation() {const credentialGetter = useCredentialGetter();@@ -99,13 +100,7 @@ function useDuplicateScheduleMutation() {const client = await getClient(credentialGetter);await client.post(`/workflows/${schedule.workflow_permanent_id}/schedules`,- {- cron_expression: schedule.cron_expression,- timezone: schedule.timezone,- enabled: schedule.enabled,- parameters: schedule.parameters,- name: `${schedule.name ?? schedule.workflow_title} (copy)`,- },+ buildDuplicateSchedulePayload(schedule),);},onSuccess: () => {diff --git a/skyvern-frontend/src/routes/workflows/components/ScheduleConfigFields.test.tsx b/skyvern-frontend/src/routes/workflows/components/ScheduleConfigFields.test.tsxindex 6e6f804b0..8285b5b6c 100644--- a/skyvern-frontend/src/routes/workflows/components/ScheduleConfigFields.test.tsx+++ b/skyvern-frontend/src/routes/workflows/components/ScheduleConfigFields.test.tsx@@ -1,6 +1,7 @@import { useState } from "react";import { fireEvent, render, screen } from "@testing-library/react";import { describe, expect, it } from "vitest";+import type { IntervalDraft } from "@/routes/workflows/editor/panels/schedulePanel/scheduleCadence";import { ScheduleConfigFields } from "./ScheduleConfigFields";function Harness({ initialCron }: { initialCron: string }) {@@ -76,4 +77,54 @@ describe("ScheduleConfigFields", () => {fireEvent.change(input, { target: { value: "0 14 * * *" } });expect(cronOut()).toBe("0 14 * * *");});++ it("interval mode without an anchor describes the first run instead of guessing times", () => {+ render(+ <ScheduleConfigFields+ cronExpression="0 9 * * *"+ timezone="UTC"+ onCronChange={() => {}}+ onTimezoneChange={() => {}}+ interval={{ every: "72", unit: "hours", firstFireAt: "" }}+ onIntervalChange={() => {}}+ />,+ );+ expect(+ screen.getByText("Every 3 days. First run 3 days after saving."),+ ).toBeTruthy();+ expect(screen.queryByText("Next Scheduled Runs")).toBeNull();+ expect(screen.queryByText("Advanced (cron expression)")).toBeNull();+ });++ it("keeps an emptied interval length empty and flags only that field", () => {+ function IntervalHarness() {+ const [interval, setInterval] = useState<IntervalDraft | null>({+ every: "72",+ unit: "hours",+ firstFireAt: "",+ });+ return (+ <ScheduleConfigFields+ cronExpression="0 9 * * *"+ timezone="UTC"+ onCronChange={() => {}}+ onTimezoneChange={() => {}}+ interval={interval}+ onIntervalChange={setInterval}+ />+ );+ }+ render(<IntervalHarness />);+ const length = screen.getByLabelText("Every");+ fireEvent.change(length, { target: { value: "" } });++ expect((length as HTMLInputElement).value).toBe("");+ expect(length.getAttribute("aria-invalid")).toBe("true");+ expect(screen.getByText("Enter how often the schedule runs.")).toBeTruthy();+ expect(+ screen+ .getByLabelText("First run (optional)")+ .getAttribute("aria-invalid"),+ ).toBe(null);+ });});diff --git a/skyvern-frontend/src/routes/workflows/components/ScheduleConfigFields.tsx b/skyvern-frontend/src/routes/workflows/components/ScheduleConfigFields.tsxindex d2b0f8d1a..cfb75f302 100644--- a/skyvern-frontend/src/routes/workflows/components/ScheduleConfigFields.tsx+++ b/skyvern-frontend/src/routes/workflows/components/ScheduleConfigFields.tsx@@ -1,4 +1,4 @@-import { useEffect, useMemo, useState } from "react";+import { useEffect, useId, useMemo, useState } from "react";import {CaretSortIcon,CheckIcon,@@ -52,12 +52,29 @@ import {type ScheduleBuilderState,type ScheduleFrequency,} from "@/routes/workflows/editor/panels/schedulePanel/scheduleBuilder";+import {+ DEFAULT_INTERVAL_DRAFT,+ formatInterval,+ formatIntervalDuration,+ getIntervalRuns,+ intervalDraftErrors,+ intervalDraftSeconds,+ upcomingFirstRun,+ zonedWallTimeToDate,+ type IntervalDraft,+ type IntervalUnit,+} from "@/routes/workflows/editor/panels/schedulePanel/scheduleCadence";type Props = {cronExpression: string;timezone: string;onCronChange: (cronExpression: string) => void;onTimezoneChange: (timezone: string) => void;+ // A non-null interval puts the fields in fixed-interval mode; omit onIntervalChange to offer cron only.+ interval?: IntervalDraft | null;+ onIntervalChange?: (interval: IntervalDraft | null) => void;+ // The stored anchor when editing, kept by the server if the first-run field is left empty.+ intervalAnchor?: string | null;size?: "default" | "compact";disabled?: boolean;};@@ -81,10 +98,19 @@ function ScheduleConfigFields({timezone,onCronChange,onTimezoneChange,+ interval = null,+ onIntervalChange,+ intervalAnchor = null,size = "default",disabled = false,}: Readonly<Props>) {const compact = size === "compact";+ const fieldId = useId();+ const everyId = `${fieldId}-every`;+ const everyErrorId = `${fieldId}-every-error`;+ const firstRunId = `${fieldId}-first-run`;+ const firstRunHintId = `${fieldId}-first-run-hint`;+ const firstRunErrorId = `${fieldId}-first-run-error`;const controlClass = compact ? "h-8 text-xs" : "h-9 text-sm";const labelClass = compact ? "text-xs" : undefined;@@ -115,10 +141,43 @@ function ScheduleConfigFields({}, [isCustom]);const allTimezones = useMemo(() => getTimezones(), []);+ const cronMode = interval === null;const valid = isValidCron(cronExpression);const intervalTooShort = valid && !meetsMinCronInterval(cronExpression);- const humanReadable = valid ? cronToHumanReadable(cronExpression) : null;- const nextRuns = valid ? getNextRuns(cronExpression, timezone, 5) : [];+ const intervalErrors = interval+ ? intervalDraftErrors(interval, timezone)+ : null;+ const intervalSeconds = interval ? intervalDraftSeconds(interval) : 0;+ let humanReadable: string | null = null;+ let nextRuns: Date[] = [];+ if (interval && intervalErrors) {+ if (!intervalErrors.every) {+ humanReadable = formatInterval(intervalSeconds);+ }+ if (!intervalErrors.every && !intervalErrors.firstFireAt) {+ const anchor = interval.firstFireAt+ ? zonedWallTimeToDate(interval.firstFireAt, timezone)+ : intervalAnchor+ ? new Date(intervalAnchor)+ : null;+ if (anchor) {+ nextRuns = getIntervalRuns(intervalSeconds, anchor, 5);+ } else {+ humanReadable = `${humanReadable}. First run ${formatIntervalDuration(intervalSeconds)} after saving.`;+ }+ }+ } else if (valid) {+ humanReadable = cronToHumanReadable(cronExpression);+ nextRuns = getNextRuns(cronExpression, timezone, 5);+ }++ const upcomingAnchor = upcomingFirstRun(intervalAnchor);+ let firstRunHint = "Leave empty to start one interval after saving.";+ if (upcomingAnchor) {+ firstRunHint = `Leave empty to keep the current first run (${formatNextRun(upcomingAnchor, timezone)}).`;+ } else if (intervalAnchor) {+ firstRunHint = "Leave empty to keep the current run times.";+ }const { hour12, meridiem } = to12Hour(builder.hour);@@ -128,7 +187,12 @@ function ScheduleConfigFields({}function handleFrequencyChange(value: string) {+ if (value === "interval") {+ onIntervalChange?.(DEFAULT_INTERVAL_DRAFT);+ return;+ }if (value === "custom") return;+ if (interval) onIntervalChange?.(null);const frequency = value as ScheduleFrequency;const next: ScheduleBuilderState = { ...builder, frequency };if (frequency === "weekly" && next.daysOfWeek.length === 0) {@@ -153,7 +217,9 @@ function ScheduleConfigFields({<div className="space-y-2"><Label className={labelClass}>Repeat</Label><Select- value={isCustom ? "custom" : builder.frequency}+ value={+ interval ? "interval" : isCustom ? "custom" : builder.frequency+ }onValueChange={handleFrequencyChange}disabled={disabled}>@@ -171,11 +237,109 @@ function ScheduleConfigFields({Custom</SelectItem>)}+ {onIntervalChange && (+ <SelectItem value="interval">Fixed interval</SelectItem>+ )}</SelectContent></Select></div>- {!isCustom && builder.frequency === "hourly" && (+ {interval && (+ <>+ <div className="space-y-2">+ <Label htmlFor={everyId} className={labelClass}>+ Every+ </Label>+ <div className="flex items-center gap-2">+ <Input+ id={everyId}+ type="number"+ min={1}+ aria-invalid={intervalErrors?.every ? true : undefined}+ aria-describedby={+ intervalErrors?.every ? everyErrorId : undefined+ }+ value={interval.every}+ onChange={(e) =>+ onIntervalChange?.({+ ...interval,+ every: e.target.value,+ })+ }+ disabled={disabled}+ className={cn(+ "w-24",+ controlClass,+ intervalErrors?.every && "border-destructive",+ )}+ />+ <Select+ value={interval.unit}+ onValueChange={(value) =>+ onIntervalChange?.({+ ...interval,+ unit: value as IntervalUnit,+ })+ }+ disabled={disabled}+ >+ <SelectTrigger+ aria-label="Interval unit"+ className={cn("w-28", controlClass)}+ >+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="minutes">minutes</SelectItem>+ <SelectItem value="hours">hours</SelectItem>+ <SelectItem value="days">days</SelectItem>+ </SelectContent>+ </Select>+ </div>+ {intervalErrors?.every && (+ <p id={everyErrorId} className="text-xs text-destructive">+ {intervalErrors.every}+ </p>+ )}+ </div>+ <div className="space-y-2">+ <Label htmlFor={firstRunId} className={labelClass}>+ First run (optional)+ </Label>+ <Input+ id={firstRunId}+ type="datetime-local"+ aria-invalid={intervalErrors?.firstFireAt ? true : undefined}+ aria-describedby={+ intervalErrors?.firstFireAt+ ? `${firstRunHintId} ${firstRunErrorId}`+ : firstRunHintId+ }+ value={interval.firstFireAt}+ onChange={(e) =>+ onIntervalChange?.({ ...interval, firstFireAt: e.target.value })+ }+ disabled={disabled}+ className={cn(+ controlClass,+ "[color-scheme:light] dark:[color-scheme:dark]",+ intervalErrors?.firstFireAt && "border-destructive",+ )}+ />+ <p id={firstRunHintId} className="text-xs text-muted-foreground">+ {firstRunHint} Runs stay exactly one interval apart, including+ across daylight saving changes. Entered in {timezone}.+ </p>+ {intervalErrors?.firstFireAt && (+ <p id={firstRunErrorId} className="text-xs text-destructive">+ {intervalErrors.firstFireAt}+ </p>+ )}+ </div>+ </>+ )}++ {cronMode && !isCustom && builder.frequency === "hourly" && (<div className="space-y-2"><Label className={labelClass}>Minute past the hour</Label><Select@@ -199,7 +363,7 @@ function ScheduleConfigFields({</div>)}- {!isCustom && builder.frequency === "weekly" && (+ {cronMode && !isCustom && builder.frequency === "weekly" && (<div className="space-y-2"><Label className={labelClass}>On these days</Label><div className="flex flex-wrap gap-1.5">@@ -225,7 +389,7 @@ function ScheduleConfigFields({</div>)}- {!isCustom && builder.frequency === "monthly" && (+ {cronMode && !isCustom && builder.frequency === "monthly" && (<div className="space-y-2"><Label className={labelClass}>On day of month</Label><Select@@ -249,7 +413,7 @@ function ScheduleConfigFields({</div>)}- {!isCustom && showTimeOfDay && (+ {cronMode && !isCustom && showTimeOfDay && (<div className="space-y-2"><Label className={labelClass}>At</Label><div className="flex items-center gap-2">@@ -376,39 +540,43 @@ function ScheduleConfigFields({</p>)}- <Collapsible open={advancedOpen} onOpenChange={setAdvancedOpen}>- <CollapsibleTrigger asChild>- <button- type="button"- className="group flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"- >- <ChevronRightIcon className="size-3 transition-transform group-data-[state=open]:rotate-90" />- Advanced (cron expression)- </button>- </CollapsibleTrigger>- <CollapsibleContent className="space-y-1.5 pt-2">- <Input- value={cronExpression}- onChange={(e) => onCronChange(e.target.value)}- placeholder="* * * * *"- disabled={disabled}- className={cn(- controlClass,- cronExpression &&- (!valid || intervalTooShort) &&- "border-destructive",+ {cronMode && (+ <Collapsible open={advancedOpen} onOpenChange={setAdvancedOpen}>+ <CollapsibleTrigger asChild>+ <button+ type="button"+ className="group flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"+ >+ <ChevronRightIcon className="size-3 transition-transform group-data-[state=open]:rotate-90" />+ Advanced (cron expression)+ </button>+ </CollapsibleTrigger>+ <CollapsibleContent className="space-y-1.5 pt-2">+ <Input+ value={cronExpression}+ onChange={(e) => onCronChange(e.target.value)}+ placeholder="* * * * *"+ disabled={disabled}+ className={cn(+ controlClass,+ cronExpression &&+ (!valid || intervalTooShort) &&+ "border-destructive",+ )}+ />+ {!valid && cronExpression && (+ <p className="text-xs text-destructive">+ Invalid cron expression+ </p>)}- />- {!valid && cronExpression && (- <p className="text-xs text-destructive">Invalid cron expression</p>- )}- {intervalTooShort && (- <p className="text-xs text-destructive">- Schedule runs must be at least 5 minutes apart.- </p>- )}- </CollapsibleContent>- </Collapsible>+ {intervalTooShort && (+ <p className="text-xs text-destructive">+ Schedule runs must be at least 5 minutes apart.+ </p>+ )}+ </CollapsibleContent>+ </Collapsible>+ )}{nextRuns.length > 0 && (<div className="space-y-2">diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/CreateScheduleDialog.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/CreateScheduleDialog.tsxindex 8aadd3f94..ea9f01602 100644--- a/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/CreateScheduleDialog.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/CreateScheduleDialog.tsx@@ -17,16 +17,18 @@ import { ScheduleConfigFields } from "@/routes/workflows/components/ScheduleConfimport { ScheduleParametersSection } from "@/routes/workflows/components/ScheduleParametersSection";import { buildScheduleParametersPayload } from "@/routes/workflows/components/scheduleParameters";import { useScheduleParameterState } from "@/routes/workflows/hooks/useScheduleParameterState";+import { getLocalTimezone } from "./cronUtils";import {- getLocalTimezone,- isValidCron,- meetsMinCronInterval,-} from "./cronUtils";+ buildCadencePayload,+ isCadenceAccepted,+ type CadencePayload,+ type IntervalDraft,+} from "./scheduleCadence";type Props = {workflowParameters: ReadonlyArray<Parameter>;onSubmit: (- cronExpression: string,+ cadence: CadencePayload,timezone: string,name: string,description: string,@@ -43,6 +45,7 @@ function CreateScheduleDialog({}: Readonly<Props>) {const [open, setOpen] = useState(false);const [cronExpression, setCronExpression] = useState("0 9 * * *");+ const [interval, setIntervalDraft] = useState<IntervalDraft | null>(null);const [timezone, setTimezone] = useState(getLocalTimezone);const [name, setName] = useState("");const [description, setDescription] = useState("");@@ -66,11 +69,11 @@ function CreateScheduleDialog({}}, [open, workflowParameters, resetParameters]);- const valid = isValidCron(cronExpression);- const cronAccepted = valid && meetsMinCronInterval(cronExpression);+ const cadenceAccepted = isCadenceAccepted(cronExpression, interval, timezone);function resetFormState() {setCronExpression("0 9 * * *");+ setIntervalDraft(null);setTimezone(getLocalTimezone());setName("");setDescription("");@@ -79,17 +82,24 @@ function CreateScheduleDialog({function handleSubmit() {const parametersValid = validateParameters();- if (!cronAccepted || !parametersValid) return;+ if (!cadenceAccepted || !parametersValid) return;const payload = buildScheduleParametersPayload(parameters,workflowParameters,);- onSubmit(cronExpression, timezone, name, description, payload, {- onSuccess: () => {- setOpen(false);- resetFormState();+ onSubmit(+ buildCadencePayload(cronExpression, interval, timezone),+ timezone,+ name,+ description,+ payload,+ {+ onSuccess: () => {+ setOpen(false);+ resetFormState();+ },},- });+ );}return (@@ -145,6 +155,8 @@ function CreateScheduleDialog({timezone={timezone}onCronChange={setCronExpression}onTimezoneChange={setTimezone}+ interval={interval}+ onIntervalChange={setIntervalDraft}disabled={isPending}/></div>@@ -153,7 +165,10 @@ function CreateScheduleDialog({<Button variant="secondary" onClick={() => setOpen(false)}>Cancel</Button>- <Button disabled={!cronAccepted || isPending} onClick={handleSubmit}>+ <Button+ disabled={!cadenceAccepted || isPending}+ onClick={handleSubmit}+ >{isPending ? "Creating..." : "Create Schedule"}</Button></DialogFooter>diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/ScheduleCard.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/ScheduleCard.tsxindex 1b651e222..1949e101e 100644--- a/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/ScheduleCard.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/ScheduleCard.tsx@@ -2,7 +2,12 @@ import { TrashIcon } from "@radix-ui/react-icons";import { Switch } from "@/components/ui/switch";import { Button } from "@/components/ui/button";import type { WorkflowSchedule } from "@/routes/workflows/types/scheduleTypes";-import { cronToHumanReadable, formatNextRun, getNextRuns } from "./cronUtils";+import { formatNextRun } from "./cronUtils";+import {+ describeCadence,+ getCadenceNextRuns,+ upcomingFirstRun,+} from "./scheduleCadence";import { cn } from "@/util/utils";type Props = {@@ -13,9 +18,9 @@ type Props = {};function ScheduleCard({ schedule, isToggling, onToggle, onDelete }: Props) {- const humanReadable = cronToHumanReadable(schedule.cron_expression);- const nextRuns = getNextRuns(schedule.cron_expression, schedule.timezone, 1);- const nextRun = nextRuns[0];+ const humanReadable = describeCadence(schedule);+ const nextRun = getCadenceNextRuns(schedule, schedule.timezone, 1)[0];+ const firstRun = upcomingFirstRun(schedule.first_fire_at);return (<div className="flex flex-col gap-2 rounded-md border border-border px-3.5 pb-0.5 pt-3.5">@@ -61,9 +66,15 @@ function ScheduleCard({ schedule, isToggling, onToggle, onDelete }: Props) {</Button></div></div>+ {firstRun && (+ <div className="text-xs text-muted-foreground dark:text-slate-500">+ First run: {formatNextRun(firstRun, schedule.timezone)}+ </div>+ )}{nextRun && (<div className="text-xs text-muted-foreground dark:text-slate-500">- Next: {formatNextRun(nextRun, schedule.timezone)}+ {schedule.enabled ? "Next" : "Next (paused)"}:{" "}+ {formatNextRun(nextRun, schedule.timezone)}</div>)}</div>diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/WorkflowSchedulePanel.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/WorkflowSchedulePanel.tsxindex afc75dc38..760565043 100644--- a/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/WorkflowSchedulePanel.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/WorkflowSchedulePanel.tsx@@ -13,6 +13,7 @@ import { CreateScheduleDialog } from "./CreateScheduleDialog";import { Cross2Icon, ReloadIcon } from "@radix-ui/react-icons";import { useState } from "react";import { useWorkflowPermanentId } from "@/routes/workflows/WorkflowPermanentIdContext";+import type { CadencePayload } from "./scheduleCadence";type Props = {onClose?: () => void;@@ -38,7 +39,7 @@ function WorkflowSchedulePanel({ onClose }: Props) {const workflowParameters = workflow?.workflow_definition.parameters ?? [];const handleCreate = (- cronExpression: string,+ cadence: CadencePayload,timezone: string,name: string,description: string,@@ -47,7 +48,7 @@ function WorkflowSchedulePanel({ onClose }: Props) {) => {createSchedule.mutate({- cron_expression: cronExpression,+ ...cadence,timezone,enabled: true,...(name && { name }),diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/cronUtils.ts b/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/cronUtils.tsindex 095bca5dd..bbd32d181 100644--- a/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/cronUtils.ts+++ b/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/cronUtils.ts@@ -29,10 +29,10 @@ export function isValidCron(expression: string): boolean {}}-// Mirror of the backend MIN_CRON_INTERVAL_SECONDS guard so the UI can reject+// Mirror of the backend MIN_SCHEDULE_INTERVAL_SECONDS guard so the UI can reject// too-frequent schedules before submitting (and avoid a bare 400 with no// inline preview feedback).-export const MIN_CRON_INTERVAL_SECONDS = 5 * 60;+export const MIN_SCHEDULE_INTERVAL_SECONDS = 5 * 60;// Sample a full day of firings (matching the backend) so a tight cluster outside// a small fixed window can't slip past, e.g. "0,5,...,55,59 * * * *" hiding the// 55->59 / 59->00 gaps. 25h covers any minute/hour cycle; the cap bounds "*/1".@@ -41,7 +41,7 @@ const CRON_INTERVAL_MAX_SAMPLES = 2000;export function meetsMinCronInterval(expression: string,- minimumIntervalSeconds: number = MIN_CRON_INTERVAL_SECONDS,+ minimumIntervalSeconds: number = MIN_SCHEDULE_INTERVAL_SECONDS,): boolean {try {const interval = CronExpressionParser.parse(expression);diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/scheduleCadence.test.ts b/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/scheduleCadence.test.tsnew file mode 100644index 000000000..dfb3e4d7e--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/scheduleCadence.test.ts@@ -0,0 +1,251 @@+import { describe, expect, it } from "vitest";+import type { OrganizationScheduleItem } from "@/routes/workflows/types/scheduleTypes";+import {+ buildCadencePayload,+ buildDuplicateSchedulePayload,+ formatInterval,+ getIntervalRuns,+ intervalDraftErrors,+ intervalDraftFromSeconds,+ upcomingFirstRun,+ zonedWallTimeToDate,+} from "./scheduleCadence";++const NOW = Date.parse("2026-11-01T12:00:00Z");++function orgSchedule(+ overrides: Partial<OrganizationScheduleItem>,+): OrganizationScheduleItem {+ return {+ workflow_schedule_id: "wfs_1",+ organization_id: "o_1",+ workflow_permanent_id: "wpid_1",+ workflow_title: "Report",+ cron_expression: null,+ interval_seconds: null,+ first_fire_at: null,+ timezone: "America/Los_Angeles",+ enabled: false,+ parameters: { city: "Toronto" },+ name: "Every 3 days",+ description: null,+ next_run: null,+ created_at: "2026-10-01T00:00:00",+ modified_at: "2026-10-01T00:00:00",+ ...overrides,+ };+}++describe("buildCadencePayload", () => {+ it("sends interval_seconds and no cron in interval mode", () => {+ expect(+ buildCadencePayload(+ "0 9 * * *",+ { every: "72", unit: "hours", firstFireAt: "" },+ "UTC",+ ),+ ).toEqual({ interval_seconds: 259200 });+ });++ it("reads the first run as wall-clock time in the schedule's timezone", () => {+ const draft = { every: "5", unit: "hours", firstFireAt: "" } as const;+ expect(+ buildCadencePayload(+ "",+ { ...draft, firstFireAt: "2026-11-01T01:30" },+ "America/New_York",+ ),+ ).toEqual({+ interval_seconds: 18000,+ first_fire_at: "2026-11-01T05:30:00.000Z",+ });+ expect(+ buildCadencePayload(+ "",+ { ...draft, firstFireAt: "2026-11-03T09:00" },+ "Asia/Kolkata",+ ),+ ).toEqual({+ interval_seconds: 18000,+ first_fire_at: "2026-11-03T03:30:00.000Z",+ });+ });++ it("sends only the cron in cron mode", () => {+ expect(buildCadencePayload("0 9 * * *", null, "UTC")).toEqual({+ cron_expression: "0 9 * * *",+ });+ });+});++describe("intervalDraftErrors", () => {+ it("puts each error on its own field", () => {+ expect(+ intervalDraftErrors(+ { every: "5", unit: "hours", firstFireAt: "2026-10-01T09:00" },+ "UTC",+ NOW,+ ),+ ).toEqual({+ every: null,+ firstFireAt: "First run must be at least a minute from now.",+ });+ expect(+ intervalDraftErrors({ every: "", unit: "hours", firstFireAt: "" }, "UTC"),+ ).toEqual({+ every: "Enter how often the schedule runs.",+ firstFireAt: null,+ });+ });++ it("rejects a first run inside the server's one-minute lead", () => {+ const draft = { every: "5", unit: "hours" } as const;+ expect(+ intervalDraftErrors(+ { ...draft, firstFireAt: "2026-11-01T12:00:30" },+ "UTC",+ NOW - 1_000,+ ).firstFireAt,+ ).toBe("First run must be at least a minute from now.");+ expect(+ intervalDraftErrors(+ { ...draft, firstFireAt: "2026-11-01T12:02" },+ "UTC",+ NOW,+ ).firstFireAt,+ ).toBe(null);+ });++ it("judges the first run in the schedule's timezone, not the browser's", () => {+ const draft = {+ every: "5",+ unit: "hours",+ firstFireAt: "2026-11-01T13:00",+ } as const;+ expect(+ intervalDraftErrors(draft, "America/New_York", NOW).firstFireAt,+ ).toBe(null);+ expect(intervalDraftErrors(draft, "Europe/Berlin", NOW).firstFireAt).toBe(+ "First run must be at least a minute from now.",+ );+ });+});++describe("zonedWallTimeToDate", () => {+ it.each([+ ["America/Los_Angeles", "2026-11-01T01:30", "2026-11-01T08:30:00.000Z"],+ ["Europe/Berlin", "2026-10-25T02:30", "2026-10-25T00:30:00.000Z"],+ ["America/Los_Angeles", "2026-07-01T09:00", "2026-07-01T16:00:00.000Z"],+ ])("resolves %s %s to its first occurrence", (timeZone, wall, iso) => {+ expect(zonedWallTimeToDate(wall, timeZone).toISOString()).toBe(iso);+ });++ it("rejects a wall time skipped by the spring-forward gap", () => {+ const draft = {+ every: "5",+ unit: "hours",+ firstFireAt: "2027-03-14T02:30",+ } as const;+ expect(+ Number.isNaN(+ zonedWallTimeToDate(draft.firstFireAt, "America/Los_Angeles").getTime(),+ ),+ ).toBe(true);+ expect(+ intervalDraftErrors(draft, "America/Los_Angeles", NOW).firstFireAt,+ ).toBe(+ "That time does not exist in America/Los_Angeles because of a daylight saving change.",+ );+ });+});++describe("intervalDraftFromSeconds", () => {+ it.each([+ [259200, "3", "days"],+ [18000, "5", "hours"],+ [5400, "90", "minutes"],+ ])("shows %i seconds as %s %s", (seconds, every, unit) => {+ expect(intervalDraftFromSeconds(seconds)).toMatchObject({ every, unit });+ });+});++describe("formatInterval", () => {+ it.each([+ [86400, "Every 24 hours"],+ [259200, "Every 3 days"],+ [3600, "Every hour"],+ [18000, "Every 5 hours"],+ [5400, "Every 90 minutes"],+ [301, "Every 301 seconds"],+ ])("formats %i seconds as %s", (seconds, label) => {+ expect(formatInterval(seconds)).toBe(label);+ });+});++describe("getIntervalRuns", () => {+ it("returns the anchor grid ticks strictly after now", () => {+ const runs = getIntervalRuns(+ 5 * 3600,+ new Date("2026-10-31T20:00:00Z"),+ 2,+ NOW,+ );+ expect(runs.map((run) => run.toISOString())).toEqual([+ "2026-11-01T16:00:00.000Z",+ "2026-11-01T21:00:00.000Z",+ ]);+ });+});++describe("upcomingFirstRun", () => {+ it("shows the first run only while it is in the future", () => {+ expect(upcomingFirstRun("2026-11-01T12:00:01Z", NOW)).toEqual(+ new Date("2026-11-01T12:00:01Z"),+ );+ expect(upcomingFirstRun("2026-11-01T12:00:00Z", NOW)).toBeNull();+ expect(upcomingFirstRun(null, NOW)).toBeNull();+ });+});++describe("buildDuplicateSchedulePayload", () => {+ it("copies an interval schedule onto the same grid from its next future tick", () => {+ expect(+ buildDuplicateSchedulePayload(+ orgSchedule({+ interval_seconds: 259200,+ first_fire_at: "2026-10-30T15:00:00Z",+ }),+ NOW,+ ),+ ).toEqual({+ interval_seconds: 259200,+ first_fire_at: "2026-11-02T15:00:00.000Z",+ timezone: "America/Los_Angeles",+ enabled: false,+ parameters: { city: "Toronto" },+ name: "Every 3 days (copy)",+ });+ });++ it("skips to the following tick when the next one is under 30 seconds away", () => {+ expect(+ buildDuplicateSchedulePayload(+ orgSchedule({+ interval_seconds: 18000,+ first_fire_at: "2026-11-01T02:00:10Z",+ }),+ NOW,+ ),+ ).toMatchObject({ first_fire_at: "2026-11-01T17:00:10.000Z" });+ });++ it("copies a cron schedule's cron and nothing interval-shaped", () => {+ const payload = buildDuplicateSchedulePayload(+ orgSchedule({ cron_expression: "0 9 * * 1" }),+ NOW,+ );+ expect(payload).toMatchObject({ cron_expression: "0 9 * * 1" });+ expect(payload).not.toHaveProperty("interval_seconds");+ expect(payload).not.toHaveProperty("first_fire_at");+ });+});diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/scheduleCadence.ts b/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/scheduleCadence.tsnew file mode 100644index 000000000..df0ce974e--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/scheduleCadence.ts@@ -0,0 +1,272 @@+import type {+ OrganizationScheduleItem,+ WorkflowSchedule,+} from "@/routes/workflows/types/scheduleTypes";+import {+ MIN_SCHEDULE_INTERVAL_SECONDS,+ cronToHumanReadable,+ getNextRuns,+ isValidCron,+ meetsMinCronInterval,+} from "./cronUtils";++export type IntervalUnit = "minutes" | "hours" | "days";++export type IntervalDraft = {+ // Raw text of the length field, so clearing it reads as empty rather than 0.+ every: string;+ unit: IntervalUnit;+ // A datetime-local value read as wall-clock time in the schedule's timezone, or "" to let the server pick.+ firstFireAt: string;+};++export type IntervalDraftErrors = {+ every: string | null;+ firstFireAt: string | null;+};++export type ScheduleCadence = Pick<+ WorkflowSchedule,+ "cron_expression" | "interval_seconds" | "first_fire_at"+>;++export type CadencePayload =+ | { cron_expression: string }+ | { interval_seconds: number; first_fire_at?: string };++export const DEFAULT_INTERVAL_DRAFT: IntervalDraft = {+ every: "1",+ unit: "days",+ firstFireAt: "",+};++const UNIT_SECONDS: Record<IntervalUnit, number> = {+ minutes: 60,+ hours: 60 * 60,+ days: 24 * 60 * 60,+};++const DAY_MS = 24 * 60 * 60 * 1000;++// Mirrors the backend's MIN_FIRST_FIRE_LEAD: an explicit first run must be at least this far out.+const MIN_FIRST_FIRE_LEAD_MS = 60_000;+// A duplicate's anchor must still clear that lead when the server receives it.+const DUPLICATE_ANCHOR_LEAD_MS = MIN_FIRST_FIRE_LEAD_MS + 30_000;++export function intervalDraftSeconds(draft: IntervalDraft): number {+ if (draft.every.trim() === "") return Number.NaN;+ return Math.round(Number(draft.every) * UNIT_SECONDS[draft.unit]);+}++export function intervalDraftFromSeconds(seconds: number): IntervalDraft {+ const unit: IntervalUnit =+ seconds % UNIT_SECONDS.days === 0+ ? "days"+ : seconds % UNIT_SECONDS.hours === 0+ ? "hours"+ : "minutes";+ return {+ every: String(seconds / UNIT_SECONDS[unit]),+ unit,+ firstFireAt: "",+ };+}++function timezoneOffsetMs(instant: number, timeZone: string): number {+ const parts = new Intl.DateTimeFormat("en-US", {+ timeZone,+ hourCycle: "h23",+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ hour: "2-digit",+ minute: "2-digit",+ second: "2-digit",+ }).formatToParts(new Date(instant));+ const part = (type: Intl.DateTimeFormatPartTypes) =>+ Number(parts.find((p) => p.type === type)?.value);+ const wallAsUtc = Date.UTC(+ part("year"),+ part("month") - 1,+ part("day"),+ part("hour"),+ part("minute"),+ part("second"),+ );+ return wallAsUtc - Math.floor(instant / 1000) * 1000;+}++export function zonedWallTimeToDate(wallTime: string, timeZone: string): Date {+ const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/.exec(wallTime);+ if (!match) return new Date(Number.NaN);+ const [year, month, day, hour, minute] = match.slice(1).map(Number) as [+ number,+ number,+ number,+ number,+ number,+ ];+ const wallAsUtc = Date.UTC(year, month - 1, day, hour, minute);+ // The offsets a day either side bracket any DST change: a skipped wall time round-trips under neither,+ // and a repeated one round-trips under both, where the earlier instant is its first occurrence.+ const candidates = [wallAsUtc - DAY_MS, wallAsUtc + DAY_MS]+ .map((probe) => wallAsUtc - timezoneOffsetMs(probe, timeZone))+ .filter(+ (instant) => instant + timezoneOffsetMs(instant, timeZone) === wallAsUtc,+ );+ return new Date(candidates.length > 0 ? Math.min(...candidates) : Number.NaN);+}++export function intervalDraftErrors(+ draft: IntervalDraft,+ timezone: string,+ now: number = Date.now(),+): IntervalDraftErrors {+ const seconds = intervalDraftSeconds(draft);+ let every: string | null = null;+ if (!Number.isFinite(seconds) || seconds <= 0) {+ every = "Enter how often the schedule runs.";+ } else if (seconds < MIN_SCHEDULE_INTERVAL_SECONDS) {+ every = "Schedule runs must be at least 5 minutes apart.";+ }+ let firstFireAt: string | null = null;+ if (draft.firstFireAt) {+ const instant = zonedWallTimeToDate(draft.firstFireAt, timezone).getTime();+ if (Number.isNaN(instant)) {+ firstFireAt = `That time does not exist in ${timezone} because of a daylight saving change.`;+ } else if (instant < now + MIN_FIRST_FIRE_LEAD_MS) {+ firstFireAt = "First run must be at least a minute from now.";+ }+ }+ return { every, firstFireAt };+}++function intervalLength(seconds: number): [number, string] {+ // "Every day" would read as a fixed time of day, which a 24-hour interval drifts off across DST.+ if (seconds % 86400 === 0 && seconds > 86400) return [seconds / 86400, "day"];+ if (seconds % 3600 === 0) return [seconds / 3600, "hour"];+ if (seconds % 60 === 0) return [seconds / 60, "minute"];+ return [seconds, "second"];+}++export function formatIntervalDuration(seconds: number): string {+ const [count, unit] = intervalLength(seconds);+ return `${count} ${unit}${count === 1 ? "" : "s"}`;+}++export function formatInterval(seconds: number): string {+ const [count, unit] = intervalLength(seconds);+ return count === 1 ? `Every ${unit}` : `Every ${count} ${unit}s`;+}++// Mirrors the backend helper: the first tick strictly after now on the anchor + k * interval grid.+export function getIntervalRuns(+ intervalSeconds: number,+ firstFireAt: Date,+ count: number,+ now: number = Date.now(),+): Date[] {+ const anchor = firstFireAt.getTime();+ const step = intervalSeconds * 1000;+ const first = now < anchor ? 0 : Math.floor((now - anchor) / step) + 1;+ return Array.from(+ { length: count },+ (_, i) => new Date(anchor + (first + i) * step),+ );+}++export function upcomingFirstRun(+ firstFireAt: string | null,+ now: number = Date.now(),+): Date | null {+ const firstRun = firstFireAt ? new Date(firstFireAt) : null;+ return firstRun && firstRun.getTime() > now ? firstRun : null;+}++export function describeCadence(schedule: ScheduleCadence): string {+ if (schedule.interval_seconds) {+ return formatInterval(schedule.interval_seconds);+ }+ return cronToHumanReadable(schedule.cron_expression ?? "");+}++export function getCadenceNextRuns(+ schedule: ScheduleCadence,+ timezone: string,+ count: number,+): Date[] {+ if (schedule.interval_seconds && schedule.first_fire_at) {+ return getIntervalRuns(+ schedule.interval_seconds,+ new Date(schedule.first_fire_at),+ count,+ );+ }+ return schedule.cron_expression+ ? getNextRuns(schedule.cron_expression, timezone, count)+ : [];+}++export function cronBelowMinInterval(cronExpression: string | null): boolean {+ return (+ cronExpression !== null &&+ isValidCron(cronExpression) &&+ !meetsMinCronInterval(cronExpression)+ );+}++export function isCadenceAccepted(+ cronExpression: string,+ interval: IntervalDraft | null,+ timezone: string,+): boolean {+ if (interval) {+ const errors = intervalDraftErrors(interval, timezone);+ return errors.every === null && errors.firstFireAt === null;+ }+ return isValidCron(cronExpression) && meetsMinCronInterval(cronExpression);+}++export function buildCadencePayload(+ cronExpression: string,+ interval: IntervalDraft | null,+ timezone: string,+): CadencePayload {+ if (!interval) {+ return { cron_expression: cronExpression };+ }+ return {+ interval_seconds: intervalDraftSeconds(interval),+ ...(interval.firstFireAt && {+ first_fire_at: zonedWallTimeToDate(+ interval.firstFireAt,+ timezone,+ ).toISOString(),+ }),+ };+}++export function buildDuplicateSchedulePayload(+ schedule: OrganizationScheduleItem,+ now: number = Date.now(),+) {+ const cadence: CadencePayload =+ schedule.interval_seconds && schedule.first_fire_at+ ? {+ interval_seconds: schedule.interval_seconds,+ first_fire_at: getIntervalRuns(+ schedule.interval_seconds,+ new Date(schedule.first_fire_at),+ 1,+ now + DUPLICATE_ANCHOR_LEAD_MS,+ )[0]!.toISOString(),+ }+ : { cron_expression: schedule.cron_expression ?? "" };+ return {+ ...cadence,+ timezone: schedule.timezone,+ enabled: schedule.enabled,+ parameters: schedule.parameters,+ name: `${schedule.name ?? schedule.workflow_title} (copy)`,+ };+}diff --git a/skyvern-frontend/src/routes/workflows/types/scheduleTypes.ts b/skyvern-frontend/src/routes/workflows/types/scheduleTypes.tsindex fb46e0e93..67171aae1 100644--- a/skyvern-frontend/src/routes/workflows/types/scheduleTypes.ts+++ b/skyvern-frontend/src/routes/workflows/types/scheduleTypes.ts@@ -2,7 +2,9 @@ export type WorkflowSchedule = {workflow_schedule_id: string;organization_id: string;workflow_permanent_id: string;- cron_expression: string;+ cron_expression: string | null;+ interval_seconds: number | null;+ first_fire_at: string | null;timezone: string;enabled: boolean;parameters: Record<string, unknown> | null;@@ -24,7 +26,9 @@ export type WorkflowScheduleListResponse = {};export type CreateScheduleRequest = {- cron_expression: string;+ cron_expression?: string;+ interval_seconds?: number;+ first_fire_at?: string;timezone: string;enabled?: boolean;parameters?: Record<string, unknown> | null;@@ -33,7 +37,9 @@ export type CreateScheduleRequest = {};export type UpdateScheduleRequest = {- cron_expression: string;+ cron_expression?: string;+ interval_seconds?: number;+ first_fire_at?: string;timezone: string;// Omit to preserve the schedule's current enable/disable state on the server.enabled?: boolean;@@ -47,7 +53,9 @@ export type OrganizationScheduleItem = {organization_id: string;workflow_permanent_id: string;workflow_title: string;- cron_expression: string;+ cron_expression: string | null;+ interval_seconds: number | null;+ first_fire_at: string | null;timezone: string;enabled: boolean;parameters: Record<string, unknown> | null;diff --git a/skyvern/cli/mcp_tools/schedule.py b/skyvern/cli/mcp_tools/schedule.pyindex 03d606004..85eca9a16 100644--- a/skyvern/cli/mcp_tools/schedule.py+++ b/skyvern/cli/mcp_tools/schedule.py@@ -2,6 +2,7 @@from __future__ import annotations+from datetime import datetimefrom typing import Annotated, Anyimport structlog@@ -22,6 +23,8 @@ def _serialize_schedule(s: Any) -> dict[str, Any]:"organization_id": s.organization_id,"workflow_permanent_id": s.workflow_permanent_id,"cron_expression": s.cron_expression,+ "interval_seconds": s.interval_seconds,+ "first_fire_at": s.first_fire_at.isoformat() if s.first_fire_at else None,"timezone": s.timezone,"enabled": s.enabled,"parameters": s.parameters,@@ -49,6 +52,8 @@ def _serialize_org_schedule_item(item: Any) -> dict[str, Any]:"workflow_permanent_id": item.workflow_permanent_id,"workflow_title": item.workflow_title,"cron_expression": item.cron_expression,+ "interval_seconds": item.interval_seconds,+ "first_fire_at": item.first_fire_at.isoformat() if item.first_fire_at else None,"timezone": item.timezone,"enabled": item.enabled,"parameters": item.parameters,@@ -180,8 +185,21 @@ async def skyvern_schedule_get(async def skyvern_schedule_create(workflow_permanent_id: Annotated[str, Field(description="Workflow ID (starts with wpid_)")],- cron_expression: Annotated[str, Field(description="Cron expression, e.g. '0 9 * * *'")],+ *,+ cron_expression: Annotated[+ str | None, Field(description="Cron expression, e.g. '0 9 * * *'. Set this or interval_seconds.")+ ] = None,timezone: Annotated[str, Field(description="IANA timezone, e.g. 'UTC' or 'America/New_York'")],+ interval_seconds: Annotated[+ int | None,+ Field(description="Run every N seconds (minimum 300), e.g. 259200 for every 72 hours. Set this or cron."),+ ] = None,+ first_fire_at: Annotated[+ datetime | None,+ Field(+ description="First run of an interval schedule, ISO 8601 with offset. Defaults to one interval from now."+ ),+ ] = None,enabled: Annotated[bool, Field(description="Whether the schedule fires immediately. Defaults to True.")] = True,parameters: Annotated[dict[str, Any] | None,@@ -190,9 +208,9 @@ async def skyvern_schedule_create(name: Annotated[str | None, Field(description="Human-readable schedule name.")] = None,description: Annotated[str | None, Field(description="Optional description.")] = None,) -> dict[str, Any]:- """Create a recurring schedule for an existing workflow.+ """Create a recurring schedule for an existing workflow, on a cron or a fixed interval.- Cron expression and timezone are validated server-side; a 400 is surfaced+ Cadence and timezone are validated server-side and errors are surfacedverbatim. Returns 501 if workflow schedules are disabled in this build."""if err := validate_workflow_id(workflow_permanent_id, "skyvern_schedule_create"):@@ -204,6 +222,8 @@ async def skyvern_schedule_create(resp = await skyvern.schedules.create(workflow_permanent_id,cron_expression=cron_expression,+ interval_seconds=interval_seconds,+ first_fire_at=first_fire_at,timezone=timezone,enabled=enabled,parameters=parameters,@@ -264,6 +284,7 @@ def _check_update_mutex(def _check_update_exact_completeness(cron_expression: str | None,+ interval_seconds: int | None,timezone: str | None,enabled: bool | None,parameters: dict[str, Any] | None,@@ -280,8 +301,8 @@ def _check_update_exact_completeness(and silently flip a paused schedule active or wipe metadata."""missing: list[str] = []- if cron_expression is None:- missing.append("cron_expression")+ if cron_expression is None and interval_seconds is None:+ missing.append("cron_expression or interval_seconds")if timezone is None:missing.append("timezone")if enabled is None:@@ -305,6 +326,13 @@ async def skyvern_schedule_update(workflow_permanent_id: Annotated[str, Field(description="Workflow ID (starts with wpid_)")],workflow_schedule_id: Annotated[str, Field(description="Schedule ID (starts with wfs_)")],cron_expression: Annotated[str | None, Field(description="New cron expression.")] = None,+ interval_seconds: Annotated[+ int | None, Field(description="New fixed interval in seconds (minimum 300); switches a cron schedule.")+ ] = None,+ first_fire_at: Annotated[+ datetime | None,+ Field(description="New future first run for an interval schedule, ISO 8601 with offset."),+ ] = None,timezone: Annotated[str | None, Field(description="New IANA timezone.")] = None,enabled: Annotated[bool | None, Field(description="New enabled flag.")] = None,parameters: Annotated[dict[str, Any] | None, Field(description="New workflow input parameters.")] = None,@@ -339,7 +367,10 @@ async def skyvern_schedule_update(if err := _check_update_mutex(parameters, clear_parameters, name, clear_name, description, clear_description):return err- any_value_set = any(v is not None for v in (cron_expression, timezone, enabled, parameters, name, description))+ any_value_set = any(+ v is not None+ for v in (cron_expression, interval_seconds, first_fire_at, timezone, enabled, parameters, name, description)+ )any_clear_set = any((clear_parameters, clear_name, clear_description))if not exact and not any_value_set and not any_clear_set:return _input_error(@@ -360,6 +391,7 @@ async def skyvern_schedule_update(if exact:if err := _check_update_exact_completeness(cron_expression,+ interval_seconds,timezone,enabled,parameters,@@ -372,6 +404,8 @@ async def skyvern_schedule_update(return err# In exact mode, every field is supplied explicitly; clear flags map to None.body_cron = cron_expression+ body_interval = interval_seconds+ body_first_fire_at = first_fire_atbody_tz = timezonebody_enabled = enabledbody_params = None if clear_parameters else parameters@@ -408,7 +442,24 @@ async def skyvern_schedule_update(snapshot_modified_at=existing.modified_at.isoformat() if existing.modified_at else None,)- body_cron = cron_expression if cron_expression is not None else existing.cron_expression+ if cron_expression is None and interval_seconds is None and first_fire_at is None:+ body_cron = existing.cron_expression+ body_interval = existing.interval_seconds+ # Omitted, the route keeps the stored anchor even once it is past.+ body_first_fire_at = None+ else:+ # Never merge a stored cadence into a new one of the other kind; the server rejects cron plus interval.+ body_cron = cron_expression+ body_interval = interval_seconds+ body_first_fire_at = first_fire_at+ if cron_expression is None and interval_seconds is None:+ if existing.interval_seconds is None:+ return _input_error(+ "skyvern_schedule_update",+ "first_fire_at applies only to interval schedules; this schedule runs on cron.",+ "Pass interval_seconds with first_fire_at to switch it to an interval schedule.",+ )+ body_interval = existing.interval_secondsbody_tz = timezone if timezone is not None else existing.timezone# Omitted, the route keeps the stored state, so a concurrent pause/resume is not undone.body_enabled = enabled@@ -423,6 +474,8 @@ async def skyvern_schedule_update(workflow_permanent_id,workflow_schedule_id,cron_expression=body_cron,+ interval_seconds=body_interval,+ first_fire_at=body_first_fire_at,timezone=body_tz,parameters=body_params,name=body_name,diff --git a/skyvern/cli/schedule_command.py b/skyvern/cli/schedule_command.pyindex e880aee7c..dab366d98 100644--- a/skyvern/cli/schedule_command.py+++ b/skyvern/cli/schedule_command.py@@ -3,6 +3,7 @@from __future__ import annotationsimport json+from datetime import datetimefrom typing import Anyimport typer@@ -97,6 +98,15 @@ def _parse_parameters(value: str | None) -> dict[str, Any] | None:return parsed+def _parse_first_fire_at(value: str | None) -> datetime | None:+ if value is None:+ return None+ try:+ return datetime.fromisoformat(value)+ except ValueError as e:+ raise typer.BadParameter(f"--first-fire-at must be an ISO 8601 date-time: {e}") from e++@schedule_app.command("list")def schedule_list(ctx: typer.Context,@@ -180,7 +190,15 @@ def schedule_get(@schedule_app.command("create")def schedule_create(workflow_id: str = typer.Option(..., "--workflow-id", help="Workflow ID (wpid_…)."),- cron: str = typer.Option(..., "--cron", help="Cron expression, e.g. '0 9 * * *'."),+ cron: str | None = typer.Option(+ None, "--cron", help="Cron expression, e.g. '0 9 * * *'. Set this or --interval-seconds."+ ),+ interval_seconds: int | None = typer.Option(+ None, "--interval-seconds", help="Run every N seconds (minimum 300), e.g. 259200 for every 72 hours."+ ),+ first_fire_at: str | None = typer.Option(+ None, "--first-fire-at", help="First run of an interval schedule, ISO 8601 with offset."+ ),timezone: str = typer.Option("UTC", "--timezone", help="IANA timezone name."),enabled: bool = typer.Option(True, "--enabled/--disabled", help="Whether the schedule fires immediately."),parameters: str | None = typer.Option(None, "--parameters", help="Workflow input parameters as JSON object."),@@ -188,13 +206,16 @@ def schedule_create(description: str | None = typer.Option(None, "--description", help="Schedule description."),json_output: bool = typer.Option(False, "--json", help="Output as JSON."),) -> None:- """Create a schedule for a workflow."""+ """Create a schedule for a workflow, on a cron or a fixed interval."""params_dict = _parse_parameters(parameters)+ first_fire_at_dt = _parse_first_fire_at(first_fire_at)async def _run() -> dict[str, Any]:return await tool_schedule_create(workflow_permanent_id=workflow_id,cron_expression=cron,+ interval_seconds=interval_seconds,+ first_fire_at=first_fire_at_dt,timezone=timezone,enabled=enabled,parameters=params_dict,@@ -205,7 +226,7 @@ def schedule_create(run_tool(_run,json_output=json_output,- hint_on_exception="Check cron, timezone, and parameter shape.",+ hint_on_exception="Check the cron or interval, timezone, and parameter shape.",action="skyvern_schedule_create",)@@ -215,6 +236,12 @@ def schedule_update(workflow_id: str = typer.Option(..., "--workflow-id", help="Workflow ID (wpid_…)."),schedule_id: str = typer.Option(..., "--id", "--schedule-id", help="Schedule ID (wfs_…)."),cron: str | None = typer.Option(None, "--cron", help="New cron expression."),+ interval_seconds: int | None = typer.Option(+ None, "--interval-seconds", help="New fixed interval in seconds (minimum 300)."+ ),+ first_fire_at: str | None = typer.Option(+ None, "--first-fire-at", help="New future first run for an interval schedule, ISO 8601 with offset."+ ),timezone: str | None = typer.Option(None, "--timezone", help="New IANA timezone."),enabled: bool | None = typer.Option(None,@@ -248,12 +275,15 @@ def schedule_update(raise typer.BadParameter("Cannot pass both --parameters and --clear-parameters.")params_dict = _parse_parameters(parameters)+ first_fire_at_dt = _parse_first_fire_at(first_fire_at)async def _run() -> dict[str, Any]:return await tool_schedule_update(workflow_permanent_id=workflow_id,workflow_schedule_id=schedule_id,cron_expression=cron,+ interval_seconds=interval_seconds,+ first_fire_at=first_fire_at_dt,timezone=timezone,enabled=enabled,parameters=params_dict,@@ -268,7 +298,7 @@ def schedule_update(run_tool(_run,json_output=json_output,- hint_on_exception="Check cron, timezone, and parameter shape.",+ hint_on_exception="Check the cron or interval, timezone, and parameter shape.",action="skyvern_schedule_update",)diff --git a/skyvern/client/schedules/client.py b/skyvern/client/schedules/client.pyindex f3ad4a267..439bc21cf 100644--- a/skyvern/client/schedules/client.py+++ b/skyvern/client/schedules/client.py@@ -1,5 +1,6 @@# This file was auto-generated by Fern from our API Definition.+import datetime as dtimport typingfrom ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper@@ -113,7 +114,9 @@ class SchedulesClient:self,workflow_permanent_id: str,*,- cron_expression: str,+ cron_expression: typing.Optional[str] = OMIT,+ interval_seconds: typing.Optional[int] = OMIT,+ first_fire_at: typing.Optional[dt.datetime] = OMIT,timezone: str,enabled: typing.Optional[bool] = OMIT,parameters: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,@@ -126,7 +129,11 @@ class SchedulesClient:----------workflow_permanent_id : str- cron_expression : str+ cron_expression : typing.Optional[str]++ interval_seconds : typing.Optional[int]++ first_fire_at : typing.Optional[dt.datetime]timezone : str@@ -162,6 +169,8 @@ class SchedulesClient:_response = self._raw_client.create(workflow_permanent_id,cron_expression=cron_expression,+ interval_seconds=interval_seconds,+ first_fire_at=first_fire_at,timezone=timezone,enabled=enabled,parameters=parameters,@@ -213,7 +222,9 @@ class SchedulesClient:workflow_permanent_id: str,workflow_schedule_id: str,*,- cron_expression: str,+ cron_expression: typing.Optional[str] = OMIT,+ interval_seconds: typing.Optional[int] = OMIT,+ first_fire_at: typing.Optional[dt.datetime] = OMIT,timezone: str,enabled: typing.Optional[bool] = OMIT,parameters: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,@@ -228,7 +239,11 @@ class SchedulesClient:workflow_schedule_id : str- cron_expression : str+ cron_expression : typing.Optional[str]++ interval_seconds : typing.Optional[int]++ first_fire_at : typing.Optional[dt.datetime]timezone : str@@ -266,6 +281,8 @@ class SchedulesClient:workflow_permanent_id,workflow_schedule_id,cron_expression=cron_expression,+ interval_seconds=interval_seconds,+ first_fire_at=first_fire_at,timezone=timezone,enabled=enabled,parameters=parameters,@@ -507,7 +524,9 @@ class AsyncSchedulesClient:self,workflow_permanent_id: str,*,- cron_expression: str,+ cron_expression: typing.Optional[str] = OMIT,+ interval_seconds: typing.Optional[int] = OMIT,+ first_fire_at: typing.Optional[dt.datetime] = OMIT,timezone: str,enabled: typing.Optional[bool] = OMIT,parameters: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,@@ -520,7 +539,11 @@ class AsyncSchedulesClient:----------workflow_permanent_id : str- cron_expression : str+ cron_expression : typing.Optional[str]++ interval_seconds : typing.Optional[int]++ first_fire_at : typing.Optional[dt.datetime]timezone : str@@ -564,6 +587,8 @@ class AsyncSchedulesClient:_response = await self._raw_client.create(workflow_permanent_id,cron_expression=cron_expression,+ interval_seconds=interval_seconds,+ first_fire_at=first_fire_at,timezone=timezone,enabled=enabled,parameters=parameters,@@ -625,7 +650,9 @@ class AsyncSchedulesClient:workflow_permanent_id: str,workflow_schedule_id: str,*,- cron_expression: str,+ cron_expression: typing.Optional[str] = OMIT,+ interval_seconds: typing.Optional[int] = OMIT,+ first_fire_at: typing.Optional[dt.datetime] = OMIT,timezone: str,enabled: typing.Optional[bool] = OMIT,parameters: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,@@ -640,7 +667,11 @@ class AsyncSchedulesClient:workflow_schedule_id : str- cron_expression : str+ cron_expression : typing.Optional[str]++ interval_seconds : typing.Optional[int]++ first_fire_at : typing.Optional[dt.datetime]timezone : str@@ -686,6 +717,8 @@ class AsyncSchedulesClient:workflow_permanent_id,workflow_schedule_id,cron_expression=cron_expression,+ interval_seconds=interval_seconds,+ first_fire_at=first_fire_at,timezone=timezone,enabled=enabled,parameters=parameters,diff --git a/skyvern/client/schedules/raw_client.py b/skyvern/client/schedules/raw_client.pyindex f350a85b5..a2ef2f469 100644--- a/skyvern/client/schedules/raw_client.py+++ b/skyvern/client/schedules/raw_client.py@@ -1,5 +1,6 @@# This file was auto-generated by Fern from our API Definition.+import datetime as dtimport typingfrom json.decoder import JSONDecodeError@@ -142,7 +143,9 @@ class RawSchedulesClient:self,workflow_permanent_id: str,*,- cron_expression: str,+ cron_expression: typing.Optional[str] = OMIT,+ interval_seconds: typing.Optional[int] = OMIT,+ first_fire_at: typing.Optional[dt.datetime] = OMIT,timezone: str,enabled: typing.Optional[bool] = OMIT,parameters: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,@@ -155,7 +158,11 @@ class RawSchedulesClient:----------workflow_permanent_id : str- cron_expression : str+ cron_expression : typing.Optional[str]++ interval_seconds : typing.Optional[int]++ first_fire_at : typing.Optional[dt.datetime]timezone : str@@ -180,6 +187,8 @@ class RawSchedulesClient:method="POST",json={"cron_expression": cron_expression,+ "interval_seconds": interval_seconds,+ "first_fire_at": first_fire_at,"timezone": timezone,"enabled": enabled,"parameters": parameters,@@ -276,7 +285,9 @@ class RawSchedulesClient:workflow_permanent_id: str,workflow_schedule_id: str,*,- cron_expression: str,+ cron_expression: typing.Optional[str] = OMIT,+ interval_seconds: typing.Optional[int] = OMIT,+ first_fire_at: typing.Optional[dt.datetime] = OMIT,timezone: str,enabled: typing.Optional[bool] = OMIT,parameters: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,@@ -291,7 +302,11 @@ class RawSchedulesClient:workflow_schedule_id : str- cron_expression : str+ cron_expression : typing.Optional[str]++ interval_seconds : typing.Optional[int]++ first_fire_at : typing.Optional[dt.datetime]timezone : str@@ -316,6 +331,8 @@ class RawSchedulesClient:method="PUT",json={"cron_expression": cron_expression,+ "interval_seconds": interval_seconds,+ "first_fire_at": first_fire_at,"timezone": timezone,"enabled": enabled,"parameters": parameters,@@ -636,7 +653,9 @@ class AsyncRawSchedulesClient:self,workflow_permanent_id: str,*,- cron_expression: str,+ cron_expression: typing.Optional[str] = OMIT,+ interval_seconds: typing.Optional[int] = OMIT,+ first_fire_at: typing.Optional[dt.datetime] = OMIT,timezone: str,enabled: typing.Optional[bool] = OMIT,parameters: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,@@ -649,7 +668,11 @@ class AsyncRawSchedulesClient:----------workflow_permanent_id : str- cron_expression : str+ cron_expression : typing.Optional[str]++ interval_seconds : typing.Optional[int]++ first_fire_at : typing.Optional[dt.datetime]timezone : str@@ -674,6 +697,8 @@ class AsyncRawSchedulesClient:method="POST",json={"cron_expression": cron_expression,+ "interval_seconds": interval_seconds,+ "first_fire_at": first_fire_at,"timezone": timezone,"enabled": enabled,"parameters": parameters,@@ -770,7 +795,9 @@ class AsyncRawSchedulesClient:workflow_permanent_id: str,workflow_schedule_id: str,*,- cron_expression: str,+ cron_expression: typing.Optional[str] = OMIT,+ interval_seconds: typing.Optional[int] = OMIT,+ first_fire_at: typing.Optional[dt.datetime] = OMIT,timezone: str,enabled: typing.Optional[bool] = OMIT,parameters: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,@@ -785,7 +812,11 @@ class AsyncRawSchedulesClient:workflow_schedule_id : str- cron_expression : str+ cron_expression : typing.Optional[str]++ interval_seconds : typing.Optional[int]++ first_fire_at : typing.Optional[dt.datetime]timezone : str@@ -810,6 +841,8 @@ class AsyncRawSchedulesClient:method="PUT",json={"cron_expression": cron_expression,+ "interval_seconds": interval_seconds,+ "first_fire_at": first_fire_at,"timezone": timezone,"enabled": enabled,"parameters": parameters,diff --git a/skyvern/client/types/organization_schedule_item.py b/skyvern/client/types/organization_schedule_item.pyindex d288100ad..6217bfff1 100644--- a/skyvern/client/types/organization_schedule_item.py+++ b/skyvern/client/types/organization_schedule_item.py@@ -21,7 +21,9 @@ class OrganizationScheduleItem(UniversalBaseModel):organization_id: strworkflow_permanent_id: strworkflow_title: str- cron_expression: str+ cron_expression: typing.Optional[str] = None+ interval_seconds: typing.Optional[int] = None+ first_fire_at: typing.Optional[dt.datetime] = Nonetimezone: strenabled: boolparameters: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = Nonediff --git a/skyvern/client/types/workflow_schedule.py b/skyvern/client/types/workflow_schedule.pyindex 1f4303095..64155aa76 100644--- a/skyvern/client/types/workflow_schedule.py+++ b/skyvern/client/types/workflow_schedule.py@@ -11,7 +11,9 @@ class WorkflowSchedule(UniversalBaseModel):workflow_schedule_id: strorganization_id: strworkflow_permanent_id: str- cron_expression: str+ cron_expression: typing.Optional[str] = None+ interval_seconds: typing.Optional[int] = None+ first_fire_at: typing.Optional[dt.datetime] = Nonetimezone: strenabled: boolparameters: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = Nonediff --git a/skyvern/client/types/workflow_schedule_upsert_request.py b/skyvern/client/types/workflow_schedule_upsert_request.pyindex 72bbdece7..bf7f095bf 100644--- a/skyvern/client/types/workflow_schedule_upsert_request.py+++ b/skyvern/client/types/workflow_schedule_upsert_request.py@@ -1,5 +1,6 @@# This file was auto-generated by Fern from our API Definition.+import datetime as dtimport typingimport pydantic@@ -7,7 +8,9 @@ from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModelclass WorkflowScheduleUpsertRequest(UniversalBaseModel):- cron_expression: str+ cron_expression: typing.Optional[str] = None+ interval_seconds: typing.Optional[int] = None+ first_fire_at: typing.Optional[dt.datetime] = Nonetimezone: strenabled: typing.Optional[bool] = Noneparameters: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = Nonediff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.pyindex 921d46dee..f0de30bfa 100644--- a/skyvern/forge/agent_functions.py+++ b/skyvern/forge/agent_functions.py@@ -1904,11 +1904,13 @@ class AgentFunction:organization_id: str,workflow_permanent_id: str,workflow_schedule_id: str,- cron_expression: str,+ cron_expression: str | None,timezone: str,enabled: bool,parameters: dict[str, Any] | None = None,max_elapsed_time_minutes: int | None = None,+ interval_seconds: int | None = None,+ first_fire_at: datetime | None = None,) -> None:"""Upsert a recurring schedule with the execution backend (e.g. Temporal).diff --git a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py b/skyvern/forge/sdk/copilot/tools/mcp_hooks.pyindex 6914bba9c..25992f1f2 100644--- a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py+++ b/skyvern/forge/sdk/copilot/tools/mcp_hooks.py@@ -2499,9 +2499,10 @@ def _build_skyvern_mcp_overlays("create_workflow_schedule": _workflow_schedule_overlay("Schedule the saved workflow open in this chat. Cadence and IANA timezone must come from the user; ""if either is missing, ask rather than assume UTC or local time. Leave name unset unless the user "- "gave one. Ask before duplicating a listed schedule. Cron cannot express an elapsed interval such "- "as 'every 36 hours'; do not approximate one. In your reply, give the saved wfs_ ID, timezone, "- "enabled state and next run from the result.",+ "gave one. Ask before duplicating a listed schedule. Cadence is a cron expression or interval_seconds, "+ "which runs a fixed elapsed interval counted from first_fire_at; cron cannot express an elapsed interval "+ "such as 'every 36 hours'. In your reply, give the saved wfs_ ID, timezone, enabled state and next run "+ "from the result.",pre_hook=_create_workflow_schedule_pre_hook,),"update_workflow_schedule": _workflow_schedule_overlay(diff --git a/skyvern/forge/sdk/db/_sentinels.py b/skyvern/forge/sdk/db/_sentinels.pyindex baa59d598..c6141db1b 100644--- a/skyvern/forge/sdk/db/_sentinels.py+++ b/skyvern/forge/sdk/db/_sentinels.py@@ -1,4 +1,12 @@"""Sentinel values for the database layer."""-# Sentinel for distinguishing "not passed" from "passed as None" in update methods.-_UNSET = object()+from enum import Enum+++class _Unset(Enum):+ TOKEN = "unset"+++# Sentinel for distinguishing "not passed" from "passed as None" in update methods; a single-member Enum so+# `x is not _UNSET` narrows a `T | _Unset` parameter to T.+_UNSET = _Unset.TOKENdiff --git a/skyvern/forge/sdk/db/models.py b/skyvern/forge/sdk/db/models.pyindex 55ed73e3e..b43ec0afe 100644--- a/skyvern/forge/sdk/db/models.py+++ b/skyvern/forge/sdk/db/models.py@@ -785,12 +785,19 @@ class WorkflowScheduleModel(Base):postgresql_where=text("deleted_at IS NULL"),),Index("idx_workflow_schedules_org_enabled", "organization_id", "enabled"),+ CheckConstraint(+ "(cron_expression IS NULL) <> (interval_seconds IS NULL) "+ "AND (interval_seconds IS NULL) = (first_fire_at IS NULL)",+ name="ck_workflow_schedules_one_cadence",+ ),)workflow_schedule_id = Column(String, primary_key=True, default=generate_workflow_schedule_id)organization_id = Column(String, nullable=False)workflow_permanent_id = Column(String, nullable=False, index=True)- cron_expression = Column(String, nullable=False)+ cron_expression = Column(String, nullable=True)+ interval_seconds = Column(Integer, nullable=True)+ first_fire_at = Column(DateTime, nullable=True)timezone = Column(String, nullable=False)enabled = Column(Boolean, nullable=False, default=True, server_default=sqlalchemy.true())parameters = Column(JSON, nullable=True)diff --git a/skyvern/forge/sdk/db/repositories/schedules.py b/skyvern/forge/sdk/db/repositories/schedules.pyindex b005f386c..d1457f8b1 100644--- a/skyvern/forge/sdk/db/repositories/schedules.py+++ b/skyvern/forge/sdk/db/repositories/schedules.py@@ -16,18 +16,22 @@ from skyvern.forge.sdk.db.exceptions import ScheduleLimitExceededErrorfrom skyvern.forge.sdk.db.models import WorkflowModel, WorkflowRunModel, WorkflowScheduleModelfrom skyvern.forge.sdk.db.utils import convert_to_workflow_schedulefrom skyvern.forge.sdk.schemas.workflow_schedules import OrganizationScheduleItem, WorkflowSchedule-from skyvern.forge.sdk.workflow.schedules import compute_next_run+from skyvern.forge.sdk.workflow.schedules import as_utc, compute_next_runif TYPE_CHECKING:from skyvern.forge.sdk.db.base_alchemy_db import _SessionFactory-from skyvern.forge.sdk.db._sentinels import _UNSET+from skyvern.forge.sdk.db._sentinels import _UNSET, _UnsetLOG = structlog.get_logger()register_passthrough_exception(ScheduleLimitExceededError)+def _naive_utc(value: datetime | None) -> datetime | None:+ return as_utc(value).replace(tzinfo=None) if value is not None else None++class SchedulesRepository(BaseRepository):"""Database operations for workflow schedules."""@@ -46,19 +50,23 @@ class SchedulesRepository(BaseRepository):self,organization_id: str,workflow_permanent_id: str,- cron_expression: str,+ cron_expression: str | None,timezone: str,enabled: bool,parameters: dict[str, Any] | None = None,backend_schedule_id: str | None = None,name: str | None = None,description: str | None = None,+ interval_seconds: int | None = None,+ first_fire_at: datetime | None = None,) -> WorkflowSchedule:async with self.Session() as session:workflow_schedule = WorkflowScheduleModel(organization_id=organization_id,workflow_permanent_id=workflow_permanent_id,cron_expression=cron_expression,+ interval_seconds=interval_seconds,+ first_fire_at=_naive_utc(first_fire_at),timezone=timezone,enabled=enabled,parameters=parameters,@@ -77,12 +85,14 @@ class SchedulesRepository(BaseRepository):organization_id: str,workflow_permanent_id: str,max_schedules: int | None,- cron_expression: str,+ cron_expression: str | None,timezone: str,enabled: bool,parameters: dict[str, Any] | None = None,name: str | None = None,description: str | None = None,+ interval_seconds: int | None = None,+ first_fire_at: datetime | None = None,) -> WorkflowSchedule:"""Create a schedule atomically with org-wide limit enforcement.@@ -109,6 +119,8 @@ class SchedulesRepository(BaseRepository):parameters,name,description,+ interval_seconds,+ first_fire_at,use_advisory_lock=False,)return await self._create_schedule_with_limit_inner(@@ -121,6 +133,8 @@ class SchedulesRepository(BaseRepository):parameters,name,description,+ interval_seconds,+ first_fire_at,use_advisory_lock=True,)@@ -131,12 +145,14 @@ class SchedulesRepository(BaseRepository):organization_id: str,workflow_permanent_id: str,max_schedules: int | None,- cron_expression: str,+ cron_expression: str | None,timezone: str,enabled: bool,parameters: dict[str, Any] | None,name: str | None,description: str | None,+ interval_seconds: int | None,+ first_fire_at: datetime | None,*,use_advisory_lock: bool,) -> WorkflowSchedule:@@ -168,6 +184,8 @@ class SchedulesRepository(BaseRepository):organization_id=organization_id,workflow_permanent_id=workflow_permanent_id,cron_expression=cron_expression,+ interval_seconds=interval_seconds,+ first_fire_at=_naive_utc(first_fire_at),timezone=timezone,enabled=enabled,parameters=parameters,@@ -211,13 +229,15 @@ class SchedulesRepository(BaseRepository):self,workflow_schedule_id: str,organization_id: str,- cron_expression: str,+ cron_expression: str | None,timezone: str,- enabled: bool | object = _UNSET,+ enabled: bool | _Unset = _UNSET,parameters: dict[str, Any] | None = None,- backend_schedule_id: str | None | object = _UNSET,- name: str | None | object = _UNSET,- description: str | None | object = _UNSET,+ backend_schedule_id: str | None | _Unset = _UNSET,+ name: str | None | _Unset = _UNSET,+ description: str | None | _Unset = _UNSET,+ interval_seconds: int | None | _Unset = _UNSET,+ first_fire_at: datetime | None | _Unset = _UNSET,) -> WorkflowSchedule | None:async with self.Session() as session:workflow_schedule = (@@ -234,6 +254,10 @@ class SchedulesRepository(BaseRepository):return Noneworkflow_schedule.cron_expression = cron_expression+ if interval_seconds is not _UNSET:+ workflow_schedule.interval_seconds = interval_seconds+ if first_fire_at is not _UNSET:+ workflow_schedule.first_fire_at = _naive_utc(first_fire_at)workflow_schedule.timezone = timezoneif enabled is not _UNSET:workflow_schedule.enabled = enabled@@ -504,6 +528,8 @@ class SchedulesRepository(BaseRepository):schedule_model.workflow_permanent_id,row[1] or "Untitled Workflow",schedule_model.cron_expression,+ schedule_model.interval_seconds,+ schedule_model.first_fire_at,schedule_model.timezone,schedule_model.enabled,schedule_model.parameters,@@ -522,6 +548,8 @@ class SchedulesRepository(BaseRepository):wpid,title,cron_expr,+ interval_seconds,+ first_fire_at,tz,enabled,params,@@ -533,7 +561,9 @@ class SchedulesRepository(BaseRepository):next_run = Noneif enabled:try:- next_run = compute_next_run(cron_expr, tz)+ next_run = compute_next_run(+ cron_expr, tz, interval_seconds=interval_seconds, first_fire_at=first_fire_at+ )except Exception:LOG.warning("Failed to compute next_run for schedule",@@ -548,6 +578,8 @@ class SchedulesRepository(BaseRepository):workflow_permanent_id=wpid,workflow_title=title,cron_expression=cron_expr,+ interval_seconds=interval_seconds,+ first_fire_at=first_fire_at,timezone=tz,enabled=enabled,parameters=params,diff --git a/skyvern/forge/sdk/db/utils.py b/skyvern/forge/sdk/db/utils.pyindex acb6a88fb..023ac1d06 100644--- a/skyvern/forge/sdk/db/utils.py+++ b/skyvern/forge/sdk/db/utils.py@@ -697,6 +697,7 @@ def convert_to_workflow_run(start_fresh_browser=workflow_run_model.start_fresh_browser,reuse_browser_session=workflow_run_model.reuse_browser_session,reuse_bound_key=workflow_run_model.reuse_bound_key,+ task_queue=workflow_run_model.task_queue,status=WorkflowRunStatus[workflow_run_model.status],failure_reason=workflow_run_model.failure_reason,retried_from_workflow_run_id=workflow_run_model.retried_from_workflow_run_id,diff --git a/skyvern/forge/sdk/routes/workflow_schedules.py b/skyvern/forge/sdk/routes/workflow_schedules.pyindex fbe731dec..9a7085119 100644--- a/skyvern/forge/sdk/routes/workflow_schedules.py+++ b/skyvern/forge/sdk/routes/workflow_schedules.py@@ -1,10 +1,11 @@from __future__ import annotations-from datetime import datetime+from datetime import UTC, datetime, timedeltafrom typing import Any, Literalimport structlogfrom fastapi import Depends, HTTPException, Query, status+from fastapi.exceptions import RequestValidationErrorfrom skyvern.forge import appfrom skyvern.forge.sdk.core.permissions.schedule_limit_checker import ScheduleLimitCheckerFactory@@ -23,14 +24,17 @@ from skyvern.forge.sdk.schemas.workflow_schedules import (from skyvern.forge.sdk.services import org_auth_servicefrom skyvern.forge.sdk.workflow.models.workflow import Workflowfrom skyvern.forge.sdk.workflow.schedules import (+ NEXT_RUNS_COUNT,calculate_next_runs,+ default_first_fire_at,validate_cron_expression,validate_timezone_name,)LOG = structlog.get_logger()-DEFAULT_NEXT_RUNS_COUNT = 5SCHEDULE_SYNC_ERROR_DETAIL = "Failed to sync schedule with scheduling service"+# Leaves time for the row write and the scheduler create to land before the requested first tick.+MIN_FIRST_FIRE_LEAD = timedelta(seconds=60)def _require_schedules_enabled() -> None:@@ -76,9 +80,15 @@ async def _get_schedule_or_404(def _next_runs(schedule: WorkflowSchedule,- count: int = DEFAULT_NEXT_RUNS_COUNT,+ count: int = NEXT_RUNS_COUNT,) -> list[datetime]:- return calculate_next_runs(schedule.cron_expression, schedule.timezone, count)+ return calculate_next_runs(+ schedule.cron_expression,+ schedule.timezone,+ count,+ interval_seconds=schedule.interval_seconds,+ first_fire_at=schedule.first_fire_at,+ )def _strip_none_parameters(params: dict[str, Any] | None) -> dict[str, Any] | None:@@ -89,14 +99,41 @@ def _strip_none_parameters(params: dict[str, Any] | None) -> dict[str, Any] | Noreturn stripped or None-def _validate_request(cron_expression: str, timezone: str) -> None:+def _validate_request(body: WorkflowScheduleUpsertRequest) -> None:try:- validate_cron_expression(cron_expression)- validate_timezone_name(timezone)+ if body.cron_expression is not None:+ validate_cron_expression(body.cron_expression)+ validate_timezone_name(body.timezone)except ValueError as e:raise HTTPException(status_code=400, detail=str(e)) from e+def _resolve_first_fire_at(body: WorkflowScheduleUpsertRequest, existing: WorkflowSchedule | None) -> datetime | None:+ if body.interval_seconds is None:+ return None+ # Clients that fetch-merge-put echo the stored anchor back, so an unchanged anchor is kept even once it is past.+ if (+ existing is not None+ and existing.first_fire_at is not None+ and body.first_fire_at in (None, existing.first_fire_at)+ ):+ return existing.first_fire_at+ if body.first_fire_at is None:+ return default_first_fire_at(body.interval_seconds)+ if body.first_fire_at < datetime.now(UTC) + MIN_FIRST_FIRE_LEAD:+ raise RequestValidationError(+ [+ {+ "type": "value_error",+ "loc": ("body", "first_fire_at"),+ "msg": "first_fire_at must be at least 60 seconds in the future",+ "input": body.first_fire_at.isoformat(),+ }+ ]+ )+ return body.first_fire_at++async def _set_schedule_enabled(workflow_permanent_id: str,workflow_schedule_id: str,@@ -236,7 +273,8 @@ async def list_organization_schedules(operation_id="schedules_create",summary="Create a schedule for an agent",description=(- "Create a cron schedule that runs the given agent automatically with a fixed set of parameters. "+ "Create a cron or fixed-interval schedule that runs the given agent automatically with a fixed set of "+ "parameters. An interval schedule first runs at first_fire_at, or one interval after creation. ""Returns the stored schedule and its next upcoming run times."),)@@ -246,7 +284,8 @@ async def create_workflow_schedule(organization: Organization = Depends(org_auth_service.get_current_org),_: None = Depends(_require_schedules_enabled),) -> WorkflowScheduleResponse:- _validate_request(body.cron_expression, body.timezone)+ _validate_request(body)+ first_fire_at = _resolve_first_fire_at(body, existing=None)workflow = await _ensure_workflow_exists(workflow_permanent_id, organization.organization_id)await app.WORKFLOW_SERVICE.validate_schedule_parameters(workflow=workflow,@@ -271,6 +310,8 @@ async def create_workflow_schedule(parameters=stored_parameters,name=body.name,description=body.description,+ interval_seconds=body.interval_seconds,+ first_fire_at=first_fire_at,)except ScheduleLimitExceededError as e:LOG.info(@@ -337,6 +378,8 @@ async def create_workflow_schedule(enabled=enabled,parameters=stored_parameters,max_elapsed_time_minutes=workflow.max_elapsed_time_minutes,+ interval_seconds=body.interval_seconds,+ first_fire_at=first_fire_at,)except Exception as e:LOG.exception(@@ -366,6 +409,7 @@ async def create_workflow_schedule(workflow_permanent_id=workflow_permanent_id,workflow_schedule_id=schedule.workflow_schedule_id,cron_expression=body.cron_expression,+ interval_seconds=body.interval_seconds,enabled=enabled,)return WorkflowScheduleResponse(schedule=schedule, next_runs=_next_runs(schedule))@@ -401,7 +445,7 @@ async def list_workflow_schedules(operation_id="schedules_get",summary="Get an agent schedule by id",description=(- "Fetch one schedule belonging to an agent. Returns the schedule's cron expression, timezone, "+ "Fetch one schedule belonging to an agent. Returns the schedule's cron expression or interval, timezone, ""parameters, enabled state, and next upcoming run times."),)@@ -432,7 +476,7 @@ async def get_workflow_schedule(operation_id="schedules_update",summary="Update an agent schedule",description=(- "Replace a schedule's cron expression, timezone, run parameters, and enabled state. "+ "Replace a schedule's cron expression or interval, timezone, run parameters, and enabled state. ""Returns the updated schedule and its next upcoming run times."),)@@ -454,7 +498,8 @@ async def update_workflow_schedule(detail=f"Schedule {workflow_schedule_id} not found",)- _validate_request(body.cron_expression, body.timezone)+ _validate_request(body)+ first_fire_at = _resolve_first_fire_at(body, existing=existing)await app.WORKFLOW_SERVICE.validate_schedule_parameters(workflow=workflow,organization=organization,@@ -479,6 +524,8 @@ async def update_workflow_schedule(raise _schedule_sync_error()old_cron = existing.cron_expression+ old_interval_seconds = existing.interval_seconds+ old_first_fire_at = existing.first_fire_atold_timezone = existing.timezoneold_enabled = existing.enabledold_parameters = existing.parameters@@ -494,7 +541,7 @@ async def update_workflow_schedule(# Pass _UNSET (not existing.enabled) when omitted so this write can't clobber# a concurrent pause/resume that lands between the read above and this write.enabled_explicit = "enabled" in body.model_fields_set and body.enabled is not None- enabled_for_write = body.enabled if enabled_explicit else _UNSET+ enabled_for_write = body.enabled if enabled_explicit and body.enabled is not None else _UNSETschedule = await app.DATABASE.schedules.update_workflow_schedule(workflow_schedule_id=workflow_schedule_id,@@ -506,6 +553,8 @@ async def update_workflow_schedule(backend_schedule_id=backend_schedule_id,name=body.name,description=body.description,+ interval_seconds=body.interval_seconds,+ first_fire_at=first_fire_at,)if not schedule:raise HTTPException(@@ -528,6 +577,8 @@ async def update_workflow_schedule(enabled=enabled,parameters=stored_parameters,max_elapsed_time_minutes=workflow.max_elapsed_time_minutes,+ interval_seconds=body.interval_seconds,+ first_fire_at=first_fire_at,)except Exception as e:LOG.exception(@@ -547,6 +598,8 @@ async def update_workflow_schedule(backend_schedule_id=backend_schedule_id,name=old_name,description=old_description,+ interval_seconds=old_interval_seconds,+ first_fire_at=old_first_fire_at,)except Exception as rollback_err:LOG.exception(@@ -564,6 +617,7 @@ async def update_workflow_schedule(workflow_permanent_id=workflow_permanent_id,workflow_schedule_id=workflow_schedule_id,cron_expression=body.cron_expression,+ interval_seconds=body.interval_seconds,enabled=enabled,)return WorkflowScheduleResponse(schedule=schedule, next_runs=_next_runs(schedule))diff --git a/skyvern/forge/sdk/schemas/workflow_schedules.py b/skyvern/forge/sdk/schemas/workflow_schedules.pyindex 3718be758..90003966f 100644--- a/skyvern/forge/sdk/schemas/workflow_schedules.py+++ b/skyvern/forge/sdk/schemas/workflow_schedules.py@@ -1,7 +1,18 @@from datetime import datetime-from typing import Any+from typing import Any, Self-from pydantic import BaseModel, ConfigDict, Field+from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, field_validator, model_validator++from skyvern.forge.sdk.workflow.schedules import (+ LATEST_FIRST_FIRE_AT,+ MAX_INTERVAL_SECONDS,+ MIN_SCHEDULE_INTERVAL_SECONDS,+ as_utc,+)+++def _anchor_as_utc(value: datetime | None) -> datetime | None:+ return as_utc(value) if value is not None else Noneclass WorkflowSchedule(BaseModel):@@ -17,7 +28,9 @@ class WorkflowSchedule(BaseModel):workflow_schedule_id: strorganization_id: strworkflow_permanent_id: str- cron_expression: str+ cron_expression: str | None = None+ interval_seconds: int | None = None+ first_fire_at: datetime | None = Nonetimezone: strenabled: boolparameters: dict[str, Any] | None = None@@ -28,6 +41,8 @@ class WorkflowSchedule(BaseModel):modified_at: datetimedeleted_at: datetime | None = None+ _first_fire_at_utc = field_validator("first_fire_at")(_anchor_as_utc)+class OrganizationScheduleItem(BaseModel):"""Compact schedule projection for the org-wide list endpoint.@@ -42,7 +57,9 @@ class OrganizationScheduleItem(BaseModel):organization_id: strworkflow_permanent_id: strworkflow_title: str- cron_expression: str+ cron_expression: str | None = None+ interval_seconds: int | None = None+ first_fire_at: datetime | None = Nonetimezone: strenabled: boolparameters: dict[str, Any] | None = None@@ -52,6 +69,8 @@ class OrganizationScheduleItem(BaseModel):created_at: datetimemodified_at: datetime+ _first_fire_at_utc = field_validator("first_fire_at")(_anchor_as_utc)+class WorkflowScheduleCreateRequest(BaseModel):cron_expression: str@@ -92,7 +111,20 @@ class DeleteScheduleResponse(BaseModel):class WorkflowScheduleUpsertRequest(BaseModel):- cron_expression: str+ cron_expression: str | None = None+ interval_seconds: int | None = Field(+ default=None,+ ge=MIN_SCHEDULE_INTERVAL_SECONDS,+ le=MAX_INTERVAL_SECONDS,+ description="Fixed elapsed interval between runs, in seconds. Mutually exclusive with cron_expression.",+ )+ first_fire_at: AwareDatetime | None = Field(+ default=None,+ description=(+ "First run of an interval schedule; later runs follow every interval_seconds from it. "+ "Must be in the future when changed. Defaults to one interval after creation."+ ),+ )timezone: str# Default True is the create default (new schedules start enabled). On# update the route inspects model_fields_set, so an omitted `enabled`@@ -102,3 +134,24 @@ class WorkflowScheduleUpsertRequest(BaseModel):parameters: dict[str, Any] | None = Nonename: str | None = Nonedescription: str | None = None++ @field_validator("first_fire_at")+ @classmethod+ def _first_fire_at_in_range(cls, value: datetime | None) -> datetime | None:+ if value is None:+ return None+ try:+ anchor = as_utc(value).replace(microsecond=0)+ except OverflowError:+ anchor = None+ if anchor is None or anchor > LATEST_FIRST_FIRE_AT:+ raise ValueError(f"first_fire_at must be no later than {LATEST_FIRST_FIRE_AT.isoformat()}")+ return anchor++ @model_validator(mode="after")+ def _exactly_one_cadence(self) -> Self:+ if (self.cron_expression is None) == (self.interval_seconds is None):+ raise ValueError("Set exactly one of cron_expression or interval_seconds")+ if self.first_fire_at is not None and self.interval_seconds is None:+ raise ValueError("first_fire_at requires interval_seconds")+ return selfdiff --git a/skyvern/forge/sdk/workflow/models/workflow.py b/skyvern/forge/sdk/workflow/models/workflow.pyindex 84f2e4dab..7a05c0082 100644--- a/skyvern/forge/sdk/workflow/models/workflow.py+++ b/skyvern/forge/sdk/workflow/models/workflow.py@@ -340,6 +340,8 @@ class WorkflowRun(BaseModel):reuse_browser_session: bool | None = None# Internal admission identity. It can contain routing inputs and must never enter API payloads.reuse_bound_key: str | None = Field(default=None, exclude=True)+ # Internal routing: the worker queue the run was dispatched to. Never an API field.+ task_queue: str | None = Field(default=None, exclude=True)debug_session_id: str | None = Nonestatus: WorkflowRunStatusattempt: int = Field(default=1, description="One-based number of the current workflow run attempt")diff --git a/skyvern/forge/sdk/workflow/schedules.py b/skyvern/forge/sdk/workflow/schedules.pyindex 564852dd3..09fc3cc5f 100644--- a/skyvern/forge/sdk/workflow/schedules.py+++ b/skyvern/forge/sdk/workflow/schedules.py@@ -1,6 +1,7 @@from __future__ import annotations-from datetime import UTC, datetime+import math+from datetime import UTC, datetime, timedeltafrom zoneinfo import ZoneInfoimport structlog@@ -8,18 +9,9 @@ from croniter import croniter # type: ignore[import-untyped]LOG = structlog.get_logger()-# Mirrored in the frontend's cronUtils.ts (MIN_CRON_INTERVAL_SECONDS,+# Mirrored in the frontend's cronUtils.ts (MIN_SCHEDULE_INTERVAL_SECONDS,# meetsMinCronInterval) — keep both copies of these three constants in sync.-MIN_CRON_INTERVAL_SECONDS = 5 * 60---def validate_timezone_name(timezone: str) -> None:- try:- ZoneInfo(timezone)- except Exception as e: # ZoneInfoNotFoundError derives from KeyError- raise ValueError(f"Invalid timezone '{timezone}'") from e--+MIN_SCHEDULE_INTERVAL_SECONDS = 5 * 60# Sample a full day of firings so the minimum-gap check can't be bypassed by a# tight cluster that falls outside a small fixed sample (e.g.# "0,5,...,55,59 * * * *" hides the 55->59 and 59->00 gaps from a 10-run window).@@ -29,7 +21,16 @@ CRON_INTERVAL_SAMPLE_WINDOW_SECONDS = 25 * 60 * 60CRON_INTERVAL_MAX_SAMPLES = 2000-def validate_cron_expression(cron_expression: str, minimum_interval_seconds: int = MIN_CRON_INTERVAL_SECONDS) -> None:+def validate_timezone_name(timezone: str) -> None:+ try:+ ZoneInfo(timezone)+ except Exception as e: # ZoneInfoNotFoundError derives from KeyError+ raise ValueError(f"Invalid timezone '{timezone}'") from e+++def validate_cron_expression(+ cron_expression: str, minimum_interval_seconds: int = MIN_SCHEDULE_INTERVAL_SECONDS+) -> None:if not croniter.is_valid(cron_expression):raise ValueError("Invalid cron expression")@@ -45,21 +46,79 @@ def validate_cron_expression(cron_expression: str, minimum_interval_seconds: intraise ValueError(f"Cron interval must be at least {minimum_interval_seconds // 60} minutes")-def calculate_next_runs(cron_expression: str, timezone: str, count: int) -> list[datetime]:- now = datetime.now(ZoneInfo(timezone))- itr = croniter(cron_expression, now)- return [itr.get_next(datetime).astimezone(UTC) for _ in range(count)]+MAX_INTERVAL_SECONDS = 2**31 - 1+NEXT_RUNS_COUNT = 5+# Bounded so NEXT_RUNS_COUNT ticks of any allowed interval stay inside datetime's range.+LATEST_FIRST_FIRE_AT = (datetime.max - timedelta(seconds=NEXT_RUNS_COUNT * MAX_INTERVAL_SECONDS)).replace(+ microsecond=0, tzinfo=UTC+)-def compute_next_run(cron_expression: str, timezone: str) -> datetime:- """Compute the single next run time. Caller must ensure inputs are valid (e.g. from DB)."""+def as_utc(value: datetime) -> datetime:+ if value.tzinfo is None:+ return value.replace(tzinfo=UTC)+ return value.astimezone(UTC)+++def default_first_fire_at(interval_seconds: int) -> datetime:+ return datetime.fromtimestamp(math.floor(datetime.now(UTC).timestamp()) + interval_seconds, UTC)+++def _interval_tick_index(interval_seconds: int, first_fire_at: datetime) -> tuple[int, int]:+ """Return (anchor_epoch, k) where anchor + k*N is the latest tick at or before now; k is -1 before the anchor."""+ anchor = int(as_utc(first_fire_at).timestamp())+ now = math.floor(datetime.now(UTC).timestamp())+ return anchor, (now - anchor) // interval_seconds if now >= anchor else -1+++def _interval_tick(anchor: int, interval_seconds: int, k: int) -> datetime:+ return datetime.fromtimestamp(anchor + k * interval_seconds, UTC)+++def calculate_next_runs(+ cron_expression: str | None,+ timezone: str,+ count: int,+ *,+ interval_seconds: int | None = None,+ first_fire_at: datetime | None = None,+) -> list[datetime]:+ if interval_seconds is not None and first_fire_at is not None:+ anchor, k = _interval_tick_index(interval_seconds, first_fire_at)+ return [_interval_tick(anchor, interval_seconds, k + 1 + i) for i in range(count)]+ if cron_expression is None:+ raise ValueError("Schedule has neither a cron expression nor an interval")now = datetime.now(ZoneInfo(timezone))itr = croniter(cron_expression, now)- return itr.get_next(datetime).astimezone(UTC)+ return [itr.get_next(datetime).astimezone(UTC) for _ in range(count)]-def compute_previous_fire_time(cron_expression: str, timezone: str) -> datetime:- """Compute the most recent scheduled fire time. Caller must ensure inputs are valid (e.g. from DB)."""+def compute_next_run(+ cron_expression: str | None,+ timezone: str,+ *,+ interval_seconds: int | None = None,+ first_fire_at: datetime | None = None,+) -> datetime:+ """Compute the single next run time. Caller must ensure inputs are valid (e.g. from DB)."""+ return calculate_next_runs(+ cron_expression, timezone, 1, interval_seconds=interval_seconds, first_fire_at=first_fire_at+ )[0]+++def compute_previous_fire_time(+ cron_expression: str | None,+ timezone: str,+ *,+ interval_seconds: int | None = None,+ first_fire_at: datetime | None = None,+) -> datetime | None:+ """Compute the most recent scheduled fire time, or None when an interval has not reached its anchor yet."""+ if interval_seconds is not None and first_fire_at is not None:+ anchor, k = _interval_tick_index(interval_seconds, first_fire_at)+ return _interval_tick(anchor, interval_seconds, k) if k >= 0 else None+ if cron_expression is None:+ raise ValueError("Schedule has neither a cron expression nor an interval")now = datetime.now(ZoneInfo(timezone))itr = croniter(cron_expression, now)return itr.get_prev(datetime).astimezone(UTC)diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.pyindex ac549c9a2..42d760f33 100644--- a/skyvern/forge/sdk/workflow/service.py+++ b/skyvern/forge/sdk/workflow/service.py@@ -12794,6 +12794,7 @@ class WorkflowService:recorded_seconds=recorded_seconds,workflow_run_status=workflow_run.status,**_failure_attribution_log_fields(workflow_run, status),+ task_queue=workflow_run.task_queue,# A run with a retry policy reaches a terminal status once per attempt. Consumers that# derive one outcome per run keep only the events without a pending retry.attempt_number=attempt_number@@ -16447,6 +16448,8 @@ class WorkflowService:enabled=schedule.enabled,parameters=schedule.parameters,max_elapsed_time_minutes=max_elapsed_time_minutes,+ interval_seconds=schedule.interval_seconds,+ first_fire_at=schedule.first_fire_at,)except Exception:LOG.exception(diff --git a/skyvern/forge/taskv3/goal_composition.py b/skyvern/forge/taskv3/goal_composition.pyindex 56a1a9eb4..63b7b7e39 100644--- a/skyvern/forge/taskv3/goal_composition.py+++ b/skyvern/forge/taskv3/goal_composition.py@@ -205,9 +205,12 @@ def render_block_context(pieces.append("This block only reads the page: its job is to report what the page shows now, not to reach ""it. Earlier blocks own navigating, searching and choosing a record, so do not redo their work. "- "Return extracted_output in the requested shape with every field the page does not show set to "- "null (an empty list if the shape is a list; extracted_output itself is never null), and finish "- "with status=completed - a page that shows none of the requested data is still a completed "+ "Return extracted_output in the requested shape (extracted_output itself is never null). A field "+ "the goal asks you to read from the page that the page does not show is null (an empty list if "+ "the shape is a list); never invent it. A value the goal asks you to produce rather than read "+ "from the page is still returned: the current date, a value stated in the goal or in the "+ "data provided for this task, or a value formatted or derived from those or from what the page "+ "shows. Finish with status=completed - a page that shows none of the requested data is still a completed ""report, and your reason should say what the page shows instead. Finish with ""status=failed only if your tools could not read the page at all.")diff --git a/skyvern/services/workflow_schedule_service.py b/skyvern/services/workflow_schedule_service.pyindex 071dc6fa9..ea24e93e2 100644--- a/skyvern/services/workflow_schedule_service.py+++ b/skyvern/services/workflow_schedule_service.py@@ -11,7 +11,7 @@ import asyncioimport hashlibfrom collections.abc import Callablefrom dataclasses import dataclass-from datetime import UTC, datetime+from datetime import datetimeimport structlogfrom sqlalchemy.exc import IntegrityError, SQLAlchemyError@@ -23,7 +23,7 @@ from skyvern.forge.sdk.db.enums import WorkflowRunTriggerTypefrom skyvern.forge.sdk.schemas.workflow_schedules import WorkflowSchedulefrom skyvern.forge.sdk.workflow.models.workflow import WorkflowRequestBodyfrom skyvern.forge.sdk.workflow.retry_policy import fail_run_without_attempt_row, queue_initial_attempt-from skyvern.forge.sdk.workflow.schedules import compute_previous_fire_time+from skyvern.forge.sdk.workflow.schedules import as_utc, compute_previous_fire_timefrom skyvern.services.workflow_service import prepare_workflowfrom skyvern.utils.files import initialize_skyvern_state_file@@ -39,15 +39,22 @@ class DueWorkflowSchedule:def build_scheduled_workflow_run_id(workflow_schedule_id: str, fire_time: datetime) -> str:- normalized_fire_time = _as_utc(fire_time)+ normalized_fire_time = as_utc(fire_time)digest = hashlib.sha256(f"{workflow_schedule_id}:{normalized_fire_time.isoformat()}".encode()).hexdigest()[:32]return f"wr_sched_{digest}"-def _as_utc(value: datetime) -> datetime:- if value.tzinfo is None:- return value.replace(tzinfo=UTC)- return value.astimezone(UTC)+def previous_fire_time_since_edit(schedule: WorkflowSchedule) -> datetime | None:+ """Return the most recent fire time, or None when it precedes the last edit; missed ticks are never backfilled."""+ previous_fire_time = compute_previous_fire_time(+ schedule.cron_expression,+ schedule.timezone,+ interval_seconds=schedule.interval_seconds,+ first_fire_at=schedule.first_fire_at,+ )+ if previous_fire_time is None or previous_fire_time < as_utc(schedule.modified_at):+ return None+ return previous_fire_timeclass LocalWorkflowScheduleScheduler:@@ -148,19 +155,18 @@ class LocalWorkflowScheduleScheduler:async def _get_due_schedule(self, schedule: WorkflowSchedule) -> DueWorkflowSchedule | None:try:- previous_fire_time = _as_utc(compute_previous_fire_time(schedule.cron_expression, schedule.timezone))+ previous_fire_time = previous_fire_time_since_edit(schedule)except Exception:LOG.warning("Failed to compute previous fire time for workflow schedule",workflow_schedule_id=schedule.workflow_schedule_id,cron_expression=schedule.cron_expression,+ interval_seconds=schedule.interval_seconds,timezone=schedule.timezone,exc_info=True,)return None-- modified_at = _as_utc(schedule.modified_at)- if previous_fire_time < modified_at:+ if previous_fire_time is None:return Noneif await app.DATABASE.schedules.has_schedule_fired_since(diff --git a/tests/unit/_schedule_fakes.py b/tests/unit/_schedule_fakes.pynew file mode 100644index 000000000..079ce90fb--- /dev/null+++ b/tests/unit/_schedule_fakes.py@@ -0,0 +1,84 @@+from __future__ import annotations++import datetime as dt+from typing import Any+from unittest.mock import AsyncMock, MagicMock++import pytest++from skyvern.client.types.workflow_schedule import WorkflowSchedule+from skyvern.client.types.workflow_schedule_response import WorkflowScheduleResponse++STORED_ANCHOR = dt.datetime(2026, 10, 30, 15, 0, 0, tzinfo=dt.timezone.utc)+NEW_ANCHOR = dt.datetime(2026, 11, 2, 8, 30, 0, tzinfo=dt.timezone.utc)+++def _make_fern_schedule(+ *,+ workflow_schedule_id: str = "wfs_test_1",+ organization_id: str = "o_test",+ workflow_permanent_id: str = "wpid_test_1",+ cron_expression: str | None = "0 9 * * *",+ interval_seconds: int | None = None,+ first_fire_at: dt.datetime | None = None,+ timezone: str = "UTC",+ enabled: bool = True,+ parameters: dict[str, Any] | None = None,+ temporal_schedule_id: str | None = "ts_abc",+ name: str | None = "probe",+ description: str | None = "test",+ created_at: dt.datetime = dt.datetime(2026, 1, 1, 12, 0, 0, tzinfo=dt.timezone.utc),+ modified_at: dt.datetime = dt.datetime(2026, 1, 2, 12, 0, 0, tzinfo=dt.timezone.utc),+) -> WorkflowSchedule:+ return WorkflowSchedule(+ workflow_schedule_id=workflow_schedule_id,+ organization_id=organization_id,+ workflow_permanent_id=workflow_permanent_id,+ cron_expression=cron_expression,+ interval_seconds=interval_seconds,+ first_fire_at=first_fire_at,+ timezone=timezone,+ enabled=enabled,+ parameters=parameters,+ temporal_schedule_id=temporal_schedule_id,+ name=name,+ description=description,+ created_at=created_at,+ modified_at=modified_at,+ )+++def _make_fern_schedule_response(+ schedule: WorkflowSchedule | None = None,+ next_runs: list[dt.datetime] | None = None,+) -> WorkflowScheduleResponse:+ return WorkflowScheduleResponse(+ schedule=schedule or _make_fern_schedule(),+ next_runs=next_runs+ or [+ dt.datetime(2026, 4, 28, 9, 0, 0, tzinfo=dt.timezone.utc),+ dt.datetime(2026, 4, 29, 9, 0, 0, tzinfo=dt.timezone.utc),+ ],+ )+++def _patch_schedules_client(monkeypatch: pytest.MonkeyPatch) -> MagicMock:+ """Patch get_skyvern() so each tool sees a fresh Mock with .schedules.*."""+ sched_client = MagicMock()+ sched_client.list_all = AsyncMock()+ sched_client.list = AsyncMock()+ sched_client.get = AsyncMock()+ sched_client.create = AsyncMock()+ sched_client.update = AsyncMock()+ sched_client.delete = AsyncMock()+ sched_client.enable = AsyncMock()+ sched_client.disable = AsyncMock()++ skyvern_mock = MagicMock()+ skyvern_mock.schedules = sched_client++ monkeypatch.setattr(+ "skyvern.cli.mcp_tools.schedule.get_skyvern",+ lambda: skyvern_mock,+ )+ return sched_clientdiff --git a/tests/unit/forge/sdk/db/test_workflow_runs_repository.py b/tests/unit/forge/sdk/db/test_workflow_runs_repository.pyindex 9ac34a1b0..dcd035d14 100644--- a/tests/unit/forge/sdk/db/test_workflow_runs_repository.py+++ b/tests/unit/forge/sdk/db/test_workflow_runs_repository.py@@ -228,6 +228,21 @@ async def test_prepare_next_attempt_clears_only_server_assigned_browser_address(assert reopened.status == WorkflowRunStatus.queued.value+async def test_routed_task_queue_reaches_the_run_but_never_its_api_payload(sqlite_db: AgentDB) -> None:+ now = datetime(2026, 9, 25, 12, 0, tzinfo=UTC)+ async with sqlite_db.Session() as session:+ session.add(_workflow_run_model(workflow_run_id="wr_routed", queued_at=now))+ await session.commit()++ await sqlite_db.workflow_runs.update_workflow_run_routing("wr_routed", "fairness-patchright-1vcpu-4gb", "aws")++ run = await sqlite_db.workflow_runs.get_workflow_run("wr_routed", "org_test")+ assert run is not None+ assert run.task_queue == "fairness-patchright-1vcpu-4gb"+ assert "task_queue" not in run.model_dump()++@pytest.mark.asyncioasync def test_prepare_next_attempt_reopens_the_task_run_mirror(sqlite_db: AgentDB) -> None:now = datetime(2026, 7, 22, 12, 0, tzinfo=UTC)diff --git a/tests/unit/forge/sdk/test_workflow_schedules_routes.py b/tests/unit/forge/sdk/test_workflow_schedules_routes.pyindex 04d88302f..f94743838 100644--- a/tests/unit/forge/sdk/test_workflow_schedules_routes.py+++ b/tests/unit/forge/sdk/test_workflow_schedules_routes.py@@ -2,13 +2,36 @@from __future__ import annotations+from collections.abc import AsyncIterator+from datetime import UTC, datetime, timedeltafrom types import SimpleNamespace+from typing import Anyfrom unittest.mock import AsyncMock+import httpximport pytest+import pytest_asyncio+from fastapi import FastAPI+from fastapi.testclient import TestClient+from freezegun import freeze_timeimport skyvern.forge.sdk.routes.workflow_schedules as workflow_schedule_routes+from skyvern.cli.mcp_tools.schedule import skyvern_schedule_create, skyvern_schedule_update+from skyvern.client import AsyncSkyvernfrom skyvern.forge.agent_functions import AgentFunction+from skyvern.forge.api_app import register_agent_route_aliases+from skyvern.forge.sdk.db.agent_db import AgentDB+from skyvern.forge.sdk.routes import routers as routers_module+from skyvern.forge.sdk.services import org_auth_service+from tests.unit.forge.sdk.db import conftest as db_fixtures++ORG_ID = "org_oss"+WPID = "wpid_interval"+NOW = datetime(2026, 10, 30, 12, 0, 30, tzinfo=UTC)+HOUR = 60 * 60++agent_db = db_fixtures.agent_db+db_engine = db_fixtures.db_engine@pytest.fixture(autouse=True)@@ -76,11 +99,6 @@ async def test_oss_delete_workflow_schedule_is_noop() -> None:def test_oss_route_returns_schedule_list_via_testclient(prefix: str, router_name: str) -> None:"""End-to-end: route resolves through the FastAPI dependency chain on boththe public `/v1` mount and the legacy `/api/v1` alias."""- from fastapi import FastAPI- from fastapi.testclient import TestClient-- from skyvern.forge.sdk.routes import routers as routers_module- from skyvern.forge.sdk.services import org_auth_serviceasync def _fake_org() -> SimpleNamespace:return SimpleNamespace(organization_id="org_oss")@@ -93,3 +111,195 @@ def test_oss_route_returns_schedule_list_via_testclient(prefix: str, router_nameresponse = client.get(f"{prefix}/schedules")assert response.status_code == 200assert response.json() == {"schedules": [], "total_count": 0, "page": 1, "page_size": 10}+++@pytest_asyncio.fixture+async def schedules_client(agent_db: AgentDB, monkeypatch: pytest.MonkeyPatch) -> AsyncIterator[httpx.AsyncClient]:+ monkeypatch.setattr(+ workflow_schedule_routes,+ "app",+ SimpleNamespace(+ AGENT_FUNCTION=AgentFunction(),+ DATABASE=agent_db,+ WORKFLOW_SERVICE=SimpleNamespace(validate_schedule_parameters=AsyncMock()),+ ),+ )+ monkeypatch.setattr(+ workflow_schedule_routes,+ "_ensure_workflow_exists",+ AsyncMock(return_value=SimpleNamespace(workflow_permanent_id=WPID, max_elapsed_time_minutes=None)),+ )++ async def _fake_org() -> SimpleNamespace:+ return SimpleNamespace(organization_id=ORG_ID)++ fastapi_app = FastAPI()+ fastapi_app.dependency_overrides[org_auth_service.get_current_org] = _fake_org+ fastapi_app.include_router(routers_module.base_router, prefix="/v1")+ register_agent_route_aliases(fastapi_app)+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=fastapi_app), base_url="http://test") as client:+ yield client+++async def _request(client: httpx.AsyncClient, when: datetime, method: str, path: str, **kwargs: Any) -> httpx.Response:+ with freeze_time(when, real_asyncio=True):+ return await client.request(method, f"/v1/workflows/{WPID}/schedules{path}", **kwargs)+++def _iso(value: datetime) -> str:+ return value.isoformat().replace("+00:00", "Z")++[email protected]("interval_seconds", [72 * HOUR, 5 * HOUR], ids=["72h", "5h"])[email protected]("explicit_first_fire_at", [None, datetime(2026, 10, 31, 9, 17, tzinfo=UTC)])+async def test_create_interval_schedule_anchors_one_interval_out_unless_a_future_first_fire_is_given(+ schedules_client: httpx.AsyncClient,+ agent_db: AgentDB,+ interval_seconds: int,+ explicit_first_fire_at: datetime | None,+) -> None:+ body: dict[str, Any] = {"interval_seconds": interval_seconds, "timezone": "America/New_York"}+ if explicit_first_fire_at is not None:+ body["first_fire_at"] = explicit_first_fire_at.isoformat()+ anchor = explicit_first_fire_at or NOW + timedelta(seconds=interval_seconds)++ response = await _request(schedules_client, NOW, "POST", "", json=body)++ assert response.status_code == 200, response.text+ payload = response.json()+ assert payload["schedule"]["cron_expression"] is None+ assert payload["schedule"]["interval_seconds"] == interval_seconds+ assert payload["schedule"]["first_fire_at"] == _iso(anchor)+ assert payload["next_runs"][:2] == [_iso(anchor), _iso(anchor + timedelta(seconds=interval_seconds))]+ [stored] = await agent_db.schedules.get_workflow_schedules(workflow_permanent_id=WPID, organization_id=ORG_ID)+ assert stored.first_fire_at == anchor+++ "body,field",+ [+ ({"interval_seconds": 299, "timezone": "UTC"}, "interval_seconds"),+ ({"cron_expression": "0 * * * *", "interval_seconds": 3600, "timezone": "UTC"}, "cron_expression"),+ ({"timezone": "UTC"}, "interval_seconds"),+ ({"interval_seconds": 3600, "first_fire_at": "2026-10-30T12:00:00Z", "timezone": "UTC"}, "first_fire_at"),+ ({"interval_seconds": 3600, "first_fire_at": "2026-10-30T12:01:00Z", "timezone": "UTC"}, "first_fire_at"),+ ],+ ids=["under-five-minutes", "cron-and-interval", "no-cadence", "past-first-fire", "first-fire-under-a-minute-out"],+)+async def test_create_rejects_invalid_cadence_with_a_field_named_422_and_writes_nothing(+ schedules_client: httpx.AsyncClient,+ agent_db: AgentDB,+ body: dict[str, Any],+ field: str,+) -> None:+ response = await _request(schedules_client, NOW, "POST", "", json=body)++ assert response.status_code == 422+ assert field in response.text+ assert await agent_db.schedules.get_workflow_schedules(workflow_permanent_id=WPID, organization_id=ORG_ID) == []+++async def test_put_echoing_a_fetched_past_anchor_keeps_it_and_a_changed_past_anchor_is_rejected(+ schedules_client: httpx.AsyncClient,+) -> None:+ created = await _request(schedules_client, NOW, "POST", "", json={"interval_seconds": 5 * HOUR, "timezone": "UTC"})+ schedule_id = created.json()["schedule"]["workflow_schedule_id"]+ later = NOW + timedelta(days=2)++ fetched = (await _request(schedules_client, later, "GET", f"/{schedule_id}")).json()+ echoed = await _request(+ schedules_client, later, "PUT", f"/{schedule_id}", json={**fetched["schedule"], "name": "renamed"}+ )++ assert echoed.status_code == 200, echoed.text+ assert echoed.json()["schedule"]["name"] == "renamed"+ assert echoed.json()["schedule"]["first_fire_at"] == fetched["schedule"]["first_fire_at"]+ assert echoed.json()["next_runs"] == fetched["next_runs"]++ moved = await _request(+ schedules_client,+ later,+ "PUT",+ f"/{schedule_id}",+ json={**fetched["schedule"], "first_fire_at": _iso(NOW + timedelta(hours=1))},+ )+ assert moved.status_code == 422+ assert "first_fire_at" in moved.text+++async def test_update_keeps_the_anchor_across_interval_edits_and_reanchors_when_switching_kinds(+ schedules_client: httpx.AsyncClient,+) -> None:+ created = await _request(schedules_client, NOW, "POST", "", json={"interval_seconds": 5 * HOUR, "timezone": "UTC"})+ schedule_id = created.json()["schedule"]["workflow_schedule_id"]+ anchor = created.json()["schedule"]["first_fire_at"]+ later = NOW + timedelta(days=1)++ lengthened = await _request(+ schedules_client, later, "PUT", f"/{schedule_id}", json={"interval_seconds": 7 * HOUR, "timezone": "UTC"}+ )+ assert lengthened.json()["schedule"]["first_fire_at"] == anchor++ to_cron = await _request(+ schedules_client, later, "PUT", f"/{schedule_id}", json={"cron_expression": "0 9 * * *", "timezone": "UTC"}+ )+ assert to_cron.status_code == 200, to_cron.text+ assert to_cron.json()["schedule"]["interval_seconds"] is None+ assert to_cron.json()["schedule"]["first_fire_at"] is None++ to_interval = await _request(+ schedules_client, later, "PUT", f"/{schedule_id}", json={"interval_seconds": 5 * HOUR, "timezone": "UTC"}+ )+ assert to_interval.json()["schedule"]["cron_expression"] is None+ assert to_interval.json()["schedule"]["first_fire_at"] == _iso(later + timedelta(hours=5))++[email protected]("entry", ["rest", "mcp"])+ "first_fire_at",+ ["9800-01-01T00:00:00+00:00", "9999-12-31T23:00:00-05:00"],+ ids=["ticks-overflow", "anchor-overflows-in-utc"],+)+async def test_first_fire_at_too_far_out_to_compute_ticks_is_a_field_named_422_that_writes_nothing(+ schedules_client: httpx.AsyncClient,+ agent_db: AgentDB,+ monkeypatch: pytest.MonkeyPatch,+ entry: str,+ first_fire_at: str,+) -> None:+ created = await _request(schedules_client, NOW, "POST", "", json={"interval_seconds": 5 * HOUR, "timezone": "UTC"})+ schedule_id = created.json()["schedule"]["workflow_schedule_id"]+ sdk = AsyncSkyvern(base_url="http://test", api_key="test", httpx_client=schedules_client)+ monkeypatch.setattr("skyvern.cli.mcp_tools.schedule.get_skyvern", lambda: sdk)+ body = {"interval_seconds": 2**31 - 1, "first_fire_at": first_fire_at, "timezone": "UTC"}++ with freeze_time(NOW, real_asyncio=True):+ if entry == "rest":+ prefix = f"/v1/workflows/{WPID}/schedules"+ created_via_rest = await schedules_client.post(prefix, json=body)+ updated_via_rest = await schedules_client.put(f"{prefix}/{schedule_id}", json=body)+ create_error = f"{created_via_rest.status_code} {created_via_rest.text}"+ update_error = f"{updated_via_rest.status_code} {updated_via_rest.text}"+ else:+ anchor = datetime.fromisoformat(first_fire_at)+ created_via_mcp = await skyvern_schedule_create(+ workflow_permanent_id=WPID, timezone="UTC", interval_seconds=2**31 - 1, first_fire_at=anchor+ )+ updated_via_mcp = await skyvern_schedule_update(+ workflow_permanent_id=WPID, workflow_schedule_id=schedule_id, first_fire_at=anchor+ )+ assert not created_via_mcp["ok"] and not updated_via_mcp["ok"]+ create_error = created_via_mcp["error"]["message"]+ update_error = updated_via_mcp["error"]["message"]++ for error in (create_error, update_error):+ assert "422" in error+ assert "first_fire_at" in error and "must be no later than" in error+ [stored] = await agent_db.schedules.get_workflow_schedules(workflow_permanent_id=WPID, organization_id=ORG_ID)+ assert stored.interval_seconds == 5 * HOUR+ assert stored.first_fire_at == NOW + timedelta(hours=5)diff --git a/tests/unit/test_copilot_mcp_adapter.py b/tests/unit/test_copilot_mcp_adapter.pyindex a08f065d6..de7af2fcc 100644--- a/tests/unit/test_copilot_mcp_adapter.py+++ b/tests/unit/test_copilot_mcp_adapter.py@@ -3020,7 +3020,9 @@ async def test_chat_surface_exposes_only_chat_bound_workflow_schedule_tools() ->assert "workflow_permanent_id" not in tools[name].inputSchema["properties"]assert "exact" not in tools[name].inputSchema["properties"]assert "force" in tools["delete_workflow_schedule"].inputSchema["properties"]- assert {"cron_expression", "timezone"} <= set(tools["create_workflow_schedule"].inputSchema["required"])+ for name in ("create_workflow_schedule", "update_workflow_schedule"):+ assert {"cron_expression", "interval_seconds", "first_fire_at"} <= set(tools[name].inputSchema["properties"])+ assert "cron_expression" not in tools["create_workflow_schedule"].inputSchema.get("required", [])@pytest.mark.asynciodiff --git a/tests/unit/test_log_artifacts.py b/tests/unit/test_log_artifacts.pyindex 19c8d5609..2f7887f92 100644--- a/tests/unit/test_log_artifacts.py+++ b/tests/unit/test_log_artifacts.py@@ -366,6 +366,7 @@ async def test_retry_logs_keep_both_attempts_and_update_only_current_attempt(organization_id="o_logs",status=WorkflowRunStatus.failed,depends_on_workflow_run_id=None,+ task_queue=None,)release_late_log = asyncio.Event()late_log_task: asyncio.Task[None] | None = Nonediff --git a/tests/unit/test_mcp_legacy_manifest.py b/tests/unit/test_mcp_legacy_manifest.pyindex 983fe4d9a..8492270b8 100644--- a/tests/unit/test_mcp_legacy_manifest.py+++ b/tests/unit/test_mcp_legacy_manifest.py@@ -96,14 +96,14 @@ LEGACY_TOOL_MANIFEST_DIGESTS = {"skyvern_org_update": "bbb6283207460a33b0d2759d563ecf4a8431fdc8c5cf7dbb15d10d27f36e0951","skyvern_press_key": "ad74ceb98f5b21483940f027747817d21f751eebb781c11f97529c5be968a9c4","skyvern_run_task": "e48efaa780ab1f49c8d5a7c489edf293880448d07e7e0f3d88b65807d559cb23",- "skyvern_schedule_create": "c96af8fafabe9cd3164f91c1489f1069a5259e9f3c5405f109ad3e16e0c1db71",+ "skyvern_schedule_create": "1ec88d11f92cd56106ab8a657617e8f6e16277049736584768f34288263c922f","skyvern_schedule_delete": "ad6fa7d028b0c168e0b12a475c0e3c954d6402843bc1a984ad605d3b3766adae","skyvern_schedule_disable": "c9e5e01c54c1934db991ab4a81a4fa369340cfabc580ac73990b1b71589101ef","skyvern_schedule_enable": "6df661f097e8cfd30c52fe66d66cc4e1a4b3ff555da2978bcc0acc4bf011fe9d","skyvern_schedule_get": "2eb8f151ace8e2c4116399437672bd41836536db9ac52545207d5905535c94c1","skyvern_schedule_list": "4aa92418fe65c6f07ab89f86ef26828e711cb37e178c2b6d90810ddf296187db","skyvern_schedule_list_for_workflow": "a9949b4ddce25849378936b675f59621165b9587e0ee6b516cb8b1e31b64709e",- "skyvern_schedule_update": "c8736498aef521f0a021ffecae4aeb2972d21e9a6f06e17e474450526d7db1af",+ "skyvern_schedule_update": "0f64b40bd760fd3e49907a4f23062ee3ffe18c1be96960276f9b71ecdc07d5f6","skyvern_screenshot": "96f506db0c7780f79d45261d8a432114893130b04160f977214d08865771a2b8","skyvern_script_deploy": "c14adba89381f2e3b6010d44f5a2c66b840b57fc835cfe08ac864aaacba63b8e","skyvern_script_fallback_episodes": "c6f23e8270426a40ff2692ef33dc738b8083e0a38eaf9d0e2e08f93768d645e6",diff --git a/tests/unit/test_schedule_cli.py b/tests/unit/test_schedule_cli.pyindex 753a57f66..96a5cda63 100644--- a/tests/unit/test_schedule_cli.py+++ b/tests/unit/test_schedule_cli.py@@ -7,6 +7,13 @@ import pytestfrom typer.testing import CliRunnerfrom skyvern.cli.schedule_command import schedule_app+from tests.unit._schedule_fakes import (+ NEW_ANCHOR,+ STORED_ANCHOR,+ _make_fern_schedule,+ _make_fern_schedule_response,+ _patch_schedules_client,+)def _patch_tools(@@ -106,6 +113,30 @@ class TestCliCreate:assert result.exit_code != 0mocks["tool_schedule_create"].assert_not_called()+ def test_interval_create_needs_no_cron(self, monkeypatch: pytest.MonkeyPatch) -> None:+ sched_client = _patch_schedules_client(monkeypatch)+ sched_client.create.return_value = _make_fern_schedule_response(+ _make_fern_schedule(cron_expression=None, interval_seconds=259200, first_fire_at=NEW_ANCHOR)+ )+ result = CliRunner().invoke(+ schedule_app,+ [+ "create",+ "--workflow-id",+ "wpid_test_1",+ "--interval-seconds",+ "259200",+ "--first-fire-at",+ NEW_ANCHOR.isoformat(),+ "--json",+ ],+ )+ assert result.exit_code == 0, result.output+ kwargs = sched_client.create.call_args.kwargs+ assert kwargs["cron_expression"] is None+ assert kwargs["interval_seconds"] == 259200+ assert kwargs["first_fire_at"] == NEW_ANCHOR+# -- update --@@ -192,6 +223,37 @@ class TestCliUpdate:assert kwargs["exact"] is Trueassert kwargs["enabled"] is None+ def test_exact_interval_update_needs_no_cron(self, monkeypatch: pytest.MonkeyPatch) -> None:+ sched_client = _patch_schedules_client(monkeypatch)+ sched_client.update.return_value = _make_fern_schedule_response(+ _make_fern_schedule(cron_expression=None, interval_seconds=18000, first_fire_at=STORED_ANCHOR)+ )+ result = CliRunner().invoke(+ schedule_app,+ [+ "update",+ "--workflow-id",+ "wpid_test_1",+ "--id",+ "wfs_test_1",+ "--interval-seconds",+ "18000",+ "--timezone",+ "UTC",+ "--enabled",+ "--clear-parameters",+ "--clear-name",+ "--clear-description",+ "--exact",+ "--json",+ ],+ )+ assert result.exit_code == 0, result.output+ sched_client.get.assert_not_called()+ kwargs = sched_client.update.call_args.kwargs+ assert kwargs["cron_expression"] is None+ assert kwargs["interval_seconds"] == 18000+# -- delete --diff --git a/tests/unit/test_schedule_mcp_tools.py b/tests/unit/test_schedule_mcp_tools.pyindex 41dfb2620..268f1685b 100644--- a/tests/unit/test_schedule_mcp_tools.py+++ b/tests/unit/test_schedule_mcp_tools.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport asyncioimport datetime as dtfrom typing import Any-from unittest.mock import AsyncMock, MagicMock+from unittest.mock import MagicMockimport pytest@@ -18,78 +18,13 @@ from skyvern.cli.mcp_tools.schedule import (skyvern_schedule_update,)from skyvern.client.types.organization_schedule_item import OrganizationScheduleItem-from skyvern.client.types.workflow_schedule import WorkflowSchedule-from skyvern.client.types.workflow_schedule_response import WorkflowScheduleResponse--# -- Test fixtures (Fern types — NOT the backend Pydantic schema) -----def _make_fern_schedule(- *,- workflow_schedule_id: str = "wfs_test_1",- organization_id: str = "o_test",- workflow_permanent_id: str = "wpid_test_1",- cron_expression: str = "0 9 * * *",- timezone: str = "UTC",- enabled: bool = True,- parameters: dict[str, Any] | None = None,- temporal_schedule_id: str | None = "ts_abc",- name: str | None = "probe",- description: str | None = "test",- created_at: dt.datetime = dt.datetime(2026, 1, 1, 12, 0, 0, tzinfo=dt.timezone.utc),- modified_at: dt.datetime = dt.datetime(2026, 1, 2, 12, 0, 0, tzinfo=dt.timezone.utc),-) -> WorkflowSchedule:- return WorkflowSchedule(- workflow_schedule_id=workflow_schedule_id,- organization_id=organization_id,- workflow_permanent_id=workflow_permanent_id,- cron_expression=cron_expression,- timezone=timezone,- enabled=enabled,- parameters=parameters,- temporal_schedule_id=temporal_schedule_id,- name=name,- description=description,- created_at=created_at,- modified_at=modified_at,- )---def _make_fern_schedule_response(- schedule: WorkflowSchedule | None = None,- next_runs: list[dt.datetime] | None = None,-) -> WorkflowScheduleResponse:- return WorkflowScheduleResponse(- schedule=schedule or _make_fern_schedule(),- next_runs=next_runs- or [- dt.datetime(2026, 4, 28, 9, 0, 0, tzinfo=dt.timezone.utc),- dt.datetime(2026, 4, 29, 9, 0, 0, tzinfo=dt.timezone.utc),- ],- )---def _patch_schedules_client(monkeypatch: pytest.MonkeyPatch) -> MagicMock:- """Patch get_skyvern() so each tool sees a fresh Mock with .schedules.*."""- sched_client = MagicMock()- sched_client.list_all = AsyncMock()- sched_client.list = AsyncMock()- sched_client.get = AsyncMock()- sched_client.create = AsyncMock()- sched_client.update = AsyncMock()- sched_client.delete = AsyncMock()- sched_client.enable = AsyncMock()- sched_client.disable = AsyncMock()-- skyvern_mock = MagicMock()- skyvern_mock.schedules = sched_client-- monkeypatch.setattr(- "skyvern.cli.mcp_tools.schedule.get_skyvern",- lambda: skyvern_mock,- )- return sched_client-+from tests.unit._schedule_fakes import (+ NEW_ANCHOR,+ STORED_ANCHOR,+ _make_fern_schedule,+ _make_fern_schedule_response,+ _patch_schedules_client,+)# -- ID validation --@@ -154,6 +89,21 @@ class TestSerializeSchedule:assert "schedule" in out and "next_runs" in outassert all(isinstance(r, str) and "T" in r for r in out["next_runs"])+ def test_serialize_interval_schedule_names_interval_anchor_next_run_and_enabled(self) -> None:+ anchor = dt.datetime(2026, 10, 30, 15, 0, 0, tzinfo=dt.timezone.utc)+ resp = _make_fern_schedule_response(+ schedule=_make_fern_schedule(+ cron_expression=None, interval_seconds=259200, first_fire_at=anchor, enabled=False+ ),+ next_runs=[anchor, anchor + dt.timedelta(hours=72)],+ )+ out = _serialize_schedule_response(resp)+ assert out["schedule"]["cron_expression"] is None+ assert out["schedule"]["interval_seconds"] == 259200+ assert out["schedule"]["first_fire_at"] == "2026-10-30T15:00:00+00:00"+ assert out["schedule"]["enabled"] is False+ assert out["next_runs"] == ["2026-10-30T15:00:00+00:00", "2026-11-02T15:00:00+00:00"]+def test_serialize_org_schedule_item_omits_backend_id(self) -> None:item = OrganizationScheduleItem(workflow_schedule_id="wfs_test_1",@@ -326,6 +276,67 @@ class TestScheduleUpdatePartial:assert kwargs["name"] == "new_name"assert kwargs["description"] == "old_desc"+ @pytest.mark.parametrize(+ "existing_kind,patch,expected",+ [+ ("interval", {"name": "renamed"}, (None, 259200, None)),+ ("interval", {"interval_seconds": 18000}, (None, 18000, None)),+ ("interval", {"first_fire_at": NEW_ANCHOR}, (None, 259200, NEW_ANCHOR)),+ ("interval", {"cron_expression": "0 9 * * *"}, ("0 9 * * *", None, None)),+ ("cron", {"interval_seconds": 18000}, (None, 18000, None)),+ ("cron", {"name": "renamed"}, ("*/15 * * * *", None, None)),+ ],+ ids=[+ "interval-metadata",+ "interval-length",+ "interval-reanchor",+ "interval-to-cron",+ "cron-to-interval",+ "cron-metadata",+ ],+ )+ def test_partial_never_mixes_a_stored_cadence_into_a_new_one(+ self,+ monkeypatch: pytest.MonkeyPatch,+ existing_kind: str,+ patch: dict[str, Any],+ expected: tuple[str | None, int | None, dt.datetime | None],+ ) -> None:+ sched_client = _patch_schedules_client(monkeypatch)+ existing = (+ _make_fern_schedule(cron_expression=None, interval_seconds=259200, first_fire_at=STORED_ANCHOR)+ if existing_kind == "interval"+ else _make_fern_schedule(cron_expression="*/15 * * * *")+ )+ sched_client.get.return_value = _make_fern_schedule_response(schedule=existing)+ sched_client.update.return_value = _make_fern_schedule_response()++ asyncio.run(+ skyvern_schedule_update(workflow_permanent_id="wpid_test_1", workflow_schedule_id="wfs_test_1", **patch)+ )++ kwargs = sched_client.update.call_args.kwargs+ expected_cron, expected_interval, expected_anchor = expected+ assert kwargs["cron_expression"] == expected_cron+ assert kwargs["interval_seconds"] == expected_interval+ assert kwargs["first_fire_at"] == expected_anchor++ def test_first_fire_at_alone_on_a_cron_schedule_is_a_local_input_error(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ sched_client = _patch_schedules_client(monkeypatch)+ sched_client.get.return_value = _make_fern_schedule_response(schedule=_make_fern_schedule())++ result = asyncio.run(+ skyvern_schedule_update(+ workflow_permanent_id="wpid_test_1", workflow_schedule_id="wfs_test_1", first_fire_at=NEW_ANCHOR+ )+ )++ assert not result["ok"]+ assert "interval_seconds" in result["error"]["hint"]+ sched_client.update.assert_not_called()+def test_clear_name_sends_null(self, monkeypatch: pytest.MonkeyPatch) -> None:sched_client = _patch_schedules_client(monkeypatch)sched_client.get.return_value = _make_fern_schedule_response()diff --git a/tests/unit/test_taskv3_goal_composition.py b/tests/unit/test_taskv3_goal_composition.pyindex 3392ed460..9283b949e 100644--- a/tests/unit/test_taskv3_goal_composition.py+++ b/tests/unit/test_taskv3_goal_composition.py@@ -274,6 +274,12 @@ def test_an_extraction_only_block_is_told_to_report_absent_data_as_completed_nulassert len(added) == 1, addedassert "null" in added[0]assert "status=completed" in added[0]+ # Nulls cover only what the goal asks to read from the page: a value the goal asks the block to produce+ # (today's date, a value the goal states) must still come back, and page data must never be invented.+ assert "every field the page does not show set to null" not in added[0]+ assert "read from the page" in added[0]+ assert "never invent" in added[0]+ assert "current date" in added[0]# The control render is what shipped before the arm existed.assert control == render_block_context(extraction_only, block, None)[0]diff --git a/tests/unit/test_workflow_browser_profile_id.py b/tests/unit/test_workflow_browser_profile_id.pyindex c348dab1b..4bab29e98 100644--- a/tests/unit/test_workflow_browser_profile_id.py+++ b/tests/unit/test_workflow_browser_profile_id.py@@ -4,7 +4,7 @@ from collections.abc import Generatorfrom datetime import datetime, timezonefrom types import SimpleNamespacefrom typing import Any, cast-from unittest.mock import AsyncMock, Mock, patch+from unittest.mock import AsyncMock, Mock, call, patchimport pytest@@ -572,14 +572,28 @@ async def test_refresh_workflow_schedule_runtime_limits_reupserts_backend_schedubackend_schedule_id="temporal_1",workflow_schedule_id="wfs_1",cron_expression="0 */6 * * *",+ interval_seconds=None,+ first_fire_at=None,timezone="UTC",enabled=True,parameters={"url": "https://example.com"},)+ interval_schedule_with_backend = SimpleNamespace(+ backend_schedule_id="temporal_2",+ workflow_schedule_id="wfs_2",+ cron_expression=None,+ interval_seconds=18000,+ first_fire_at=datetime(2026, 10, 30, 15, 0, tzinfo=timezone.utc),+ timezone="America/New_York",+ enabled=False,+ parameters=None,+ )schedule_without_backend = SimpleNamespace(backend_schedule_id=None,workflow_schedule_id="wfs_local",cron_expression="0 */12 * * *",+ interval_seconds=None,+ first_fire_at=None,timezone="UTC",enabled=False,parameters=None,@@ -588,7 +602,7 @@ async def test_refresh_workflow_schedule_runtime_limits_reupserts_backend_scheduwith patch("skyvern.forge.sdk.workflow.service.app") as mock_app:mock_app.DATABASE.workflows.get_browser_action_policy = AsyncMock(return_value=None)mock_app.DATABASE.schedules.get_workflow_schedules = AsyncMock(- return_value=[schedule_with_backend, schedule_without_backend]+ return_value=[schedule_with_backend, interval_schedule_with_backend, schedule_without_backend])mock_app.AGENT_FUNCTION.upsert_workflow_schedule = AsyncMock()@@ -602,17 +616,34 @@ async def test_refresh_workflow_schedule_runtime_limits_reupserts_backend_scheduworkflow_permanent_id="wpid_test",organization_id="org_1",)- mock_app.AGENT_FUNCTION.upsert_workflow_schedule.assert_awaited_once_with(- backend_schedule_id="temporal_1",- organization_id="org_1",- workflow_permanent_id="wpid_test",- workflow_schedule_id="wfs_1",- cron_expression="0 */6 * * *",- timezone="UTC",- enabled=True,- parameters={"url": "https://example.com"},- max_elapsed_time_minutes=360,- )+ assert mock_app.AGENT_FUNCTION.upsert_workflow_schedule.await_args_list == [+ call(+ backend_schedule_id="temporal_1",+ organization_id="org_1",+ workflow_permanent_id="wpid_test",+ workflow_schedule_id="wfs_1",+ cron_expression="0 */6 * * *",+ timezone="UTC",+ enabled=True,+ parameters={"url": "https://example.com"},+ max_elapsed_time_minutes=360,+ interval_seconds=None,+ first_fire_at=None,+ ),+ call(+ backend_schedule_id="temporal_2",+ organization_id="org_1",+ workflow_permanent_id="wpid_test",+ workflow_schedule_id="wfs_2",+ cron_expression=None,+ timezone="America/New_York",+ enabled=False,+ parameters=None,+ max_elapsed_time_minutes=360,+ interval_seconds=18000,+ first_fire_at=datetime(2026, 10, 30, 15, 0, tzinfo=timezone.utc),+ ),+ ]def _make_workflow_update_service(diff --git a/tests/unit/test_workflow_run_minutes_gate.py b/tests/unit/test_workflow_run_minutes_gate.pyindex 6004bfe3d..47359e973 100644--- a/tests/unit/test_workflow_run_minutes_gate.py+++ b/tests/unit/test_workflow_run_minutes_gate.py@@ -320,6 +320,7 @@ async def test_finally_block_re_finalization_records_only_the_minutes_it_added(workflow_schedule_id=None,sequential_key=None,depends_on_workflow_run_id=None,+ task_queue=None,browser_session_id=None,browser_profile_id=None,browser_address=None,@@ -656,6 +657,19 @@ async def test_an_unattributed_run_logs_why_attribution_abstained(record_run_durassert event["attribution_evidence_source"] == "keyword_only"+async def test_the_terminal_run_log_names_the_task_queue(record_run_duration: AsyncMock) -> None:+ # Start wait differs sharply by worker queue (pod size and engine), so the scorecard splits it by queue.+ row = _make_row(started=True)+ row.task_queue = "fairness-patchright-1vcpu-4gb"++ with capture_logs() as logs:+ await WorkflowService()._after_workflow_run_status_write(row, WorkflowRunStatus.completed)++ [event] = [e for e in logs if e.get("event") == "Workflow run duration metrics"]+ assert event["task_queue"] == "fairness-patchright-1vcpu-4gb"++@pytest.mark.asyncioasync def test_duration_log_reads_unknown_when_no_context_is_current(record_run_duration: AsyncMock,diff --git a/tests/unit/test_workflow_schedule_service.py b/tests/unit/test_workflow_schedule_service.pyindex aa1ff5e20..2616641b9 100644--- a/tests/unit/test_workflow_schedule_service.py+++ b/tests/unit/test_workflow_schedule_service.py@@ -52,7 +52,7 @@ async def test_get_due_schedule_skips_backfill_after_modified_at(monkeypatch: pyDATABASE=SimpleNamespace(schedules=SimpleNamespace(has_schedule_fired_since=has_schedule_fired_since))),)- monkeypatch.setattr(schedule_service, "compute_previous_fire_time", lambda *_args: previous_fire_time)+ monkeypatch.setattr(schedule_service, "compute_previous_fire_time", lambda *_args, **_kwargs: previous_fire_time)scheduler = schedule_service.LocalWorkflowScheduleScheduler(poll_interval_seconds=1, max_concurrent_runs=1)@@ -72,7 +72,7 @@ async def test_get_due_schedule_skips_when_fire_already_has_run(monkeypatch: pytDATABASE=SimpleNamespace(schedules=SimpleNamespace(has_schedule_fired_since=has_schedule_fired_since))),)- monkeypatch.setattr(schedule_service, "compute_previous_fire_time", lambda *_args: previous_fire_time)+ monkeypatch.setattr(schedule_service, "compute_previous_fire_time", lambda *_args, **_kwargs: previous_fire_time)scheduler = schedule_service.LocalWorkflowScheduleScheduler(poll_interval_seconds=1, max_concurrent_runs=1)@@ -123,7 +123,7 @@ async def test_dispatch_due_schedules_launches_scheduled_workflow(monkeypatch: p)monkeypatch.setattr(schedule_service, "app", fake_app)monkeypatch.setattr(retry_policy_module, "app", fake_app)- monkeypatch.setattr(schedule_service, "compute_previous_fire_time", lambda *_args: previous_fire_time)+ monkeypatch.setattr(schedule_service, "compute_previous_fire_time", lambda *_args, **_kwargs: previous_fire_time)monkeypatch.setattr(schedule_service, "prepare_workflow", prepare_workflow)monkeypatch.setattr(schedule_service, "initialize_skyvern_state_file", initialize_state)monkeypatch.setattr(schedule_service, "prepare_org_llm_runtime", prepare_llm)diff --git a/tests/unit/test_workflow_service_managed_browser_profile.py b/tests/unit/test_workflow_service_managed_browser_profile.pyindex 9fe9839fe..13bc512f4 100644--- a/tests/unit/test_workflow_service_managed_browser_profile.py+++ b/tests/unit/test_workflow_service_managed_browser_profile.py@@ -116,6 +116,7 @@ def _execute_workflow_run(status: WorkflowRunStatus) -> SimpleNamespace:ignore_inherited_workflow_system_prompt=False,parent_workflow_run_id=None,depends_on_workflow_run_id=None,+ task_queue=None,proxy_location=None,max_elapsed_time_minutes=1,started_at=now,