Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Let a workflow schedule run once at a set time (SKY-16176) (#8680)
Andrew Neilson15ccb91bf5cf
diff --git a/alembic/versions/2026_09_27_0506-9bde879d4fc0_add_one_time_cadence_to_workflow_schedules.py b/alembic/versions/2026_09_27_0506-9bde879d4fc0_add_one_time_cadence_to_workflow_schedules.pynew file mode 100644index 000000000..e0672fd30--- /dev/null+++ b/alembic/versions/2026_09_27_0506-9bde879d4fc0_add_one_time_cadence_to_workflow_schedules.py@@ -0,0 +1,57 @@+"""add one-time cadence to workflow_schedules++Revision ID: 9bde879d4fc0+Revises: adf6f1f2e672+Create Date: 2026-09-27T05:06:02.153506+00:00++"""++from typing import Sequence, Union++import sqlalchemy as sa++from alembic import op++# revision identifiers, used by Alembic.+revision: str = "9bde879d4fc0"+down_revision: Union[str, None] = "adf6f1f2e672"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None++CADENCE_CHECK = "ck_workflow_schedules_one_cadence"+OLD_CADENCE_RULE = (+ "(cron_expression IS NULL) <> (interval_seconds IS NULL) AND (interval_seconds IS NULL) = (first_fire_at IS NULL)"+)+NEW_CADENCE_RULE = (+ "(CASE WHEN cron_expression IS NULL THEN 0 ELSE 1 END + CASE WHEN interval_seconds IS NULL THEN 0 ELSE 1 END "+ "+ CASE WHEN run_at IS NULL THEN 0 ELSE 1 END) = 1 "+ "AND (interval_seconds IS NULL) = (first_fire_at IS NULL) "+ "AND (run_at IS NULL) = (dispatch_status IS NULL)"+)+++def upgrade() -> None:+ op.execute("SET LOCAL lock_timeout = '5s'")+ op.add_column("workflow_schedules", sa.Column("run_at", sa.DateTime(), nullable=True))+ op.add_column("workflow_schedules", sa.Column("dispatch_status", sa.String(), nullable=True))+ op.add_column("workflow_schedules", sa.Column("workflow_run_id", sa.String(), nullable=True))+ op.drop_constraint(CADENCE_CHECK, "workflow_schedules", type_="check")+ op.create_check_constraint(CADENCE_CHECK, "workflow_schedules", NEW_CADENCE_RULE)+++def downgrade() -> None:+ count = (+ op.get_bind().execute(sa.text("SELECT COUNT(*) FROM workflow_schedules WHERE run_at IS NOT NULL")).scalar_one()+ )+ if count:+ raise RuntimeError(+ f"Refusing to downgrade: workflow_schedules holds {count} one-time schedules. Cancel or delete the live "+ "ones through the schedules API, then run `DELETE FROM workflow_schedules WHERE run_at IS NOT NULL` "+ "and retry."+ )+ op.execute("SET LOCAL lock_timeout = '5s'")+ op.drop_constraint(CADENCE_CHECK, "workflow_schedules", type_="check")+ op.create_check_constraint(CADENCE_CHECK, "workflow_schedules", OLD_CADENCE_RULE)+ op.drop_column("workflow_schedules", "workflow_run_id")+ op.drop_column("workflow_schedules", "dispatch_status")+ op.drop_column("workflow_schedules", "run_at")diff --git a/docs/api-reference/openapi.json b/docs/api-reference/openapi.jsonindex 86d2d80a4..e19256679 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 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.",+ "description": "Create a cron, fixed-interval or one-time 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. A one-time schedule runs once at run_at. Returns the stored schedule and its next upcoming run times.","operationId": "schedules_create","parameters": [{@@ -7465,7 +7465,7 @@"Schedules"],"summary": "Update an agent schedule",- "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.",+ "description": "Replace a schedule's cron expression, interval or one-time run_at, timezone, run parameters, and enabled state. A one-time schedule stays one-time and can change only until it fires; afterwards this returns 409. Returns the updated schedule and its next upcoming run times.","operationId": "schedules_update","parameters": [{@@ -7607,6 +7607,76 @@}}},+ "/v1/agents/{workflow_permanent_id}/schedules/{workflow_schedule_id}/cancel": {+ "post": {+ "tags": [+ "Schedules"+ ],+ "summary": "Cancel a one-time agent schedule",+ "description": "Cancel a one-time schedule that has not fired yet. The schedule stays readable with dispatch_status canceled. Returns 409 once it has fired or was already canceled, and 422 for a recurring schedule.",+ "operationId": "schedules_cancel",+ "parameters": [+ {+ "name": "workflow_permanent_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "title": "Workflow Permanent Id"+ }+ },+ {+ "name": "workflow_schedule_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "title": "Workflow Schedule Id"+ }+ },+ {+ "name": "x-api-key",+ "in": "header",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings.",+ "title": "X-Api-Key"+ },+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings."+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WorkflowScheduleResponse"+ }+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ }+ }+ },"/v1/agents/{workflow_permanent_id}/schedules/{workflow_schedule_id}/enable": {"post": {"tags": [@@ -20941,6 +21011,16 @@],"title": "OnePasswordCredentialParameterYAML"},+ "OneTimeDispatchStatus": {+ "type": "string",+ "enum": [+ "pending",+ "fired",+ "canceled",+ "failed"+ ],+ "title": "OneTimeDispatchStatus"+ },"OrganizationScheduleItem": {"properties": {"workflow_schedule_id": {@@ -20993,6 +21073,39 @@],"title": "First Fire At"},+ "run_at": {+ "anyOf": [+ {+ "type": "string",+ "format": "date-time"+ },+ {+ "type": "null"+ }+ ],+ "title": "Run At"+ },+ "dispatch_status": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/OneTimeDispatchStatus"+ },+ {+ "type": "null"+ }+ ]+ },+ "workflow_run_id": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Workflow Run Id"+ },"timezone": {"type": "string","title": "Timezone"@@ -32901,6 +33014,39 @@],"title": "First Fire At"},+ "run_at": {+ "anyOf": [+ {+ "type": "string",+ "format": "date-time"+ },+ {+ "type": "null"+ }+ ],+ "title": "Run At"+ },+ "dispatch_status": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/OneTimeDispatchStatus"+ },+ {+ "type": "null"+ }+ ]+ },+ "workflow_run_id": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Workflow Run Id"+ },"timezone": {"type": "string","title": "Timezone"@@ -33065,6 +33211,19 @@"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."},+ "run_at": {+ "anyOf": [+ {+ "type": "string",+ "format": "date-time"+ },+ {+ "type": "null"+ }+ ],+ "title": "Run At",+ "description": "Run the agent once at this instant, ISO 8601 with a UTC offset, at least 60 seconds in the future. Mutually exclusive with cron_expression and interval_seconds; the schedule can be edited or canceled only until it fires."+ },"timezone": {"type": "string","title": "Timezone"diff --git a/docs/cloud/building-agents/run-from-code.mdx b/docs/cloud/building-agents/run-from-code.mdxindex 57c7e266f..8071cab62 100644--- a/docs/cloud/building-agents/run-from-code.mdx+++ b/docs/cloud/building-agents/run-from-code.mdx@@ -315,8 +315,9 @@ curl -X POST "https://api.skyvern.com/api/v1/workflows/wpid_123456789/schedules"| Field | Type | Required | Description ||-------|------|----------|-------------|-| `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 |+| `cron_expression` | string | One of these three | 5-field cron expression (minimum 5-minute interval) |+| `interval_seconds` | integer | One of these three | 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 |+| `run_at` | datetime | One of these three | Run the agent once at this instant, with a timezone offset, at least 60 seconds in the future. A one-time schedule cannot be disabled || `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 |@@ -324,6 +325,8 @@ curl -X POST "https://api.skyvern.com/api/v1/workflows/wpid_123456789/schedules"| `parameters` | object | No | Agent parameters to pass on each run || `enabled` | boolean | No | Whether the schedule is active. Defaults to `true` |+A one-time schedule reads back a `dispatch_status` of `pending`, `fired`, `canceled` or `failed`, and a `workflow_run_id` once it fires. If the scheduler was down at `run_at`, the schedule fires once when it recovers. You can update `run_at` or `parameters` only while the schedule is `pending`; after it fires, updates return `409`.+### Enable and disable a schedule<CodeGroup>@@ -352,6 +355,24 @@ curl -X POST "https://api.skyvern.com/api/v1/workflows/wpid_123456789/schedules/```</CodeGroup>+### Cancel a one-time schedule++Cancel a one-time schedule before it fires. It stays readable with `dispatch_status` `canceled`. Canceling returns `409` once the schedule has fired or was already canceled, and `422` for a recurring schedule.++<CodeGroup>+```python Python+await client.schedules.cancel(+ workflow_permanent_id="wpid_123456789",+ workflow_schedule_id="wfs_abc123"+)+```++```bash cURL+curl -X POST "https://api.skyvern.com/api/v1/workflows/wpid_123456789/schedules/wfs_abc123/cancel" \+ -H "x-api-key: $SKYVERN_API_KEY"+```+</CodeGroup>+### Delete a schedulePermanently remove a schedule. This cannot be undone. Runs that were already triggered by this schedule are not affected.diff --git a/fern/openapi/skyvern_openapi.json b/fern/openapi/skyvern_openapi.jsonindex 8f354b014..0fc752d12 100644--- a/fern/openapi/skyvern_openapi.json+++ b/fern/openapi/skyvern_openapi.json@@ -6839,7 +6839,7 @@}}},- "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."+ "description": "Create a cron, fixed-interval or one-time 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. A one-time schedule runs once at run_at. Returns the stored schedule and its next upcoming run times."},"get": {"tags": [@@ -7045,7 +7045,7 @@}}},- "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."+ "description": "Replace a schedule's cron expression, interval or one-time run_at, timezone, run parameters, and enabled state. A one-time schedule stays one-time and can change only until it fires; afterwards this returns 409. Returns the updated schedule and its next upcoming run times."},"delete": {"tags": [@@ -7252,6 +7252,76 @@}}}+ },+ "/v1/agents/{workflow_permanent_id}/schedules/{workflow_schedule_id}/cancel": {+ "post": {+ "tags": [+ "Schedules"+ ],+ "summary": "Cancel a one-time agent schedule",+ "description": "Cancel a one-time schedule that has not fired yet. The schedule stays readable with dispatch_status canceled. Returns 409 once it has fired or was already canceled, and 422 for a recurring schedule.",+ "operationId": "schedules_cancel",+ "parameters": [+ {+ "name": "workflow_permanent_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "title": "Workflow Permanent Id"+ }+ },+ {+ "name": "workflow_schedule_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "title": "Workflow Schedule Id"+ }+ },+ {+ "name": "x-api-key",+ "in": "header",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings.",+ "title": "X-Api-Key"+ },+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings."+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/WorkflowScheduleResponse"+ }+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ }+ }}},"components": {@@ -18597,6 +18667,39 @@],"title": "First Fire At"},+ "run_at": {+ "anyOf": [+ {+ "type": "string",+ "format": "date-time"+ },+ {+ "type": "null"+ }+ ],+ "title": "Run At"+ },+ "dispatch_status": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/OneTimeDispatchStatus"+ },+ {+ "type": "null"+ }+ ]+ },+ "workflow_run_id": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Workflow Run Id"+ },"timezone": {"type": "string","title": "Timezone"@@ -28886,6 +28989,39 @@],"title": "First Fire At"},+ "run_at": {+ "anyOf": [+ {+ "type": "string",+ "format": "date-time"+ },+ {+ "type": "null"+ }+ ],+ "title": "Run At"+ },+ "dispatch_status": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/OneTimeDispatchStatus"+ },+ {+ "type": "null"+ }+ ]+ },+ "workflow_run_id": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Workflow Run Id"+ },"timezone": {"type": "string","title": "Timezone"@@ -29050,6 +29186,19 @@"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."},+ "run_at": {+ "anyOf": [+ {+ "type": "string",+ "format": "date-time"+ },+ {+ "type": "null"+ }+ ],+ "title": "Run At",+ "description": "Run the agent once at this instant, ISO 8601 with a UTC offset, at least 60 seconds in the future. Mutually exclusive with cron_expression and interval_seconds; the schedule can be edited or canceled only until it fires."+ },"timezone": {"type": "string","title": "Timezone"@@ -29447,6 +29596,16 @@"azure_vault"],"title": "CredentialType"+ },+ "OneTimeDispatchStatus": {+ "type": "string",+ "enum": [+ "pending",+ "fired",+ "canceled",+ "failed"+ ],+ "title": "OneTimeDispatchStatus"}}},diff --git a/skyvern-frontend/src/routes/schedules/ScheduleDetailPage.tsx b/skyvern-frontend/src/routes/schedules/ScheduleDetailPage.tsxindex 4ad90718c..79281f58b 100644--- a/skyvern-frontend/src/routes/schedules/ScheduleDetailPage.tsx+++ b/skyvern-frontend/src/routes/schedules/ScheduleDetailPage.tsx@@ -41,6 +41,7 @@ import {} from "@/routes/workflows/components/scheduleParameters";import { useScheduleParameterState } from "@/routes/workflows/hooks/useScheduleParameterState";import type { Parameter } from "@/routes/workflows/types/workflowTypes";+import { DispatchStatusPill } from "@/routes/workflows/editor/panels/schedulePanel/DispatchStatusPill";function ScheduleDetailPage() {const navigate = useNavigate();@@ -117,6 +118,7 @@ function ScheduleDetailPage() {const { schedule, next_runs } = data;const humanReadable = describeCadence(schedule);+ const isOneTime = schedule.run_at != null;const firstRun = upcomingFirstRun(schedule.first_fire_at);const scheduleCronTooFrequent = cronBelowMinInterval(schedule.cron_expression,@@ -184,6 +186,9 @@ function ScheduleDetailPage() {cron_expression: schedule.cron_expression,interval_seconds: schedule.interval_seconds,first_fire_at: schedule.first_fire_at,+ run_at: schedule.run_at,+ dispatch_status: schedule.dispatch_status,+ workflow_run_id: schedule.workflow_run_id,timezone: schedule.timezone,enabled: schedule.enabled,parameters: schedule.parameters,@@ -209,6 +214,9 @@ function ScheduleDetailPage() {cron_expression: schedule.cron_expression,interval_seconds: schedule.interval_seconds,first_fire_at: schedule.first_fire_at,+ run_at: schedule.run_at,+ dispatch_status: schedule.dispatch_status,+ workflow_run_id: schedule.workflow_run_id,timezone: schedule.timezone,enabled: schedule.enabled,parameters: schedule.parameters,@@ -253,7 +261,9 @@ function ScheduleDetailPage() {{workflowTitle} runs →</Link></div>- <Switch checked={schedule.enabled} onCheckedChange={handleToggle} />+ {!isOneTime && (+ <Switch checked={schedule.enabled} onCheckedChange={handleToggle} />+ )}<Buttonvariant="destructive"size="icon"@@ -270,7 +280,7 @@ function ScheduleDetailPage() {<div className="rounded-lg border border-slate-700 p-4"><div className="mb-4 flex items-center justify-between"><h3 className="text-sm text-slate-400">Schedule Configuration</h3>- {!editing && (+ {!editing && !isOneTime && (<Buttonvariant="ghost"size="sm"@@ -365,6 +375,35 @@ function ScheduleDetailPage() {{schedule.timezone}</span></div>+ {schedule.run_at && (+ <div className="flex items-start justify-between">+ <span className="text-sm text-slate-400">Runs at</span>+ <span className="text-sm text-slate-50">+ {formatNextRun(+ new Date(schedule.run_at),+ schedule.timezone,+ )}+ </span>+ </div>+ )}+ {schedule.dispatch_status && (+ <div className="flex items-start justify-between">+ <span className="text-sm text-slate-400">Status</span>+ <DispatchStatusPill status={schedule.dispatch_status} />+ </div>+ )}+ {schedule.dispatch_status === "fired" &&+ schedule.workflow_run_id && (+ <div className="flex items-start justify-between">+ <span className="text-sm text-slate-400">Run</span>+ <Link+ to={`/runs/${schedule.workflow_run_id}`}+ className="font-mono text-xs text-slate-50 hover:underline"+ >+ {schedule.workflow_run_id}+ </Link>+ </div>+ )}{schedule.cron_expression && (<div className="flex items-start justify-between"><span className="text-sm text-slate-400">Cron</span>@@ -459,19 +498,21 @@ function ScheduleDetailPage() {</div>)}- <div className="rounded-lg border border-slate-700 p-4">- <h3 className="mb-4 text-sm text-slate-400">Upcoming Runs</h3>- <p className="mb-2 text-xs text-slate-400">- Next {next_runs.length} runs- </p>- <div className="space-y-0.5">- {next_runs.map((run) => (- <p key={run} className="text-xs text-slate-500">- {formatNextRun(new Date(run), schedule.timezone)}- </p>- ))}+ {!isOneTime && (+ <div className="rounded-lg border border-slate-700 p-4">+ <h3 className="mb-4 text-sm text-slate-400">Upcoming Runs</h3>+ <p className="mb-2 text-xs text-slate-400">+ Next {next_runs.length} runs+ </p>+ <div className="space-y-0.5">+ {next_runs.map((run) => (+ <p key={run} className="text-xs text-slate-500">+ {formatNextRun(new Date(run), schedule.timezone)}+ </p>+ ))}+ </div></div>- </div>+ )}</div></div><ConfirmDialogdiff --git a/skyvern-frontend/src/routes/schedules/SchedulesPage.tsx b/skyvern-frontend/src/routes/schedules/SchedulesPage.tsxindex a82357598..65e46ed4d 100644--- a/skyvern-frontend/src/routes/schedules/SchedulesPage.tsx+++ b/skyvern-frontend/src/routes/schedules/SchedulesPage.tsx@@ -77,6 +77,7 @@ import {} from "@/routes/workflows/editor/panels/schedulePanel/scheduleCadence";import { basicLocalTimeFormat, basicTimeFormat } from "@/util/timeFormat";import type { OrganizationScheduleItem } from "@/routes/workflows/types/scheduleTypes";+import { DispatchStatusPill } from "@/routes/workflows/editor/panels/schedulePanel/DispatchStatusPill";import { CreateOrgScheduleDialog } from "./CreateOrgScheduleDialog";type ScheduleStatus = "active" | "paused";@@ -94,6 +95,15 @@ function StatusDisplay({ enabled }: Readonly<{ enabled: boolean }>) {);}+function RunTimeDisplay({ time }: Readonly<{ time: string | null }>) {+ if (!time) {+ return "\u2014";+ }+ return (+ <span title={basicTimeFormat(time)}>{basicLocalTimeFormat(time)}</span>+ );+}+const PAGE_SIZE_OPTIONS = ["10", "25", "50"];function SchedulesPage() {@@ -239,8 +249,21 @@ function SchedulesPage() {}}+ const selectedRecurring = selectedSchedules.filter((s) => s.run_at == null);++ function recurringOnly(action: string) {+ const skipped = selectedSchedules.length - selectedRecurring.length;+ if (skipped > 0) {+ toast({+ title: `Skipped ${skipped} one-time schedule${skipped !== 1 ? "s" : ""}.`,+ description: `One-time schedules cannot be ${action}.`,+ });+ }+ return selectedRecurring;+ }+function handleBulkActivate() {- const toActivate = selectedSchedules.filter((s) => !s.enabled);+ const toActivate = recurringOnly("activated").filter((s) => !s.enabled);if (toActivate.length === 0) {toast({ title: "All selected schedules are already active." });return;@@ -257,7 +280,7 @@ function SchedulesPage() {}function handleBulkPause() {- const toPause = selectedSchedules.filter((s) => s.enabled);+ const toPause = recurringOnly("paused").filter((s) => s.enabled);if (toPause.length === 0) {toast({ title: "All selected schedules are already paused." });return;@@ -275,7 +298,7 @@ function SchedulesPage() {function handleBulkDuplicate() {void runBulkOperation(- selectedSchedules,+ recurringOnly("duplicated"),(client, item) =>client.post(`/workflows/${item.workflow_permanent_id}/schedules`,@@ -490,16 +513,22 @@ function SchedulesPage() {</div></TableCell><TableCell className="text-slate-400">- {schedule.next_run ? (- <span title={basicTimeFormat(schedule.next_run)}>- {basicLocalTimeFormat(schedule.next_run)}- </span>- ) : (- "\u2014"- )}+ <RunTimeDisplay+ time={+ schedule.dispatch_status === "pending"+ ? schedule.run_at+ : schedule.next_run+ }+ /></TableCell><TableCell>- <StatusDisplay enabled={schedule.enabled} />+ {schedule.run_at != null ? (+ schedule.dispatch_status && (+ <DispatchStatusPill status={schedule.dispatch_status} />+ )+ ) : (+ <StatusDisplay enabled={schedule.enabled} />+ )}</TableCell><TableCell onClick={(e) => e.stopPropagation()}>{/* Row menus yield to the bulk bar while any selection is active. */}@@ -515,7 +544,7 @@ function SchedulesPage() {</Button></DropdownMenuTrigger><DropdownMenuContent align="end">- {schedule.enabled ? (+ {schedule.run_at != null ? null : schedule.enabled ? (<DropdownMenuItemonSelect={() => disableMutation.mutate(schedule)}>@@ -530,12 +559,16 @@ function SchedulesPage() {Activate</DropdownMenuItem>)}- <DropdownMenuItem- onSelect={() => duplicateMutation.mutate(schedule)}- >- <CopyIcon className="mr-2 size-4" />- Duplicate- </DropdownMenuItem>+ {schedule.run_at == null && (+ <DropdownMenuItem+ onSelect={() =>+ duplicateMutation.mutate(schedule)+ }+ >+ <CopyIcon className="mr-2 size-4" />+ Duplicate+ </DropdownMenuItem>+ )}<DropdownMenuItemonSelect={() =>setDeleteDialog({ open: true, schedule })@@ -628,7 +661,7 @@ function SchedulesPage() {size="sm"variant="ghost"onClick={handleBulkActivate}- disabled={isBulkOperating}+ disabled={isBulkOperating || selectedRecurring.length === 0}><PlayIcon className="mr-1.5 size-3.5" />Activate@@ -637,7 +670,7 @@ function SchedulesPage() {size="sm"variant="ghost"onClick={handleBulkPause}- disabled={isBulkOperating}+ disabled={isBulkOperating || selectedRecurring.length === 0}><PauseIcon className="mr-1.5 size-3.5" />Pause@@ -646,7 +679,7 @@ function SchedulesPage() {size="sm"variant="ghost"onClick={handleBulkDuplicate}- disabled={isBulkOperating}+ disabled={isBulkOperating || selectedRecurring.length === 0}><CopyIcon className="mr-1.5 size-3.5" />Duplicatediff --git a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.tsindex 582031755..e3a8b4c87 100644--- a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts@@ -691,6 +691,7 @@ const ACTIVITY_TOOL_DISPLAY_LABELS: Record<string, string> = {enable_workflow_schedule: "Resuming a schedule",disable_workflow_schedule: "Pausing a schedule",delete_workflow_schedule: "Deleting a schedule",+ cancel_workflow_schedule: "Canceling a schedule",get_block_schema: "Checking workflow block options",inspect_current_workflow: "Inspecting workflow",discover_workflow_entrypoint: "Finding the entry page",diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/DispatchStatusPill.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/DispatchStatusPill.tsxnew file mode 100644index 000000000..5cd904d8b--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/DispatchStatusPill.tsx@@ -0,0 +1,21 @@+import { Pill, type PillTone } from "@/components/StatusBadge";+import type { OneTimeDispatchStatus } from "@/routes/workflows/types/scheduleTypes";++const DISPLAY: Record<+ OneTimeDispatchStatus,+ { tone: PillTone; label: string }+> = {+ pending: { tone: "success", label: "Scheduled" },+ fired: { tone: "neutral", label: "Started" },+ canceled: { tone: "neutral", label: "Canceled" },+ failed: { tone: "danger", label: "Failed to start" },+};++function DispatchStatusPill({+ status,+}: Readonly<{ status: OneTimeDispatchStatus }>) {+ const { tone, label } = DISPLAY[status];+ return <Pill tone={tone}>{label}</Pill>;+}++export { DispatchStatusPill };diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/ScheduleCard.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/ScheduleCard.tsxindex 1949e101e..3b058471a 100644--- a/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/ScheduleCard.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/ScheduleCard.tsx@@ -1,7 +1,9 @@import { TrashIcon } from "@radix-ui/react-icons";+import { Link } from "react-router-dom";import { Switch } from "@/components/ui/switch";import { Button } from "@/components/ui/button";import type { WorkflowSchedule } from "@/routes/workflows/types/scheduleTypes";+import { DispatchStatusPill } from "./DispatchStatusPill";import { formatNextRun } from "./cronUtils";import {describeCadence,@@ -19,7 +21,10 @@ type Props = {function ScheduleCard({ schedule, isToggling, onToggle, onDelete }: Props) {const humanReadable = describeCadence(schedule);- const nextRun = getCadenceNextRuns(schedule, schedule.timezone, 1)[0];+ const isOneTime = schedule.run_at != null;+ const nextRun = schedule.run_at+ ? new Date(schedule.run_at)+ : getCadenceNextRuns(schedule, schedule.timezone, 1)[0];const firstRun = upcomingFirstRun(schedule.first_fire_at);return (@@ -49,13 +54,19 @@ function ScheduleCard({ schedule, isToggling, onToggle, onDelete }: Props) {{schedule.timezone}</span><div className="flex items-center gap-2">- <Switch- checked={schedule.enabled}- disabled={isToggling}- onCheckedChange={(checked) =>- onToggle(schedule.workflow_schedule_id, checked)- }- />+ {isOneTime ? (+ schedule.dispatch_status && (+ <DispatchStatusPill status={schedule.dispatch_status} />+ )+ ) : (+ <Switch+ checked={schedule.enabled}+ disabled={isToggling}+ onCheckedChange={(checked) =>+ onToggle(schedule.workflow_schedule_id, checked)+ }+ />+ )}<Buttonvariant="ghost"size="icon"@@ -73,10 +84,22 @@ function ScheduleCard({ schedule, isToggling, onToggle, onDelete }: Props) {)}{nextRun && (<div className="text-xs text-muted-foreground dark:text-slate-500">- {schedule.enabled ? "Next" : "Next (paused)"}:{" "}- {formatNextRun(nextRun, schedule.timezone)}+ {isOneTime+ ? "Scheduled for"+ : schedule.enabled+ ? "Next"+ : "Next (paused)"}+ : {formatNextRun(nextRun, schedule.timezone)}</div>)}+ {schedule.dispatch_status === "fired" && schedule.workflow_run_id && (+ <Link+ to={`/runs/${schedule.workflow_run_id}`}+ className="text-xs text-muted-foreground hover:underline dark:text-slate-500"+ >+ Run {schedule.workflow_run_id}+ </Link>+ )}</div>);}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.tsindex dfb3e4d7e..4b1a34f0b 100644--- a/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/scheduleCadence.test.ts+++ b/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/scheduleCadence.test.ts@@ -3,7 +3,9 @@ import type { OrganizationScheduleItem } from "@/routes/workflows/types/scheduleimport {buildCadencePayload,buildDuplicateSchedulePayload,+ describeCadence,formatInterval,+ getCadenceNextRuns,getIntervalRuns,intervalDraftErrors,intervalDraftFromSeconds,@@ -24,6 +26,9 @@ function orgSchedule(cron_expression: null,interval_seconds: null,first_fire_at: null,+ run_at: null,+ dispatch_status: null,+ workflow_run_id: null,timezone: "America/Los_Angeles",enabled: false,parameters: { city: "Toronto" },@@ -249,3 +254,28 @@ describe("buildDuplicateSchedulePayload", () => {expect(payload).not.toHaveProperty("first_fire_at");});});++describe("one-time cadence", () => {+ const oneTime = orgSchedule({ run_at: "2026-11-02T08:01:00Z" });++ it("describes the schedule as running once", () => {+ expect(describeCadence(oneTime)).toBe("Once");+ });++ it("lists run_at as the next run only while pending", () => {+ expect(+ getCadenceNextRuns(+ { ...oneTime, dispatch_status: "pending" },+ oneTime.timezone,+ 5,+ ),+ ).toEqual([new Date("2026-11-02T08:01:00Z")]);+ expect(+ getCadenceNextRuns(+ { ...oneTime, dispatch_status: "fired" },+ oneTime.timezone,+ 5,+ ),+ ).toEqual([]);+ });+});diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/scheduleCadence.ts b/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/scheduleCadence.tsindex df0ce974e..ae90f3a0c 100644--- a/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/scheduleCadence.ts+++ b/skyvern-frontend/src/routes/workflows/editor/panels/schedulePanel/scheduleCadence.ts@@ -27,7 +27,11 @@ export type IntervalDraftErrors = {export type ScheduleCadence = Pick<WorkflowSchedule,- "cron_expression" | "interval_seconds" | "first_fire_at"+ | "cron_expression"+ | "interval_seconds"+ | "first_fire_at"+ | "run_at"+ | "dispatch_status">;export type CadencePayload =@@ -184,6 +188,9 @@ export function upcomingFirstRun(}export function describeCadence(schedule: ScheduleCadence): string {+ if (schedule.run_at) {+ return "Once";+ }if (schedule.interval_seconds) {return formatInterval(schedule.interval_seconds);}@@ -195,6 +202,11 @@ export function getCadenceNextRuns(timezone: string,count: number,): Date[] {+ if (schedule.run_at) {+ return schedule.dispatch_status === "pending"+ ? [new Date(schedule.run_at)]+ : [];+ }if (schedule.interval_seconds && schedule.first_fire_at) {return getIntervalRuns(schedule.interval_seconds,diff --git a/skyvern-frontend/src/routes/workflows/types/scheduleTypes.ts b/skyvern-frontend/src/routes/workflows/types/scheduleTypes.tsindex 67171aae1..41bc2c83e 100644--- a/skyvern-frontend/src/routes/workflows/types/scheduleTypes.ts+++ b/skyvern-frontend/src/routes/workflows/types/scheduleTypes.ts@@ -1,3 +1,5 @@+export type OneTimeDispatchStatus = "pending" | "fired" | "canceled" | "failed";+export type WorkflowSchedule = {workflow_schedule_id: string;organization_id: string;@@ -5,6 +7,9 @@ export type WorkflowSchedule = {cron_expression: string | null;interval_seconds: number | null;first_fire_at: string | null;+ run_at: string | null;+ dispatch_status: OneTimeDispatchStatus | null;+ workflow_run_id: string | null;timezone: string;enabled: boolean;parameters: Record<string, unknown> | null;@@ -29,6 +34,7 @@ export type CreateScheduleRequest = {cron_expression?: string;interval_seconds?: number;first_fire_at?: string;+ run_at?: string;timezone: string;enabled?: boolean;parameters?: Record<string, unknown> | null;@@ -56,6 +62,9 @@ export type OrganizationScheduleItem = {cron_expression: string | null;interval_seconds: number | null;first_fire_at: string | null;+ run_at: string | null;+ dispatch_status: OneTimeDispatchStatus | null;+ workflow_run_id: string | null;timezone: string;enabled: boolean;parameters: Record<string, unknown> | null;diff --git a/skyvern/cli/mcp_tools/__init__.py b/skyvern/cli/mcp_tools/__init__.pyindex 8567066f2..f5dd62d23 100644--- a/skyvern/cli/mcp_tools/__init__.py+++ b/skyvern/cli/mcp_tools/__init__.py@@ -150,6 +150,7 @@ from .response_network import (from .response_storage import format_storage_responsefrom .response_workflow import format_workflow_responsefrom .schedule import (+ skyvern_schedule_cancel,skyvern_schedule_create,skyvern_schedule_delete,skyvern_schedule_disable,@@ -515,6 +516,7 @@ mcp.tool(tags={"schedule"}, annotations=_mut("Create Workflow Schedule"))(skyvermcp.tool(tags={"schedule"}, annotations=_mut("Update Workflow Schedule"))(skyvern_schedule_update)mcp.tool(tags={"schedule"}, annotations=_mut("Enable Workflow Schedule"))(skyvern_schedule_enable)mcp.tool(tags={"schedule"}, annotations=_mut("Disable Workflow Schedule"))(skyvern_schedule_disable)+mcp.tool(tags={"schedule"}, annotations=_dest("Cancel One-Time Workflow Schedule"))(skyvern_schedule_cancel)mcp.tool(tags={"schedule"}, annotations=_dest("Delete Workflow Schedule"))(skyvern_schedule_delete)# -- Script/caching tools (no browser needed) --@@ -664,6 +666,7 @@ __all__ = ["skyvern_schedule_update","skyvern_schedule_enable","skyvern_schedule_disable",+ "skyvern_schedule_cancel","skyvern_schedule_delete",# Script/caching"skyvern_script_list_for_workflow",diff --git a/skyvern/cli/mcp_tools/schedule.py b/skyvern/cli/mcp_tools/schedule.pyindex 85eca9a16..18d8f9ac2 100644--- a/skyvern/cli/mcp_tools/schedule.py+++ b/skyvern/cli/mcp_tools/schedule.py@@ -1,4 +1,4 @@-"""Skyvern MCP workflow-schedule tools — CRUD + enable/disable via ``client.schedules.*``."""+"""Skyvern MCP workflow-schedule tools — CRUD, enable/disable and cancel via ``client.schedules.*``."""from __future__ import annotations@@ -25,6 +25,9 @@ def _serialize_schedule(s: Any) -> dict[str, Any]:"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,+ "run_at": s.run_at.isoformat() if s.run_at else None,+ "dispatch_status": s.dispatch_status,+ "workflow_run_id": s.workflow_run_id,"timezone": s.timezone,"enabled": s.enabled,"parameters": s.parameters,@@ -54,6 +57,9 @@ def _serialize_org_schedule_item(item: Any) -> dict[str, Any]:"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,+ "run_at": item.run_at.isoformat() if item.run_at else None,+ "dispatch_status": item.dispatch_status,+ "workflow_run_id": item.workflow_run_id,"timezone": item.timezone,"enabled": item.enabled,"parameters": item.parameters,@@ -187,12 +193,16 @@ async def skyvern_schedule_create(workflow_permanent_id: Annotated[str, Field(description="Workflow ID (starts with wpid_)")],*,cron_expression: Annotated[- str | None, Field(description="Cron expression, e.g. '0 9 * * *'. Set this or interval_seconds.")+ str | None,+ Field(description="Cron expression, e.g. '0 9 * * *'. Set exactly one of this, interval_seconds or run_at."),] = 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."),+ Field(+ description="Run every N seconds (minimum 300), e.g. 259200 for every 72 hours. Set exactly one of this, "+ "cron_expression or run_at."+ ),] = None,first_fire_at: Annotated[datetime | None,@@ -200,6 +210,13 @@ async def skyvern_schedule_create(description="First run of an interval schedule, ISO 8601 with offset. Defaults to one interval from now."),] = None,+ run_at: Annotated[+ datetime | None,+ Field(+ description="Run once at this instant instead of recurring, ISO 8601 with UTC offset, at least 60 "+ "seconds ahead."+ ),+ ] = None,enabled: Annotated[bool, Field(description="Whether the schedule fires immediately. Defaults to True.")] = True,parameters: Annotated[dict[str, Any] | None,@@ -208,7 +225,7 @@ 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, on a cron or a fixed interval.+ """Create a schedule for an existing workflow: on a cron, on a fixed interval, or once at run_at.Cadence and timezone are validated server-side and errors are surfacedverbatim. Returns 501 if workflow schedules are disabled in this build.@@ -224,6 +241,7 @@ async def skyvern_schedule_create(cron_expression=cron_expression,interval_seconds=interval_seconds,first_fire_at=first_fire_at,+ run_at=run_at,timezone=timezone,enabled=enabled,parameters=parameters,@@ -285,6 +303,7 @@ def _check_update_mutex(def _check_update_exact_completeness(cron_expression: str | None,interval_seconds: int | None,+ run_at: datetime | None,timezone: str | None,enabled: bool | None,parameters: dict[str, Any] | None,@@ -301,8 +320,8 @@ def _check_update_exact_completeness(and silently flip a paused schedule active or wipe metadata."""missing: list[str] = []- if cron_expression is None and interval_seconds is None:- missing.append("cron_expression or interval_seconds")+ if cron_expression is None and interval_seconds is None and run_at is None:+ missing.append("cron_expression, interval_seconds or run_at")if timezone is None:missing.append("timezone")if enabled is None:@@ -333,6 +352,10 @@ async def skyvern_schedule_update(datetime | None,Field(description="New future first run for an interval schedule, ISO 8601 with offset."),] = None,+ run_at: Annotated[+ datetime | None,+ Field(description="New instant for a one-time schedule that has not fired yet, 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,@@ -369,7 +392,17 @@ async def skyvern_schedule_update(any_value_set = any(v is not None- for v in (cron_expression, interval_seconds, first_fire_at, timezone, enabled, parameters, name, description)+ for v in (+ cron_expression,+ interval_seconds,+ first_fire_at,+ run_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:@@ -392,6 +425,7 @@ async def skyvern_schedule_update(if err := _check_update_exact_completeness(cron_expression,interval_seconds,+ run_at,timezone,enabled,parameters,@@ -406,6 +440,7 @@ async def skyvern_schedule_update(body_cron = cron_expressionbody_interval = interval_secondsbody_first_fire_at = first_fire_at+ body_run_at = run_atbody_tz = timezonebody_enabled = enabledbody_params = None if clear_parameters else parameters@@ -442,17 +477,19 @@ async def skyvern_schedule_update(snapshot_modified_at=existing.modified_at.isoformat() if existing.modified_at else None,)- if cron_expression is None and interval_seconds is None and first_fire_at is None:+ if cron_expression is None and interval_seconds is None and first_fire_at is None and run_at is None:body_cron = existing.cron_expressionbody_interval = existing.interval_seconds# Omitted, the route keeps the stored anchor even once it is past.body_first_fire_at = None+ body_run_at = existing.run_atelse:- # Never merge a stored cadence into a new one of the other kind; the server rejects cron plus interval.+ # Never merge a stored cadence into a new one of the other kind; the server rejects mixed cadences.body_cron = cron_expressionbody_interval = interval_secondsbody_first_fire_at = first_fire_at- if cron_expression is None and interval_seconds is None:+ body_run_at = run_at+ if cron_expression is None and interval_seconds is None and run_at is None:if existing.interval_seconds is None:return _input_error("skyvern_schedule_update",@@ -476,6 +513,7 @@ async def skyvern_schedule_update(cron_expression=body_cron,interval_seconds=body_interval,first_fire_at=body_first_fire_at,+ run_at=body_run_at,timezone=body_tz,parameters=body_params,name=body_name,@@ -577,6 +615,36 @@ async def skyvern_schedule_disable()+async def skyvern_schedule_cancel(+ workflow_permanent_id: Annotated[str, Field(description="Workflow ID (starts with wpid_)")],+ workflow_schedule_id: Annotated[str, Field(description="Schedule ID (starts with wfs_)")],+) -> dict[str, Any]:+ """Cancel a one-time schedule before it fires; it stays readable with dispatch_status canceled.+ Fails with a conflict once the schedule has fired or was already canceled."""+ if err := validate_workflow_id(workflow_permanent_id, "skyvern_schedule_cancel"):+ return err+ if err := validate_schedule_id(workflow_schedule_id, "skyvern_schedule_cancel"):+ return err++ skyvern = get_skyvern()+ with Timer() as timer:+ try:+ resp = await skyvern.schedules.cancel(workflow_permanent_id, workflow_schedule_id)+ timer.mark("sdk")+ except ApiError as e:+ if e.status_code == 404:+ return _not_found_404("skyvern_schedule_cancel", workflow_schedule_id, timer)+ return _api_error("skyvern_schedule_cancel", e, timer, hint="Read the schedule to see its dispatch_status.")+ except Exception as e:+ return _api_error("skyvern_schedule_cancel", e, timer)++ return make_result(+ "skyvern_schedule_cancel",+ data=_serialize_schedule_response(resp),+ timing_ms=timer.timing_ms,+ )++async def skyvern_schedule_delete(workflow_permanent_id: Annotated[str, Field(description="Workflow ID (starts with wpid_)")],workflow_schedule_id: Annotated[str, Field(description="Schedule ID (starts with wfs_)")],@@ -620,6 +688,7 @@ async def skyvern_schedule_delete(__all__ = [+ "skyvern_schedule_cancel","skyvern_schedule_create","skyvern_schedule_delete","skyvern_schedule_disable",diff --git a/skyvern/client/__init__.py b/skyvern/client/__init__.pyindex c89824425..2a372965a 100644--- a/skyvern/client/__init__.py+++ b/skyvern/client/__init__.py@@ -364,6 +364,7 @@ if typing.TYPE_CHECKING:NonEmptyPasswordCredential,OnePasswordCredentialParameter,OnePasswordCredentialParameterYaml,+ OneTimeDispatchStatus,OrganizationScheduleItem,OrganizationScheduleListResponse,OtpType,@@ -1142,6 +1143,7 @@ _dynamic_imports: typing.Dict[str, str] = {"NotFoundError": ".errors","OnePasswordCredentialParameter": ".types","OnePasswordCredentialParameterYaml": ".types",+ "OneTimeDispatchStatus": ".types","OrganizationScheduleItem": ".types","OrganizationScheduleListResponse": ".types","OtpType": ".types",@@ -1938,6 +1940,7 @@ __all__ = ["NotFoundError","OnePasswordCredentialParameter","OnePasswordCredentialParameterYaml",+ "OneTimeDispatchStatus","OrganizationScheduleItem","OrganizationScheduleListResponse","OtpType",diff --git a/skyvern/client/schedules/client.py b/skyvern/client/schedules/client.pyindex 439bc21cf..ad2f0d723 100644--- a/skyvern/client/schedules/client.py+++ b/skyvern/client/schedules/client.py@@ -117,6 +117,7 @@ class SchedulesClient:cron_expression: typing.Optional[str] = OMIT,interval_seconds: typing.Optional[int] = OMIT,first_fire_at: typing.Optional[dt.datetime] = OMIT,+ run_at: typing.Optional[dt.datetime] = OMIT,timezone: str,enabled: typing.Optional[bool] = OMIT,parameters: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,@@ -135,6 +136,8 @@ class SchedulesClient:first_fire_at : typing.Optional[dt.datetime]+ run_at : typing.Optional[dt.datetime]+timezone : strenabled : typing.Optional[bool]@@ -171,6 +174,7 @@ class SchedulesClient:cron_expression=cron_expression,interval_seconds=interval_seconds,first_fire_at=first_fire_at,+ run_at=run_at,timezone=timezone,enabled=enabled,parameters=parameters,@@ -225,6 +229,7 @@ class SchedulesClient:cron_expression: typing.Optional[str] = OMIT,interval_seconds: typing.Optional[int] = OMIT,first_fire_at: typing.Optional[dt.datetime] = OMIT,+ run_at: typing.Optional[dt.datetime] = OMIT,timezone: str,enabled: typing.Optional[bool] = OMIT,parameters: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,@@ -245,6 +250,8 @@ class SchedulesClient:first_fire_at : typing.Optional[dt.datetime]+ run_at : typing.Optional[dt.datetime]+timezone : strenabled : typing.Optional[bool]@@ -283,6 +290,7 @@ class SchedulesClient:cron_expression=cron_expression,interval_seconds=interval_seconds,first_fire_at=first_fire_at,+ run_at=run_at,timezone=timezone,enabled=enabled,parameters=parameters,@@ -409,6 +417,45 @@ class SchedulesClient:)return _response.data+ def cancel(+ self,+ workflow_permanent_id: str,+ workflow_schedule_id: str,+ *,+ request_options: typing.Optional[RequestOptions] = None,+ ) -> WorkflowScheduleResponse:+ """+ Parameters+ ----------+ workflow_permanent_id : str++ workflow_schedule_id : str++ request_options : typing.Optional[RequestOptions]+ Request-specific configuration.++ Returns+ -------+ WorkflowScheduleResponse+ Successful Response++ Examples+ --------+ from skyvern import Skyvern++ client = Skyvern(+ api_key="YOUR_API_KEY",+ )+ client.schedules.cancel(+ workflow_permanent_id="workflow_permanent_id",+ workflow_schedule_id="workflow_schedule_id",+ )+ """+ _response = self._raw_client.cancel(+ workflow_permanent_id, workflow_schedule_id, request_options=request_options+ )+ return _response.data+class AsyncSchedulesClient:def __init__(self, *, client_wrapper: AsyncClientWrapper):@@ -527,6 +574,7 @@ class AsyncSchedulesClient:cron_expression: typing.Optional[str] = OMIT,interval_seconds: typing.Optional[int] = OMIT,first_fire_at: typing.Optional[dt.datetime] = OMIT,+ run_at: typing.Optional[dt.datetime] = OMIT,timezone: str,enabled: typing.Optional[bool] = OMIT,parameters: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,@@ -545,6 +593,8 @@ class AsyncSchedulesClient:first_fire_at : typing.Optional[dt.datetime]+ run_at : typing.Optional[dt.datetime]+timezone : strenabled : typing.Optional[bool]@@ -589,6 +639,7 @@ class AsyncSchedulesClient:cron_expression=cron_expression,interval_seconds=interval_seconds,first_fire_at=first_fire_at,+ run_at=run_at,timezone=timezone,enabled=enabled,parameters=parameters,@@ -653,6 +704,7 @@ class AsyncSchedulesClient:cron_expression: typing.Optional[str] = OMIT,interval_seconds: typing.Optional[int] = OMIT,first_fire_at: typing.Optional[dt.datetime] = OMIT,+ run_at: typing.Optional[dt.datetime] = OMIT,timezone: str,enabled: typing.Optional[bool] = OMIT,parameters: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,@@ -673,6 +725,8 @@ class AsyncSchedulesClient:first_fire_at : typing.Optional[dt.datetime]+ run_at : typing.Optional[dt.datetime]+timezone : strenabled : typing.Optional[bool]@@ -719,6 +773,7 @@ class AsyncSchedulesClient:cron_expression=cron_expression,interval_seconds=interval_seconds,first_fire_at=first_fire_at,+ run_at=run_at,timezone=timezone,enabled=enabled,parameters=parameters,@@ -868,3 +923,51 @@ class AsyncSchedulesClient:workflow_permanent_id, workflow_schedule_id, request_options=request_options)return _response.data+++ async def cancel(+ self,+ workflow_permanent_id: str,+ workflow_schedule_id: str,+ *,+ request_options: typing.Optional[RequestOptions] = None,+ ) -> WorkflowScheduleResponse:+ """+ Parameters+ ----------+ workflow_permanent_id : str++ workflow_schedule_id : str++ request_options : typing.Optional[RequestOptions]+ Request-specific configuration.++ Returns+ -------+ WorkflowScheduleResponse+ Successful Response++ Examples+ --------+ import asyncio++ from skyvern import AsyncSkyvern++ client = AsyncSkyvern(+ api_key="YOUR_API_KEY",+ )+++ async def main() -> None:+ await client.schedules.cancel(+ workflow_permanent_id="workflow_permanent_id",+ workflow_schedule_id="workflow_schedule_id",+ )+++ asyncio.run(main())+ """+ _response = await self._raw_client.cancel(+ workflow_permanent_id, workflow_schedule_id, request_options=request_options+ )+ return _response.datadiff --git a/skyvern/client/schedules/raw_client.py b/skyvern/client/schedules/raw_client.pyindex a2ef2f469..a46fcb111 100644--- a/skyvern/client/schedules/raw_client.py+++ b/skyvern/client/schedules/raw_client.py@@ -146,6 +146,7 @@ class RawSchedulesClient:cron_expression: typing.Optional[str] = OMIT,interval_seconds: typing.Optional[int] = OMIT,first_fire_at: typing.Optional[dt.datetime] = OMIT,+ run_at: typing.Optional[dt.datetime] = OMIT,timezone: str,enabled: typing.Optional[bool] = OMIT,parameters: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,@@ -164,6 +165,8 @@ class RawSchedulesClient:first_fire_at : typing.Optional[dt.datetime]+ run_at : typing.Optional[dt.datetime]+timezone : strenabled : typing.Optional[bool]@@ -189,6 +192,7 @@ class RawSchedulesClient:"cron_expression": cron_expression,"interval_seconds": interval_seconds,"first_fire_at": first_fire_at,+ "run_at": run_at,"timezone": timezone,"enabled": enabled,"parameters": parameters,@@ -288,6 +292,7 @@ class RawSchedulesClient:cron_expression: typing.Optional[str] = OMIT,interval_seconds: typing.Optional[int] = OMIT,first_fire_at: typing.Optional[dt.datetime] = OMIT,+ run_at: typing.Optional[dt.datetime] = OMIT,timezone: str,enabled: typing.Optional[bool] = OMIT,parameters: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,@@ -308,6 +313,8 @@ class RawSchedulesClient:first_fire_at : typing.Optional[dt.datetime]+ run_at : typing.Optional[dt.datetime]+timezone : strenabled : typing.Optional[bool]@@ -333,6 +340,7 @@ class RawSchedulesClient:"cron_expression": cron_expression,"interval_seconds": interval_seconds,"first_fire_at": first_fire_at,+ "run_at": run_at,"timezone": timezone,"enabled": enabled,"parameters": parameters,@@ -530,6 +538,59 @@ class RawSchedulesClient:raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)+ def cancel(+ self,+ workflow_permanent_id: str,+ workflow_schedule_id: str,+ *,+ request_options: typing.Optional[RequestOptions] = None,+ ) -> HttpResponse[WorkflowScheduleResponse]:+ """+ Parameters+ ----------+ workflow_permanent_id : str++ workflow_schedule_id : str++ request_options : typing.Optional[RequestOptions]+ Request-specific configuration.++ Returns+ -------+ HttpResponse[WorkflowScheduleResponse]+ Successful Response+ """+ _response = self._client_wrapper.httpx_client.request(+ f"v1/agents/{jsonable_encoder(workflow_permanent_id)}/schedules/{jsonable_encoder(workflow_schedule_id)}/cancel",+ method="POST",+ request_options=request_options,+ )+ try:+ if 200 <= _response.status_code < 300:+ _data = typing.cast(+ WorkflowScheduleResponse,+ parse_obj_as(+ type_=WorkflowScheduleResponse, # type: ignore+ object_=_response.json(),+ ),+ )+ return HttpResponse(response=_response, data=_data)+ if _response.status_code == 422:+ raise UnprocessableEntityError(+ headers=dict(_response.headers),+ body=typing.cast(+ typing.Optional[typing.Any],+ parse_obj_as(+ type_=typing.Optional[typing.Any], # type: ignore+ object_=_response.json(),+ ),+ ),+ )+ _response_json = _response.json()+ except JSONDecodeError:+ raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)+ raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)+class AsyncRawSchedulesClient:def __init__(self, *, client_wrapper: AsyncClientWrapper):@@ -656,6 +717,7 @@ class AsyncRawSchedulesClient:cron_expression: typing.Optional[str] = OMIT,interval_seconds: typing.Optional[int] = OMIT,first_fire_at: typing.Optional[dt.datetime] = OMIT,+ run_at: typing.Optional[dt.datetime] = OMIT,timezone: str,enabled: typing.Optional[bool] = OMIT,parameters: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,@@ -674,6 +736,8 @@ class AsyncRawSchedulesClient:first_fire_at : typing.Optional[dt.datetime]+ run_at : typing.Optional[dt.datetime]+timezone : strenabled : typing.Optional[bool]@@ -699,6 +763,7 @@ class AsyncRawSchedulesClient:"cron_expression": cron_expression,"interval_seconds": interval_seconds,"first_fire_at": first_fire_at,+ "run_at": run_at,"timezone": timezone,"enabled": enabled,"parameters": parameters,@@ -798,6 +863,7 @@ class AsyncRawSchedulesClient:cron_expression: typing.Optional[str] = OMIT,interval_seconds: typing.Optional[int] = OMIT,first_fire_at: typing.Optional[dt.datetime] = OMIT,+ run_at: typing.Optional[dt.datetime] = OMIT,timezone: str,enabled: typing.Optional[bool] = OMIT,parameters: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,@@ -818,6 +884,8 @@ class AsyncRawSchedulesClient:first_fire_at : typing.Optional[dt.datetime]+ run_at : typing.Optional[dt.datetime]+timezone : strenabled : typing.Optional[bool]@@ -843,6 +911,7 @@ class AsyncRawSchedulesClient:"cron_expression": cron_expression,"interval_seconds": interval_seconds,"first_fire_at": first_fire_at,+ "run_at": run_at,"timezone": timezone,"enabled": enabled,"parameters": parameters,@@ -1039,3 +1108,57 @@ class AsyncRawSchedulesClient:except JSONDecodeError:raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)+++ async def cancel(+ self,+ workflow_permanent_id: str,+ workflow_schedule_id: str,+ *,+ request_options: typing.Optional[RequestOptions] = None,+ ) -> AsyncHttpResponse[WorkflowScheduleResponse]:+ """+ Parameters+ ----------+ workflow_permanent_id : str++ workflow_schedule_id : str++ request_options : typing.Optional[RequestOptions]+ Request-specific configuration.++ Returns+ -------+ AsyncHttpResponse[WorkflowScheduleResponse]+ Successful Response+ """+ _response = await self._client_wrapper.httpx_client.request(+ f"v1/agents/{jsonable_encoder(workflow_permanent_id)}/schedules/{jsonable_encoder(workflow_schedule_id)}/cancel",+ method="POST",+ request_options=request_options,+ )+ try:+ if 200 <= _response.status_code < 300:+ _data = typing.cast(+ WorkflowScheduleResponse,+ parse_obj_as(+ type_=WorkflowScheduleResponse, # type: ignore+ object_=_response.json(),+ ),+ )+ return AsyncHttpResponse(response=_response, data=_data)+ if _response.status_code == 422:+ raise UnprocessableEntityError(+ headers=dict(_response.headers),+ body=typing.cast(+ typing.Optional[typing.Any],+ parse_obj_as(+ type_=typing.Optional[typing.Any], # type: ignore+ object_=_response.json(),+ ),+ ),+ )+ _response_json = _response.json()+ except JSONDecodeError:+ raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)+ raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)diff --git a/skyvern/client/types/__init__.py b/skyvern/client/types/__init__.pyindex ae96e95b0..22ba81536 100644--- a/skyvern/client/types/__init__.py+++ b/skyvern/client/types/__init__.py@@ -397,6 +397,7 @@ if typing.TYPE_CHECKING:from .non_empty_password_credential import NonEmptyPasswordCredentialfrom .one_password_credential_parameter import OnePasswordCredentialParameterfrom .one_password_credential_parameter_yaml import OnePasswordCredentialParameterYaml+ from .one_time_dispatch_status import OneTimeDispatchStatusfrom .organization_schedule_item import OrganizationScheduleItemfrom .organization_schedule_list_response import OrganizationScheduleListResponsefrom .otp_type import OtpType@@ -1188,6 +1189,7 @@ _dynamic_imports: typing.Dict[str, str] = {"NonEmptyPasswordCredential": ".non_empty_password_credential","OnePasswordCredentialParameter": ".one_password_credential_parameter","OnePasswordCredentialParameterYaml": ".one_password_credential_parameter_yaml",+ "OneTimeDispatchStatus": ".one_time_dispatch_status","OrganizationScheduleItem": ".organization_schedule_item","OrganizationScheduleListResponse": ".organization_schedule_list_response","OtpType": ".otp_type",@@ -1969,6 +1971,7 @@ __all__ = ["NonEmptyPasswordCredential","OnePasswordCredentialParameter","OnePasswordCredentialParameterYaml",+ "OneTimeDispatchStatus","OrganizationScheduleItem","OrganizationScheduleListResponse","OtpType",diff --git a/skyvern/client/types/one_time_dispatch_status.py b/skyvern/client/types/one_time_dispatch_status.pynew file mode 100644index 000000000..c7554b3ca--- /dev/null+++ b/skyvern/client/types/one_time_dispatch_status.py@@ -0,0 +1,5 @@+# This file was auto-generated by Fern from our API Definition.++import typing++OneTimeDispatchStatus = typing.Union[typing.Literal["pending", "fired", "canceled", "failed"], typing.Any]diff --git a/skyvern/client/types/organization_schedule_item.py b/skyvern/client/types/organization_schedule_item.pyindex 6217bfff1..4a78f3f4b 100644--- a/skyvern/client/types/organization_schedule_item.py+++ b/skyvern/client/types/organization_schedule_item.py@@ -5,6 +5,7 @@ import typingimport pydanticfrom ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel+from .one_time_dispatch_status import OneTimeDispatchStatusclass OrganizationScheduleItem(UniversalBaseModel):@@ -24,6 +25,9 @@ class OrganizationScheduleItem(UniversalBaseModel):cron_expression: typing.Optional[str] = Noneinterval_seconds: typing.Optional[int] = Nonefirst_fire_at: typing.Optional[dt.datetime] = None+ run_at: typing.Optional[dt.datetime] = None+ dispatch_status: typing.Optional[OneTimeDispatchStatus] = None+ workflow_run_id: typing.Optional[str] = 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 64155aa76..ad8699fc2 100644--- a/skyvern/client/types/workflow_schedule.py+++ b/skyvern/client/types/workflow_schedule.py@@ -5,6 +5,7 @@ import typingimport pydanticfrom ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel+from .one_time_dispatch_status import OneTimeDispatchStatusclass WorkflowSchedule(UniversalBaseModel):@@ -14,6 +15,9 @@ class WorkflowSchedule(UniversalBaseModel):cron_expression: typing.Optional[str] = Noneinterval_seconds: typing.Optional[int] = Nonefirst_fire_at: typing.Optional[dt.datetime] = None+ run_at: typing.Optional[dt.datetime] = None+ dispatch_status: typing.Optional[OneTimeDispatchStatus] = None+ workflow_run_id: typing.Optional[str] = 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 bf7f095bf..49b5ed3e2 100644--- a/skyvern/client/types/workflow_schedule_upsert_request.py+++ b/skyvern/client/types/workflow_schedule_upsert_request.py@@ -11,6 +11,7 @@ class WorkflowScheduleUpsertRequest(UniversalBaseModel):cron_expression: typing.Optional[str] = Noneinterval_seconds: typing.Optional[int] = Nonefirst_fire_at: typing.Optional[dt.datetime] = None+ run_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 f0de30bfa..dab68dcb2 100644--- a/skyvern/forge/agent_functions.py+++ b/skyvern/forge/agent_functions.py@@ -1911,8 +1911,9 @@ class AgentFunction:max_elapsed_time_minutes: int | None = None,interval_seconds: int | None = None,first_fire_at: datetime | None = None,+ run_at: datetime | None = None,) -> None:- """Upsert a recurring schedule with the execution backend (e.g. Temporal).+ """Upsert a cron, interval or one-time schedule with the execution backend (e.g. Temporal).OSS base is a no-op because the local scheduler scans the database.Cloud overrides this to register the schedule with Temporal.diff --git a/skyvern/forge/sdk/copilot/narration.py b/skyvern/forge/sdk/copilot/narration.pyindex 424baa012..b366d8e18 100644--- a/skyvern/forge/sdk/copilot/narration.py+++ b/skyvern/forge/sdk/copilot/narration.py@@ -132,6 +132,7 @@ _TOOL_ACTIVITY_DISPLAY_LABELS = {"update_workflow_schedule": "Updating a schedule","enable_workflow_schedule": "Resuming a schedule","disable_workflow_schedule": "Pausing a schedule",+ "cancel_workflow_schedule": "Canceling a schedule","delete_workflow_schedule": "Deleting a schedule","fill_credential_field": "Entering saved credentials","solve_page_challenge": "Solving the page's verification challenge",diff --git a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py b/skyvern/forge/sdk/copilot/tools/mcp_hooks.pyindex 25992f1f2..9b3c4e6a7 100644--- a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py+++ b/skyvern/forge/sdk/copilot/tools/mcp_hooks.py@@ -2028,6 +2028,7 @@ def get_skyvern_mcp_alias_map() -> dict[str, str]:"update_workflow_schedule": "skyvern_schedule_update","enable_workflow_schedule": "skyvern_schedule_enable","disable_workflow_schedule": "skyvern_schedule_disable",+ "cancel_workflow_schedule": "skyvern_schedule_cancel","delete_workflow_schedule": "skyvern_schedule_delete",}@@ -2499,17 +2500,19 @@ 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. 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.",+ "gave one. Ask before duplicating a listed schedule. Cadence is a cron expression, interval_seconds, "+ "which runs a fixed elapsed interval counted from first_fire_at (cron cannot express an elapsed interval "+ "such as 'every 36 hours'), or run_at to run once at the user's instant, given as ISO 8601 with the "+ "user's UTC offset. In your reply, give the saved wfs_ ID, timezone, enabled state and next run from the "+ "result, and for a one-time schedule its run_at and dispatch_status.",pre_hook=_create_workflow_schedule_pre_hook,),"update_workflow_schedule": _workflow_schedule_overlay("Change a schedule by wfs_ ID, passing only the fields that change; parameters, name and paused ""state are kept. Send name or clear_name only when the user asks to rename it, even if the name ""mentions the old time. Parameter values read back as ***; send *** for a key to keep its stored "- "value. Ask which one when several could match.",+ "value. A one-time schedule keeps run_at as its cadence and can change only until it fires. Ask which "+ "one when several could match.",hide_params=frozenset({"exact"}),pre_hook=_schedule_parameters_credential_pre_hook,),@@ -2520,6 +2523,10 @@ def _build_skyvern_mcp_overlays("disable_workflow_schedule": _workflow_schedule_overlay("Pause a schedule by wfs_ ID without deleting it. Ask which one when several could match."),+ "cancel_workflow_schedule": _workflow_schedule_overlay(+ "Cancel a one-time schedule by wfs_ ID before it fires; it stays listed with dispatch_status canceled. "+ "Pause or delete a recurring schedule instead. Ask which one when several could match."+ ),"delete_workflow_schedule": _workflow_schedule_overlay("Delete a schedule by wfs_ ID; irreversible. Pass force=true only when the user clearly asked to ""remove that schedule, then list schedules to confirm it is gone."diff --git a/skyvern/forge/sdk/db/models.py b/skyvern/forge/sdk/db/models.pyindex dccceb273..3ec1c8034 100644--- a/skyvern/forge/sdk/db/models.py+++ b/skyvern/forge/sdk/db/models.py@@ -786,8 +786,10 @@ class WorkflowScheduleModel(Base):),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)",+ "(CASE WHEN cron_expression IS NULL THEN 0 ELSE 1 END + CASE WHEN interval_seconds IS NULL THEN 0 ELSE 1 END "+ "+ CASE WHEN run_at IS NULL THEN 0 ELSE 1 END) = 1 "+ "AND (interval_seconds IS NULL) = (first_fire_at IS NULL) "+ "AND (run_at IS NULL) = (dispatch_status IS NULL)",name="ck_workflow_schedules_one_cadence",),)@@ -798,6 +800,9 @@ class WorkflowScheduleModel(Base):cron_expression = Column(String, nullable=True)interval_seconds = Column(Integer, nullable=True)first_fire_at = Column(DateTime, nullable=True)+ run_at = Column(DateTime, nullable=True)+ dispatch_status = Column(String, nullable=True)+ workflow_run_id = Column(String, 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 d1457f8b1..cd304ac09 100644--- a/skyvern/forge/sdk/db/repositories/schedules.py+++ b/skyvern/forge/sdk/db/repositories/schedules.py@@ -7,15 +7,20 @@ from datetime import UTC, datetimefrom typing import TYPE_CHECKING, Any, Callableimport structlog-from sqlalchemy import exists, func, or_, select, text, update+from sqlalchemy import and_, exists, func, or_, select, text, updatefrom sqlalchemy.exc import SQLAlchemyErrorfrom skyvern.forge.sdk.db._error_handling import db_operation, register_passthrough_exceptionfrom skyvern.forge.sdk.db.base_repository import BaseRepository+from skyvern.forge.sdk.db.datetime_utils import naive_utc_nowfrom 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_schedule-from skyvern.forge.sdk.schemas.workflow_schedules import OrganizationScheduleItem, WorkflowSchedule+from skyvern.forge.sdk.schemas.workflow_schedules import (+ OneTimeDispatchStatus,+ OrganizationScheduleItem,+ WorkflowSchedule,+)from skyvern.forge.sdk.workflow.schedules import as_utc, compute_next_runif TYPE_CHECKING:@@ -32,6 +37,16 @@ def _naive_utc(value: datetime | None) -> datetime | None:return as_utc(value).replace(tzinfo=None) if value is not None else None+def _initial_dispatch_status(run_at: datetime | None) -> OneTimeDispatchStatus | None:+ return OneTimeDispatchStatus.pending if run_at is not None else None+++_NOT_TERMINAL_ONE_TIME = or_(+ WorkflowScheduleModel.run_at.is_(None),+ WorkflowScheduleModel.dispatch_status == OneTimeDispatchStatus.pending,+)++class SchedulesRepository(BaseRepository):"""Database operations for workflow schedules."""@@ -59,6 +74,7 @@ class SchedulesRepository(BaseRepository):description: str | None = None,interval_seconds: int | None = None,first_fire_at: datetime | None = None,+ run_at: datetime | None = None,) -> WorkflowSchedule:async with self.Session() as session:workflow_schedule = WorkflowScheduleModel(@@ -67,6 +83,8 @@ class SchedulesRepository(BaseRepository):cron_expression=cron_expression,interval_seconds=interval_seconds,first_fire_at=_naive_utc(first_fire_at),+ run_at=_naive_utc(run_at),+ dispatch_status=_initial_dispatch_status(run_at),timezone=timezone,enabled=enabled,parameters=parameters,@@ -93,6 +111,7 @@ class SchedulesRepository(BaseRepository):description: str | None = None,interval_seconds: int | None = None,first_fire_at: datetime | None = None,+ run_at: datetime | None = None,) -> WorkflowSchedule:"""Create a schedule atomically with org-wide limit enforcement.@@ -121,6 +140,7 @@ class SchedulesRepository(BaseRepository):description,interval_seconds,first_fire_at,+ run_at,use_advisory_lock=False,)return await self._create_schedule_with_limit_inner(@@ -135,6 +155,7 @@ class SchedulesRepository(BaseRepository):description,interval_seconds,first_fire_at,+ run_at,use_advisory_lock=True,)@@ -153,6 +174,7 @@ class SchedulesRepository(BaseRepository):description: str | None,interval_seconds: int | None,first_fire_at: datetime | None,+ run_at: datetime | None,*,use_advisory_lock: bool,) -> WorkflowSchedule:@@ -169,6 +191,7 @@ class SchedulesRepository(BaseRepository):select(func.count()).where(WorkflowScheduleModel.organization_id == organization_id,WorkflowScheduleModel.deleted_at.is_(None),+ _NOT_TERMINAL_ONE_TIME,))).scalar_one()@@ -186,6 +209,8 @@ class SchedulesRepository(BaseRepository):cron_expression=cron_expression,interval_seconds=interval_seconds,first_fire_at=_naive_utc(first_fire_at),+ run_at=_naive_utc(run_at),+ dispatch_status=_initial_dispatch_status(run_at),timezone=timezone,enabled=enabled,parameters=parameters,@@ -238,15 +263,20 @@ class SchedulesRepository(BaseRepository):description: str | None | _Unset = _UNSET,interval_seconds: int | None | _Unset = _UNSET,first_fire_at: datetime | None | _Unset = _UNSET,+ run_at: datetime | None | _Unset = _UNSET,) -> WorkflowSchedule | None:+ """Returns None when the row is gone or, for a one-time schedule, is no longer pending."""async with self.Session() as session:workflow_schedule = (await session.scalars(- select(WorkflowScheduleModel).filter_by(+ select(WorkflowScheduleModel)+ .filter_by(workflow_schedule_id=workflow_schedule_id,organization_id=organization_id,deleted_at=None,)+ .where(_NOT_TERMINAL_ONE_TIME)+ .with_for_update())).first()@@ -258,6 +288,8 @@ class SchedulesRepository(BaseRepository):workflow_schedule.interval_seconds = interval_secondsif first_fire_at is not _UNSET:workflow_schedule.first_fire_at = _naive_utc(first_fire_at)+ if run_at is not _UNSET:+ workflow_schedule.run_at = _naive_utc(run_at)workflow_schedule.timezone = timezoneif enabled is not _UNSET:workflow_schedule.enabled = enabled@@ -318,9 +350,15 @@ class SchedulesRepository(BaseRepository):) -> list[WorkflowSchedule]:"""Fetch all enabled, non-deleted schedules, optionally filtered by org."""async with self.Session() as session:+ # A fired one-time row with no run crashed between its claim and the run insert, so it is re-admitted.+ claimed_without_run = and_(+ WorkflowScheduleModel.dispatch_status == OneTimeDispatchStatus.fired,+ ~exists().where(WorkflowRunModel.workflow_run_id == WorkflowScheduleModel.workflow_run_id),+ )stmt = select(WorkflowScheduleModel).where(WorkflowScheduleModel.enabled.is_(True),WorkflowScheduleModel.deleted_at.is_(None),+ or_(_NOT_TERMINAL_ONE_TIME, claimed_without_run),)if organization_id:stmt = stmt.where(WorkflowScheduleModel.organization_id == organization_id)@@ -339,7 +377,9 @@ class SchedulesRepository(BaseRepository):preserving their paused state."""async with self.Session() as session:- stmt = select(WorkflowScheduleModel).where(WorkflowScheduleModel.deleted_at.is_(None))+ stmt = select(WorkflowScheduleModel).where(+ WorkflowScheduleModel.deleted_at.is_(None), _NOT_TERMINAL_ONE_TIME+ )if organization_id:stmt = stmt.where(WorkflowScheduleModel.organization_id == organization_id)rows = (await session.scalars(stmt)).all()@@ -365,6 +405,148 @@ class SchedulesRepository(BaseRepository):).scalar()return bool(row)+ @db_operation("claim_one_time_dispatch")+ async def claim_one_time_dispatch(+ self,+ workflow_schedule_id: str,+ organization_id: str,+ workflow_run_id: str,+ fire_at: datetime,+ ) -> WorkflowSchedule | None:+ """Commit the pending row whose run_at equals this fire to one run id; a retry of that id re-enters.+ None means the row was edited, canceled, deleted or claimed by another run, so the fire must not start one."""+ async with self.Session() as session:+ claimed = (+ await session.scalars(+ update(WorkflowScheduleModel)+ .where(+ WorkflowScheduleModel.workflow_schedule_id == workflow_schedule_id,+ WorkflowScheduleModel.organization_id == organization_id,+ WorkflowScheduleModel.deleted_at.is_(None),+ WorkflowScheduleModel.dispatch_status == OneTimeDispatchStatus.pending,+ WorkflowScheduleModel.run_at == _naive_utc(fire_at),+ )+ .values(+ dispatch_status=OneTimeDispatchStatus.fired,+ workflow_run_id=workflow_run_id,+ modified_at=naive_utc_now(),+ )+ .returning(WorkflowScheduleModel)+ )+ ).first()+ if claimed is not None:+ result = convert_to_workflow_schedule(claimed, self.debug_enabled)+ await session.commit()+ return result+ existing = (+ await session.scalars(+ select(WorkflowScheduleModel).filter_by(+ workflow_schedule_id=workflow_schedule_id,+ organization_id=organization_id,+ workflow_run_id=workflow_run_id,+ deleted_at=None,+ )+ )+ ).first()+ if existing is None or existing.dispatch_status not in (+ OneTimeDispatchStatus.fired,+ OneTimeDispatchStatus.failed,+ ):+ return None+ return convert_to_workflow_schedule(existing, self.debug_enabled)++ @db_operation("finish_one_time_dispatch")+ async def finish_one_time_dispatch(+ self,+ workflow_schedule_id: str,+ organization_id: str,+ workflow_run_id: str,+ dispatch_status: OneTimeDispatchStatus,+ ) -> None:+ async with self.Session() as session:+ await session.execute(+ update(WorkflowScheduleModel)+ .where(+ WorkflowScheduleModel.workflow_schedule_id == workflow_schedule_id,+ WorkflowScheduleModel.organization_id == organization_id,+ WorkflowScheduleModel.workflow_run_id == workflow_run_id,+ WorkflowScheduleModel.dispatch_status.in_(+ [OneTimeDispatchStatus.fired, OneTimeDispatchStatus.failed]+ ),+ )+ .values(dispatch_status=dispatch_status, modified_at=naive_utc_now())+ )+ await session.commit()++ @db_operation("list_overdue_pending_one_time_schedules")+ async def list_overdue_pending_one_time_schedules(+ self, due_before: datetime, limit: int = 100+ ) -> list[WorkflowSchedule]:+ async with self.Session() as session:+ rows = (+ await session.scalars(+ select(WorkflowScheduleModel)+ .where(+ WorkflowScheduleModel.deleted_at.is_(None),+ WorkflowScheduleModel.dispatch_status == OneTimeDispatchStatus.pending,+ WorkflowScheduleModel.run_at <= _naive_utc(due_before),+ )+ .order_by(WorkflowScheduleModel.run_at)+ .limit(limit)+ )+ ).all()+ return [convert_to_workflow_schedule(row, self.debug_enabled) for row in rows]++ @db_operation("fail_pending_one_time_dispatch")+ async def fail_pending_one_time_dispatch(+ self,+ workflow_schedule_id: str,+ organization_id: str,+ run_at: datetime,+ ) -> bool:+ """False when the row was edited, canceled, deleted or claimed since it was read."""+ async with self.Session() as session:+ result = await session.execute(+ update(WorkflowScheduleModel)+ .where(+ WorkflowScheduleModel.workflow_schedule_id == workflow_schedule_id,+ WorkflowScheduleModel.organization_id == organization_id,+ WorkflowScheduleModel.deleted_at.is_(None),+ WorkflowScheduleModel.dispatch_status == OneTimeDispatchStatus.pending,+ WorkflowScheduleModel.run_at == _naive_utc(run_at),+ )+ .values(dispatch_status=OneTimeDispatchStatus.failed, modified_at=naive_utc_now())+ )+ await session.commit()+ return result.rowcount == 1++ @db_operation("cancel_one_time_schedule")+ async def cancel_one_time_schedule(+ self,+ workflow_schedule_id: str,+ organization_id: str,+ ) -> WorkflowSchedule | None:+ """Returns None when the row is gone or no longer pending."""+ async with self.Session() as session:+ canceled = (+ await session.scalars(+ update(WorkflowScheduleModel)+ .where(+ WorkflowScheduleModel.workflow_schedule_id == workflow_schedule_id,+ WorkflowScheduleModel.organization_id == organization_id,+ WorkflowScheduleModel.deleted_at.is_(None),+ WorkflowScheduleModel.dispatch_status == OneTimeDispatchStatus.pending,+ )+ .values(dispatch_status=OneTimeDispatchStatus.canceled, modified_at=naive_utc_now())+ .returning(WorkflowScheduleModel)+ )+ ).first()+ if canceled is None:+ return None+ result = convert_to_workflow_schedule(canceled, self.debug_enabled)+ await session.commit()+ return result+@db_operation("update_workflow_schedule_enabled")async def update_workflow_schedule_enabled(self,@@ -495,7 +677,7 @@ class SchedulesRepository(BaseRepository):)if enabled_filter is not None:- base_filter = base_filter.where(WorkflowScheduleModel.enabled == enabled_filter)+ base_filter = base_filter.where(WorkflowScheduleModel.enabled == enabled_filter, _NOT_TERMINAL_ONE_TIME)if search:base_filter = base_filter.where(@@ -530,6 +712,9 @@ class SchedulesRepository(BaseRepository):schedule_model.cron_expression,schedule_model.interval_seconds,schedule_model.first_fire_at,+ schedule_model.run_at,+ schedule_model.dispatch_status,+ schedule_model.workflow_run_id,schedule_model.timezone,schedule_model.enabled,schedule_model.parameters,@@ -550,6 +735,9 @@ class SchedulesRepository(BaseRepository):cron_expr,interval_seconds,first_fire_at,+ run_at,+ dispatch_status,+ workflow_run_id,tz,enabled,params,@@ -559,7 +747,9 @@ class SchedulesRepository(BaseRepository):modified,) in raw_schedules:next_run = None- if enabled:+ if run_at is not None:+ next_run = as_utc(run_at) if dispatch_status == OneTimeDispatchStatus.pending else None+ elif enabled:try:next_run = compute_next_run(cron_expr, tz, interval_seconds=interval_seconds, first_fire_at=first_fire_at@@ -580,6 +770,9 @@ class SchedulesRepository(BaseRepository):cron_expression=cron_expr,interval_seconds=interval_seconds,first_fire_at=first_fire_at,+ run_at=run_at,+ dispatch_status=dispatch_status,+ workflow_run_id=workflow_run_id,timezone=tz,enabled=enabled,parameters=params,diff --git a/skyvern/forge/sdk/routes/workflow_schedules.py b/skyvern/forge/sdk/routes/workflow_schedules.pyindex 9a7085119..0df9e4120 100644--- a/skyvern/forge/sdk/routes/workflow_schedules.py+++ b/skyvern/forge/sdk/routes/workflow_schedules.py@@ -15,6 +15,7 @@ from skyvern.forge.sdk.routes.routers import base_router, legacy_base_routerfrom skyvern.forge.sdk.schemas.organizations import Organizationfrom skyvern.forge.sdk.schemas.workflow_schedules import (DeleteScheduleResponse,+ OneTimeDispatchStatus,OrganizationScheduleListResponse,WorkflowSchedule,WorkflowScheduleListResponse,@@ -82,6 +83,8 @@ def _next_runs(schedule: WorkflowSchedule,count: int = NEXT_RUNS_COUNT,) -> list[datetime]:+ if schedule.run_at is not None:+ return [schedule.run_at] if schedule.dispatch_status == OneTimeDispatchStatus.pending else []return calculate_next_runs(schedule.cron_expression,schedule.timezone,@@ -120,18 +123,37 @@ def _resolve_first_fire_at(body: WorkflowScheduleUpsertRequest, existing: Workflreturn existing.first_fire_atif 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:+ return _require_future(body.first_fire_at, "first_fire_at")+++def _require_future(value: datetime, field: str) -> datetime:+ if value < 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(),+ "loc": ("body", field),+ "msg": f"{field} must be at least 60 seconds in the future",+ "input": value.isoformat(),}])- return body.first_fire_at+ return value+++def _resolve_run_at(body: WorkflowScheduleUpsertRequest, existing: WorkflowSchedule | None) -> datetime | None:+ if body.run_at is None:+ return None+ if existing is not None and body.run_at == existing.run_at:+ return existing.run_at+ return _require_future(body.run_at, "run_at")+++def _one_time_conflict(workflow_schedule_id: str) -> HTTPException:+ return HTTPException(+ status_code=status.HTTP_409_CONFLICT,+ detail=f"Schedule {workflow_schedule_id} already fired or was canceled, so it can no longer change",+ )async def _set_schedule_enabled(@@ -152,6 +174,11 @@ async def _set_schedule_enabled(status_code=404,detail=f"Schedule {workflow_schedule_id} not found",)+ if existing.is_one_time:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail="A one-time schedule cannot be paused or resumed; cancel it, or update run_at to move it",+ )backend_schedule_id = existing.backend_schedule_id or app.AGENT_FUNCTION.build_workflow_schedule_id(existing.workflow_schedule_id@@ -273,9 +300,9 @@ async def list_organization_schedules(operation_id="schedules_create",summary="Create a schedule for an agent",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."+ "Create a cron, fixed-interval or one-time 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. A "+ "one-time schedule runs once at run_at. Returns the stored schedule and its next upcoming run times."),)async def create_workflow_schedule(@@ -286,6 +313,7 @@ async def create_workflow_schedule() -> WorkflowScheduleResponse:_validate_request(body)first_fire_at = _resolve_first_fire_at(body, existing=None)+ run_at = _resolve_run_at(body, existing=None)workflow = await _ensure_workflow_exists(workflow_permanent_id, organization.organization_id)await app.WORKFLOW_SERVICE.validate_schedule_parameters(workflow=workflow,@@ -312,6 +340,7 @@ async def create_workflow_schedule(description=body.description,interval_seconds=body.interval_seconds,first_fire_at=first_fire_at,+ run_at=run_at,)except ScheduleLimitExceededError as e:LOG.info(@@ -380,6 +409,7 @@ async def create_workflow_schedule(max_elapsed_time_minutes=workflow.max_elapsed_time_minutes,interval_seconds=body.interval_seconds,first_fire_at=first_fire_at,+ run_at=run_at,)except Exception as e:LOG.exception(@@ -410,6 +440,7 @@ async def create_workflow_schedule(workflow_schedule_id=schedule.workflow_schedule_id,cron_expression=body.cron_expression,interval_seconds=body.interval_seconds,+ run_at=run_at,enabled=enabled,)return WorkflowScheduleResponse(schedule=schedule, next_runs=_next_runs(schedule))@@ -476,7 +507,8 @@ async def get_workflow_schedule(operation_id="schedules_update",summary="Update an agent schedule",description=(- "Replace a schedule's cron expression or interval, timezone, run parameters, and enabled state. "+ "Replace a schedule's cron expression, interval or one-time run_at, timezone, run parameters, and enabled "+ "state. A one-time schedule stays one-time and can change only until it fires; afterwards this returns 409. ""Returns the updated schedule and its next upcoming run times."),)@@ -498,8 +530,17 @@ async def update_workflow_schedule(detail=f"Schedule {workflow_schedule_id} not found",)+ if existing.is_one_time != (body.run_at is not None):+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail="A schedule cannot switch between one-time and recurring; create a new schedule instead",+ )+ if existing.is_one_time and existing.dispatch_status != OneTimeDispatchStatus.pending:+ raise _one_time_conflict(workflow_schedule_id)+_validate_request(body)first_fire_at = _resolve_first_fire_at(body, existing=existing)+ run_at = _resolve_run_at(body, existing=existing)await app.WORKFLOW_SERVICE.validate_schedule_parameters(workflow=workflow,organization=organization,@@ -526,6 +567,7 @@ async def update_workflow_schedule(old_cron = existing.cron_expressionold_interval_seconds = existing.interval_secondsold_first_fire_at = existing.first_fire_at+ old_run_at = existing.run_atold_timezone = existing.timezoneold_enabled = existing.enabledold_parameters = existing.parameters@@ -555,8 +597,11 @@ async def update_workflow_schedule(description=body.description,interval_seconds=body.interval_seconds,first_fire_at=first_fire_at,+ run_at=run_at,)if not schedule:+ if existing.is_one_time:+ raise _one_time_conflict(workflow_schedule_id)raise HTTPException(status_code=404,detail=f"Schedule {workflow_schedule_id} not found",@@ -579,6 +624,7 @@ async def update_workflow_schedule(max_elapsed_time_minutes=workflow.max_elapsed_time_minutes,interval_seconds=body.interval_seconds,first_fire_at=first_fire_at,+ run_at=run_at,)except Exception as e:LOG.exception(@@ -600,6 +646,7 @@ async def update_workflow_schedule(description=old_description,interval_seconds=old_interval_seconds,first_fire_at=old_first_fire_at,+ run_at=old_run_at,)except Exception as rollback_err:LOG.exception(@@ -618,11 +665,70 @@ async def update_workflow_schedule(workflow_schedule_id=workflow_schedule_id,cron_expression=body.cron_expression,interval_seconds=body.interval_seconds,+ run_at=run_at,enabled=enabled,)return WorkflowScheduleResponse(schedule=schedule, next_runs=_next_runs(schedule))+@legacy_base_router.post(+ "/workflows/{workflow_permanent_id}/schedules/{workflow_schedule_id}/cancel",+ include_in_schema=False,+)+@base_router.post(+ "/workflows/{workflow_permanent_id}/schedules/{workflow_schedule_id}/cancel",+ response_model=WorkflowScheduleResponse,+ tags=["Schedules"],+ operation_id="schedules_cancel",+ summary="Cancel a one-time agent schedule",+ description=(+ "Cancel a one-time schedule that has not fired yet. The schedule stays readable with dispatch_status "+ "canceled. Returns 409 once it has fired or was already canceled, and 422 for a recurring schedule."+ ),+)+async def cancel_workflow_schedule(+ workflow_permanent_id: str,+ workflow_schedule_id: str,+ organization: Organization = Depends(org_auth_service.get_current_org),+ _: None = Depends(_require_schedules_enabled),+) -> WorkflowScheduleResponse:+ await _ensure_workflow_exists(workflow_permanent_id, organization.organization_id)+ existing = await _get_schedule_or_404(workflow_schedule_id, organization.organization_id)+ if existing.workflow_permanent_id != workflow_permanent_id:+ raise HTTPException(status_code=404, detail=f"Schedule {workflow_schedule_id} not found")+ if not existing.is_one_time:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail="Only a one-time schedule can be canceled; disable or delete a recurring schedule instead",+ )++ schedule = await app.DATABASE.schedules.cancel_one_time_schedule(+ workflow_schedule_id=workflow_schedule_id,+ organization_id=organization.organization_id,+ )+ if schedule is None:+ raise _one_time_conflict(workflow_schedule_id)++ # The pending-only claim already refuses a canceled row, so a leftover backend schedule can never start a run.+ if existing.backend_schedule_id:+ try:+ await app.AGENT_FUNCTION.delete_workflow_schedule(existing.backend_schedule_id)+ except Exception:+ LOG.exception(+ "Failed to delete canceled one-time schedule on execution backend",+ workflow_schedule_id=workflow_schedule_id,+ backend_schedule_id=existing.backend_schedule_id,+ )++ LOG.info(+ "One-time workflow schedule canceled",+ organization_id=organization.organization_id,+ workflow_permanent_id=workflow_permanent_id,+ workflow_schedule_id=workflow_schedule_id,+ )+ return WorkflowScheduleResponse(schedule=schedule, next_runs=[])++@legacy_base_router.post("/workflows/{workflow_permanent_id}/schedules/{workflow_schedule_id}/enable",include_in_schema=False,diff --git a/skyvern/forge/sdk/schemas/workflow_schedules.py b/skyvern/forge/sdk/schemas/workflow_schedules.pyindex 90003966f..2da040e9d 100644--- a/skyvern/forge/sdk/schemas/workflow_schedules.py+++ b/skyvern/forge/sdk/schemas/workflow_schedules.py@@ -1,10 +1,12 @@from datetime import datetime+from enum import StrEnumfrom typing import Any, Self-from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, field_validator, model_validator+from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, ValidationInfo, field_validator, model_validatorfrom skyvern.forge.sdk.workflow.schedules import (LATEST_FIRST_FIRE_AT,+ LATEST_RUN_AT,MAX_INTERVAL_SECONDS,MIN_SCHEDULE_INTERVAL_SECONDS,as_utc,@@ -15,6 +17,13 @@ def _anchor_as_utc(value: datetime | None) -> datetime | None:return as_utc(value) if value is not None else None+class OneTimeDispatchStatus(StrEnum):+ pending = "pending"+ fired = "fired"+ canceled = "canceled"+ failed = "failed"++class WorkflowSchedule(BaseModel):# populate_by_name + serialize_by_alias keep the wire format stable at# `temporal_schedule_id` (the already-deployed name external clients see)@@ -31,6 +40,9 @@ class WorkflowSchedule(BaseModel):cron_expression: str | None = Noneinterval_seconds: int | None = Nonefirst_fire_at: datetime | None = None+ run_at: datetime | None = None+ dispatch_status: OneTimeDispatchStatus | None = None+ workflow_run_id: str | None = Nonetimezone: strenabled: boolparameters: dict[str, Any] | None = None@@ -41,7 +53,11 @@ class WorkflowSchedule(BaseModel):modified_at: datetimedeleted_at: datetime | None = None- _first_fire_at_utc = field_validator("first_fire_at")(_anchor_as_utc)+ _instants_as_utc = field_validator("first_fire_at", "run_at")(_anchor_as_utc)++ @property+ def is_one_time(self) -> bool:+ return self.run_at is not Noneclass OrganizationScheduleItem(BaseModel):@@ -60,6 +76,9 @@ class OrganizationScheduleItem(BaseModel):cron_expression: str | None = Noneinterval_seconds: int | None = Nonefirst_fire_at: datetime | None = None+ run_at: datetime | None = None+ dispatch_status: OneTimeDispatchStatus | None = None+ workflow_run_id: str | None = Nonetimezone: strenabled: boolparameters: dict[str, Any] | None = None@@ -69,7 +88,7 @@ class OrganizationScheduleItem(BaseModel):created_at: datetimemodified_at: datetime- _first_fire_at_utc = field_validator("first_fire_at")(_anchor_as_utc)+ _instants_as_utc = field_validator("first_fire_at", "run_at")(_anchor_as_utc)class WorkflowScheduleCreateRequest(BaseModel):@@ -125,6 +144,14 @@ class WorkflowScheduleUpsertRequest(BaseModel):"Must be in the future when changed. Defaults to one interval after creation."),)+ run_at: AwareDatetime | None = Field(+ default=None,+ description=(+ "Run the agent once at this instant, ISO 8601 with a UTC offset, at least 60 seconds in the future. "+ "Mutually exclusive with cron_expression and interval_seconds; the schedule can be edited or canceled "+ "only until it fires."+ ),+ )timezone: str# Default True is the create default (new schedules start enabled). On# update the route inspects model_fields_set, so an omitted `enabled`@@ -135,23 +162,27 @@ class WorkflowScheduleUpsertRequest(BaseModel):name: str | None = Nonedescription: str | None = None- @field_validator("first_fire_at")+ @field_validator("first_fire_at", "run_at")@classmethod- def _first_fire_at_in_range(cls, value: datetime | None) -> datetime | None:+ def _instant_in_range(cls, value: datetime | None, info: ValidationInfo) -> datetime | None:if value is None:return Nonetry: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()}")+ latest = LATEST_RUN_AT if info.field_name == "run_at" else LATEST_FIRST_FIRE_AT+ if anchor is None or anchor > latest:+ raise ValueError(f"{info.field_name} must be no later than {latest.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")+ cadences = [self.cron_expression, self.interval_seconds, self.run_at]+ if sum(cadence is not None for cadence in cadences) != 1:+ raise ValueError("Set exactly one of cron_expression, interval_seconds or run_at")if self.first_fire_at is not None and self.interval_seconds is None:raise ValueError("first_fire_at requires interval_seconds")+ if self.run_at is not None and self.enabled is False:+ raise ValueError("A one-time schedule cannot be disabled; cancel it or change run_at instead")return selfdiff --git a/skyvern/forge/sdk/workflow/schedules.py b/skyvern/forge/sdk/workflow/schedules.pyindex 09fc3cc5f..04042a62f 100644--- a/skyvern/forge/sdk/workflow/schedules.py+++ b/skyvern/forge/sdk/workflow/schedules.py@@ -52,6 +52,8 @@ NEXT_RUNS_COUNT = 5LATEST_FIRST_FIRE_AT = (datetime.max - timedelta(seconds=NEXT_RUNS_COUNT * MAX_INTERVAL_SECONDS)).replace(microsecond=0, tzinfo=UTC)+# Temporal calendar specs reject a year outside 2000-2100, and a one-time schedule is a calendar spec there.+LATEST_RUN_AT = datetime(2100, 12, 31, 23, 59, 59, tzinfo=UTC)def as_utc(value: datetime) -> datetime:diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.pyindex d9cb4a7de..a1d29f4df 100644--- a/skyvern/forge/sdk/workflow/service.py+++ b/skyvern/forge/sdk/workflow/service.py@@ -136,6 +136,7 @@ from skyvern.forge.sdk.schemas.persistent_browser_sessions import ()from skyvern.forge.sdk.schemas.tasks import Task, TaskStatusfrom skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunBlock, WorkflowRunTimeline, WorkflowRunTimelineType+from skyvern.forge.sdk.schemas.workflow_schedules import OneTimeDispatchStatusfrom skyvern.forge.sdk.streaming.registries import mark_stream_closingfrom skyvern.forge.sdk.submission import shadow as submission_shadowfrom skyvern.forge.sdk.trace import traced@@ -16457,6 +16458,8 @@ class WorkflowService:for schedule in schedules:if not schedule.backend_schedule_id:continue+ if schedule.run_at is not None and schedule.dispatch_status != OneTimeDispatchStatus.pending:+ continuetry:await app.AGENT_FUNCTION.upsert_workflow_schedule(backend_schedule_id=schedule.backend_schedule_id,@@ -16470,6 +16473,7 @@ class WorkflowService:max_elapsed_time_minutes=max_elapsed_time_minutes,interval_seconds=schedule.interval_seconds,first_fire_at=schedule.first_fire_at,+ run_at=schedule.run_at,)except Exception:LOG.exception(diff --git a/skyvern/services/workflow_schedule_service.py b/skyvern/services/workflow_schedule_service.pyindex ea24e93e2..93122255f 100644--- a/skyvern/services/workflow_schedule_service.py+++ b/skyvern/services/workflow_schedule_service.py@@ -9,9 +9,10 @@ from __future__ import annotationsimport asyncioimport hashlib-from collections.abc import Callable+from collections.abc import AsyncIterator, Callable+from contextlib import asynccontextmanagerfrom dataclasses import dataclass-from datetime import datetime+from datetime import UTC, datetimeimport structlogfrom sqlalchemy.exc import IntegrityError, SQLAlchemyError@@ -20,7 +21,7 @@ from skyvern.config import settingsfrom skyvern.forge import appfrom skyvern.forge.sdk.api.llm.custom_llm_registry import prepare_org_llm_runtimefrom skyvern.forge.sdk.db.enums import WorkflowRunTriggerType-from skyvern.forge.sdk.schemas.workflow_schedules import WorkflowSchedule+from skyvern.forge.sdk.schemas.workflow_schedules import OneTimeDispatchStatus, WorkflowSchedulefrom skyvern.forge.sdk.workflow.models.workflow import WorkflowRequestBodyfrom skyvern.forge.sdk.workflow.retry_policy import fail_run_without_attempt_row, queue_initial_attemptfrom skyvern.forge.sdk.workflow.schedules import as_utc, compute_previous_fire_time@@ -57,6 +58,46 @@ def previous_fire_time_since_edit(schedule: WorkflowSchedule) -> datetime | Nonereturn previous_fire_time+def due_fire_time(schedule: WorkflowSchedule) -> datetime | None:+ """A one-time schedule is due from run_at on, however late; recurring ones follow previous_fire_time_since_edit."""+ if schedule.run_at is not None:+ return schedule.run_at if schedule.run_at <= datetime.now(UTC) else None+ return previous_fire_time_since_edit(schedule)+++async def claim_schedule_for_dispatch(+ schedule: WorkflowSchedule, workflow_run_id: str, fire_at: datetime+) -> WorkflowSchedule | None:+ """Return the row to dispatch from, or None when a one-time schedule was not claimed for this fire."""+ if not schedule.is_one_time:+ return schedule+ return await app.DATABASE.schedules.claim_one_time_dispatch(+ schedule.workflow_schedule_id, schedule.organization_id, workflow_run_id, fire_at+ )+++async def _record_one_time_dispatch(claimed: WorkflowSchedule, workflow_run_id: str, *, succeeded: bool) -> None:+ if not claimed.is_one_time:+ return+ dispatch_status = OneTimeDispatchStatus.fired if succeeded else OneTimeDispatchStatus.failed+ if claimed.dispatch_status != dispatch_status:+ await app.DATABASE.schedules.finish_one_time_dispatch(+ claimed.workflow_schedule_id, claimed.organization_id, workflow_run_id, dispatch_status+ )+++@asynccontextmanager+async def one_time_dispatch_outcome(claimed: WorkflowSchedule, workflow_run_id: str) -> AsyncIterator[None]:+ """An exception or cancellation marks the claimed dispatch failed; a normal exit, including finding the run already+ created by an earlier attempt of the same run id, marks it fired."""+ try:+ yield+ except (Exception, asyncio.CancelledError):+ await _record_one_time_dispatch(claimed, workflow_run_id, succeeded=False)+ raise+ await _record_one_time_dispatch(claimed, workflow_run_id, succeeded=True)++class LocalWorkflowScheduleScheduler:def __init__(self, *, poll_interval_seconds: float, max_concurrent_runs: int) -> None:self.poll_interval_seconds = poll_interval_seconds@@ -155,7 +196,7 @@ class LocalWorkflowScheduleScheduler:async def _get_due_schedule(self, schedule: WorkflowSchedule) -> DueWorkflowSchedule | None:try:- previous_fire_time = previous_fire_time_since_edit(schedule)+ previous_fire_time = due_fire_time(schedule)except Exception:LOG.warning("Failed to compute previous fire time for workflow schedule",@@ -198,35 +239,45 @@ class LocalWorkflowScheduleScheduler:)return- try:- workflow_run = await prepare_workflow(- workflow_id=schedule.workflow_permanent_id,- organization=organization,- workflow_request=WorkflowRequestBody(data=schedule.parameters),- request_id=f"schedule:{schedule.workflow_schedule_id}:{due.previous_fire_time.isoformat()}",- trigger_type=WorkflowRunTriggerType.scheduled,- workflow_schedule_id=schedule.workflow_schedule_id,- workflow_run_id=workflow_run_id,- )- except IntegrityError:+ claimed = await claim_schedule_for_dispatch(schedule, workflow_run_id, due.previous_fire_time)+ if claimed is None:LOG.info(- "Scheduled workflow run already exists; skipping duplicate fire",+ "One-time schedule was not claimed for this fire; skipping",workflow_schedule_id=schedule.workflow_schedule_id,workflow_run_id=workflow_run_id,)return- except SQLAlchemyError:- if await app.DATABASE.schedules.has_schedule_fired_since(- schedule.workflow_schedule_id,- due.previous_fire_time,- ):++ async with one_time_dispatch_outcome(claimed, workflow_run_id):+ try:+ workflow_run = await prepare_workflow(+ workflow_id=schedule.workflow_permanent_id,+ organization=organization,+ workflow_request=WorkflowRequestBody(data=claimed.parameters),+ request_id=f"schedule:{schedule.workflow_schedule_id}:{due.previous_fire_time.isoformat()}",+ trigger_type=WorkflowRunTriggerType.scheduled,+ workflow_schedule_id=schedule.workflow_schedule_id,+ workflow_run_id=workflow_run_id,+ )+ except IntegrityError:LOG.info(- "Scheduled workflow run already persisted; skipping duplicate fire",+ "Scheduled workflow run already exists; skipping duplicate fire",workflow_schedule_id=schedule.workflow_schedule_id,workflow_run_id=workflow_run_id,)return- raise+ except SQLAlchemyError:+ if await app.DATABASE.schedules.has_schedule_fired_since(+ schedule.workflow_schedule_id,+ due.previous_fire_time,+ ):+ LOG.info(+ "Scheduled workflow run already persisted; skipping duplicate fire",+ workflow_schedule_id=schedule.workflow_schedule_id,+ workflow_run_id=workflow_run_id,+ )+ return+ raise# A persisted run counts as a delivered fire. Queue its attempt for sweep recovery;# without an attempt row, an initialization failure must make the run terminal.diff --git a/tests/unit/forge/sdk/test_workflow_schedules_routes.py b/tests/unit/forge/sdk/test_workflow_schedules_routes.pyindex f94743838..902d3c714 100644--- a/tests/unit/forge/sdk/test_workflow_schedules_routes.py+++ b/tests/unit/forge/sdk/test_workflow_schedules_routes.py@@ -11,17 +11,24 @@ from unittest.mock import AsyncMockimport httpximport pytestimport pytest_asyncio-from fastapi import FastAPI+from fastapi import FastAPI, HTTPExceptionfrom fastapi.testclient import TestClientfrom 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.cli.mcp_tools.schedule import (+ skyvern_schedule_cancel,+ skyvern_schedule_create,+ skyvern_schedule_get,+ skyvern_schedule_list,+ skyvern_schedule_update,+)from skyvern.client import AsyncSkyvernfrom skyvern.forge.agent_functions import AgentFunctionfrom skyvern.forge.api_app import register_agent_route_aliasesfrom skyvern.forge.sdk.db.agent_db import AgentDBfrom skyvern.forge.sdk.routes import routers as routers_module+from skyvern.forge.sdk.schemas.workflow_schedules import OneTimeDispatchStatusfrom skyvern.forge.sdk.services import org_auth_servicefrom tests.unit.forge.sdk.db import conftest as db_fixtures@@ -303,3 +310,233 @@ async def test_first_fire_at_too_far_out_to_compute_ticks_is_a_field_named_422_t[stored] = await agent_db.schedules.get_workflow_schedules(workflow_permanent_id=WPID, organization_id=ORG_ID)assert stored.interval_seconds == 5 * HOURassert stored.first_fire_at == NOW + timedelta(hours=5)+++RUN_AT = NOW + timedelta(minutes=10)+REAL_ENSURE_WORKFLOW_EXISTS = workflow_schedule_routes._ensure_workflow_exists+++async def _create_one_time_and_assert_nothing_written(+ schedules_client: httpx.AsyncClient, agent_db: AgentDB, body: dict[str, Any], status: int+) -> None:+ response = await _request(schedules_client, NOW, "POST", "", json={**body, "timezone": "America/Los_Angeles"})++ assert response.status_code == status, response.text+ assert await agent_db.schedules.get_workflow_schedules(workflow_permanent_id=WPID, organization_id=ORG_ID) == []+++ "body",+ [+ pytest.param({"run_at": _iso(NOW - timedelta(minutes=1))}, id="past"),+ pytest.param({"run_at": _iso(NOW + timedelta(seconds=30))}, id="under-a-minute"),+ pytest.param({"run_at": "2026-10-30T12:10:00"}, id="naive"),+ pytest.param({"run_at": _iso(RUN_AT), "enabled": False}, id="disabled"),+ pytest.param({"run_at": _iso(RUN_AT), "cron_expression": "0 9 * * *"}, id="two-cadences"),+ ],+)+async def test_create_one_time_rejects_each_invalid_input_with_a_422_and_writes_nothing(+ schedules_client: httpx.AsyncClient, agent_db: AgentDB, body: dict[str, Any]+) -> None:+ await _create_one_time_and_assert_nothing_written(schedules_client, agent_db, body, 422)+++async def test_create_one_time_rejects_invalid_parameters_with_a_400_and_writes_nothing(+ schedules_client: httpx.AsyncClient, agent_db: AgentDB+) -> None:+ workflow_schedule_routes.app.WORKFLOW_SERVICE.validate_schedule_parameters.side_effect = HTTPException(+ status_code=400, detail="Missing required parameter: city"+ )++ await _create_one_time_and_assert_nothing_written(schedules_client, agent_db, {"run_at": _iso(RUN_AT)}, 400)+++async def test_create_one_time_on_a_foreign_workflow_returns_404_and_writes_nothing(+ schedules_client: httpx.AsyncClient, agent_db: AgentDB, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(workflow_schedule_routes, "_ensure_workflow_exists", REAL_ENSURE_WORKFLOW_EXISTS)++ await _create_one_time_and_assert_nothing_written(schedules_client, agent_db, {"run_at": _iso(RUN_AT)}, 404)+++async def test_one_time_run_at_after_2100_is_rejected_before_the_backend_sync(+ schedules_client: httpx.AsyncClient,+) -> None:+ too_late = await _request(+ schedules_client, NOW, "POST", "", json={"run_at": "2101-01-01T00:00:00Z", "timezone": "UTC"}+ )+ last_allowed = await _request(+ schedules_client, NOW, "POST", "", json={"run_at": "2100-12-31T23:59:59Z", "timezone": "UTC"}+ )++ assert too_late.status_code == 422 and "run_at must be no later than 2100-12-31T23:59:59" in too_late.text+ assert last_allowed.status_code == 200+++async def test_one_time_schedule_edits_while_pending_and_conflicts_unchanged_once_fired(+ schedules_client: httpx.AsyncClient,+ agent_db: AgentDB,+) -> None:+ created = await _request(+ schedules_client,+ NOW,+ "POST",+ "",+ json={"run_at": "2026-10-30T05:10:30.750-07:00", "timezone": "America/Los_Angeles", "parameters": {"a": 1}},+ )+ assert created.status_code == 200, created.text+ schedule = created.json()["schedule"]+ schedule_id = schedule["workflow_schedule_id"]+ assert (schedule["run_at"], schedule["dispatch_status"], schedule["workflow_run_id"]) == (+ _iso(RUN_AT),+ "pending",+ None,+ )+ assert created.json()["next_runs"] == [_iso(RUN_AT)]++ for path, method, body in (+ (f"/{schedule_id}", "PUT", {"cron_expression": "0 9 * * *", "timezone": "UTC"}),+ (f"/{schedule_id}/disable", "POST", None),+ (f"/{schedule_id}/enable", "POST", None),+ ):+ refused = await _request(schedules_client, NOW, method, path, json=body)+ assert refused.status_code == 422, (path, refused.text)++ moved_to = RUN_AT + timedelta(minutes=5)+ edited = await _request(+ schedules_client,+ NOW,+ "PUT",+ f"/{schedule_id}",+ json={"run_at": _iso(moved_to), "timezone": "America/Los_Angeles", "parameters": {"a": 2}},+ )+ assert edited.status_code == 200, edited.text+ assert edited.json()["schedule"]["run_at"] == _iso(moved_to)+ assert edited.json()["schedule"]["parameters"] == {"a": 2}+ pending = (await schedules_client.get("/v1/schedules")).json()["schedules"]+ assert [(item["dispatch_status"], item["next_run"]) for item in pending] == [("pending", _iso(moved_to))]++ with freeze_time(RUN_AT, real_asyncio=True):+ assert await agent_db.schedules.claim_one_time_dispatch(schedule_id, ORG_ID, "wr_sched_early", RUN_AT) is None+ with freeze_time(moved_to, real_asyncio=True):+ claimed = await agent_db.schedules.claim_one_time_dispatch(schedule_id, ORG_ID, "wr_sched_once", moved_to)+ assert claimed is not None and claimed.parameters == {"a": 2}+ assert (+ await agent_db.schedules.claim_one_time_dispatch(schedule_id, ORG_ID, "wr_sched_once", moved_to) == claimed+ )+ assert await agent_db.schedules.claim_one_time_dispatch(schedule_id, ORG_ID, "wr_sched_other", moved_to) is None++ before = (await _request(schedules_client, moved_to, "GET", f"/{schedule_id}")).json()+ assert before["schedule"]["dispatch_status"] == "fired"+ assert before["schedule"]["workflow_run_id"] == "wr_sched_once"+ assert before["next_runs"] == []+ for path, method, body in (+ (f"/{schedule_id}", "PUT", {"run_at": _iso(moved_to + timedelta(hours=1)), "timezone": "UTC"}),+ (f"/{schedule_id}/cancel", "POST", None),+ ):+ conflict = await _request(schedules_client, moved_to, method, path, json=body)+ assert conflict.status_code == 409, (path, conflict.text)+ raced_edit = await agent_db.schedules.update_workflow_schedule(+ workflow_schedule_id=schedule_id,+ organization_id=ORG_ID,+ cron_expression=None,+ timezone="UTC",+ parameters={"a": 3},+ run_at=moved_to + timedelta(hours=1),+ )+ assert raced_edit is None+ after = (await _request(schedules_client, moved_to, "GET", f"/{schedule_id}")).json()+ assert after == before++ listed = (await schedules_client.get("/v1/schedules")).json()["schedules"]+ assert [+ (item["run_at"], item["dispatch_status"], item["workflow_run_id"], item["next_run"]) for item in listed+ ] == [(_iso(moved_to), "fired", "wr_sched_once", None)]+++async def test_cancel_keeps_a_pending_one_time_schedule_readable_and_it_never_fires(+ schedules_client: httpx.AsyncClient,+ agent_db: AgentDB,+) -> None:+ created = await _request(schedules_client, NOW, "POST", "", json={"run_at": _iso(RUN_AT), "timezone": "UTC"})+ schedule_id = created.json()["schedule"]["workflow_schedule_id"]+ recurring = await _request(+ schedules_client, NOW, "POST", "", json={"cron_expression": "0 9 * * *", "timezone": "UTC"}+ )++ canceled = await _request(schedules_client, NOW, "POST", f"/{schedule_id}/cancel")+ not_one_time = await _request(+ schedules_client, NOW, "POST", f"/{recurring.json()['schedule']['workflow_schedule_id']}/cancel"+ )++ assert canceled.status_code == 200, canceled.text+ assert canceled.json()["schedule"]["dispatch_status"] == OneTimeDispatchStatus.canceled+ assert canceled.json()["next_runs"] == []+ assert not_one_time.status_code == 422+ with freeze_time(RUN_AT + timedelta(days=1), real_asyncio=True):+ assert await agent_db.schedules.claim_one_time_dispatch(schedule_id, ORG_ID, "wr_sched_late", RUN_AT) is None+ due_ids = [s.workflow_schedule_id for s in await agent_db.schedules.get_all_enabled_schedules()]+ assert schedule_id not in due_ids+ assert (await _request(schedules_client, NOW, "GET", f"/{schedule_id}")).json()["schedule"][+ "dispatch_status"+ ] == "canceled"+++async def test_mcp_tools_create_edit_cancel_and_read_back_every_one_time_state(+ schedules_client: httpx.AsyncClient,+ agent_db: AgentDB,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ sdk = AsyncSkyvern(base_url="http://test", api_key="test", httpx_client=schedules_client)+ monkeypatch.setattr("skyvern.cli.mcp_tools.schedule.get_skyvern", lambda: sdk)++ async def state(schedule_id: str) -> tuple[str, str | None, list[str]]:+ got = await skyvern_schedule_get(workflow_permanent_id=WPID, workflow_schedule_id=schedule_id)+ assert got["ok"], got+ schedule = got["data"]["schedule"]+ return schedule["dispatch_status"], schedule["workflow_run_id"], got["data"]["next_runs"]++ with freeze_time(NOW, real_asyncio=True):+ created = [+ await skyvern_schedule_create(+ workflow_permanent_id=WPID, timezone="America/Los_Angeles", run_at=RUN_AT, parameters={"n": n}+ )+ for n in range(3)+ ]+ assert all(result["ok"] for result in created), created+ canceled_id, fired_id, failed_id = (result["data"]["schedule"]["workflow_schedule_id"] for result in created)+ edited = await skyvern_schedule_update(+ workflow_permanent_id=WPID, workflow_schedule_id=fired_id, parameters={"n": 10}+ )+ assert edited["ok"], edited+ assert (edited["data"]["schedule"]["run_at"], edited["data"]["schedule"]["parameters"]) == (+ RUN_AT.isoformat(),+ {"n": 10},+ )+ assert (await skyvern_schedule_cancel(workflow_permanent_id=WPID, workflow_schedule_id=canceled_id))["ok"]++ with freeze_time(RUN_AT, real_asyncio=True):+ for schedule_id, run_id in ((fired_id, "wr_sched_fired"), (failed_id, "wr_sched_failed")):+ assert await agent_db.schedules.claim_one_time_dispatch(schedule_id, ORG_ID, run_id, RUN_AT) is not None+ await agent_db.schedules.finish_one_time_dispatch(+ failed_id, ORG_ID, "wr_sched_failed", OneTimeDispatchStatus.failed+ )+ refused = await skyvern_schedule_cancel(workflow_permanent_id=WPID, workflow_schedule_id=fired_id)+ listed = await skyvern_schedule_list()++ assert await state(canceled_id) == ("canceled", None, [])+ assert await state(fired_id) == ("fired", "wr_sched_fired", [])+ assert await state(failed_id) == ("failed", "wr_sched_failed", [])+ assert refused["ok"] is False and "409" in refused["error"]["message"]+ assert sorted((item["dispatch_status"], item["workflow_run_id"]) for item in listed["data"]["schedules"]) == [+ ("canceled", None),+ ("failed", "wr_sched_failed"),+ ("fired", "wr_sched_fired"),+ ]diff --git a/tests/unit/test_background_task_executor.py b/tests/unit/test_background_task_executor.pyindex 2600c2e9b..7d77715f6 100644--- a/tests/unit/test_background_task_executor.py+++ b/tests/unit/test_background_task_executor.py@@ -3477,7 +3477,11 @@ async def test_scheduled_run_whose_initializer_fails_is_recovered_after_a_restar) -> None:fire_time = datetime(2026, 6, 2, 10, 0, tzinfo=UTC)schedule = SimpleNamespace(- workflow_schedule_id="wfs_test", workflow_permanent_id="wpid_test", organization_id="org_test", parameters={}+ workflow_schedule_id="wfs_test",+ workflow_permanent_id="wpid_test",+ organization_id="org_test",+ parameters={},+ is_one_time=False,)workflow_run_id = schedule_service_module.build_scheduled_workflow_run_id(schedule.workflow_schedule_id, fire_time)async with sqlite_db.Session() as session:diff --git a/tests/unit/test_copilot_hooks.py b/tests/unit/test_copilot_hooks.pyindex c044160f8..38ee3a01a 100644--- a/tests/unit/test_copilot_hooks.py+++ b/tests/unit/test_copilot_hooks.py@@ -907,6 +907,7 @@ class TestMCPToolOverlayCompleteness:"update_workflow_schedule","enable_workflow_schedule","disable_workflow_schedule",+ "cancel_workflow_schedule","delete_workflow_schedule",}assert set(alias_map.keys()) == expected_aliasesdiff --git a/tests/unit/test_copilot_mcp_adapter.py b/tests/unit/test_copilot_mcp_adapter.pyindex de7af2fcc..0901b23b4 100644--- a/tests/unit/test_copilot_mcp_adapter.py+++ b/tests/unit/test_copilot_mcp_adapter.py@@ -2962,6 +2962,7 @@ _SCHEDULE_TOOLS = ("update_workflow_schedule","enable_workflow_schedule","disable_workflow_schedule",+ "cancel_workflow_schedule","delete_workflow_schedule",)@@ -3021,7 +3022,9 @@ async def test_chat_surface_exposes_only_chat_bound_workflow_schedule_tools() ->assert "exact" not in tools[name].inputSchema["properties"]assert "force" in tools["delete_workflow_schedule"].inputSchema["properties"]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", "interval_seconds", "first_fire_at", "run_at"} <= set(+ tools[name].inputSchema["properties"]+ )assert "cron_expression" not in tools["create_workflow_schedule"].inputSchema.get("required", [])diff --git a/tests/unit/test_mcp_legacy_manifest.py b/tests/unit/test_mcp_legacy_manifest.pyindex 6dece7d66..b8e28ea6d 100644--- a/tests/unit/test_mcp_legacy_manifest.py+++ b/tests/unit/test_mcp_legacy_manifest.py@@ -97,14 +97,14 @@ LEGACY_TOOL_MANIFEST_DIGESTS = {"skyvern_org_update": "bbb6283207460a33b0d2759d563ecf4a8431fdc8c5cf7dbb15d10d27f36e0951","skyvern_press_key": "ad74ceb98f5b21483940f027747817d21f751eebb781c11f97529c5be968a9c4","skyvern_run_task": "e48efaa780ab1f49c8d5a7c489edf293880448d07e7e0f3d88b65807d559cb23",- "skyvern_schedule_create": "1ec88d11f92cd56106ab8a657617e8f6e16277049736584768f34288263c922f",+ "skyvern_schedule_create": "b7a4305713340d816176ae39c8f20045da3d084c5e58303e29ca202a99c5fdd6","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": "0f64b40bd760fd3e49907a4f23062ee3ffe18c1be96960276f9b71ecdc07d5f6",+ "skyvern_schedule_update": "f9da5e0ce2657c594c526f0201fcb082ff6b939f6c8c98a468f2140b8a35b75d","skyvern_screenshot": "96f506db0c7780f79d45261d8a432114893130b04160f977214d08865771a2b8","skyvern_script_deploy": "c14adba89381f2e3b6010d44f5a2c66b840b57fc835cfe08ac864aaacba63b8e","skyvern_script_fallback_episodes": "c6f23e8270426a40ff2692ef33dc738b8083e0a38eaf9d0e2e08f93768d645e6",@@ -148,8 +148,8 @@ LEGACY_TOOL_MANIFEST_DIGESTS = {# Resolved memberships for the three pre-existing scopes must remain byte-for-byte stable.LEGACY_SCOPE_MEMBERSHIP_DIGESTS: dict[MCPScope, tuple[int, str]] = {"browser": (54, "8c05058f36d5d4472e11f384ed68cabbae0478b3e16d2f7da6c2d07dda21703a"),- "build": (61, "3d5e09451edd441de5c79f489539a8b0f97679e0e342972c7541757eb4de14a4"),- "operate": (29, "d5181b03b06212403ce381a6f95a916d12e303987949acd46b8f813f38e413f0"),+ "build": (62, "0f6d512bf4a3af872181682aa1deb47df8180c9bf4da83e3ae9c63fc3b8ec121"),+ "operate": (30, "fb27a193d3bedb074331306de64264afcce59dd88223b33045cb41d95cc612b7"),}diff --git a/tests/unit/test_mcp_scope_visibility.py b/tests/unit/test_mcp_scope_visibility.pyindex f684cde6f..4e2da48f8 100644--- a/tests/unit/test_mcp_scope_visibility.py+++ b/tests/unit/test_mcp_scope_visibility.py@@ -182,11 +182,11 @@ async def test_every_real_scope_is_non_empty_strict_subset(scoped_mcp: FastMCP)# on ONE tool of many — the tag survives elsewhere, the subset stays strict, and the scope# silently loses a tool. Only an external oracle catches that, so these numbers are a ratchet:# adding or re-tagging a tool must be a conscious edit here, reviewed alongside the scope map.-RESOLVED_SCOPE_SIZES: dict[MCPScope, int] = {"operate": 29, "build": 61, "browser": 54, "lean": 33}+RESOLVED_SCOPE_SIZES: dict[MCPScope, int] = {"operate": 30, "build": 62, "browser": 54, "lean": 33}# Same ratchet for the unfiltered (`all`) surface. Kept in one place because duplicated copies# drift: a registration that bumps only its own copy leaves the others to fail in CI.-TOTAL_TOOL_COUNT: int = 116+TOTAL_TOOL_COUNT: int = 117@pytest.mark.asynciodiff --git a/tests/unit/test_workflow_browser_profile_id.py b/tests/unit/test_workflow_browser_profile_id.pyindex 4bab29e98..baf0f99c7 100644--- a/tests/unit/test_workflow_browser_profile_id.py+++ b/tests/unit/test_workflow_browser_profile_id.py@@ -574,6 +574,8 @@ async def test_refresh_workflow_schedule_runtime_limits_reupserts_backend_scheducron_expression="0 */6 * * *",interval_seconds=None,first_fire_at=None,+ run_at=None,+ dispatch_status=None,timezone="UTC",enabled=True,parameters={"url": "https://example.com"},@@ -584,10 +586,26 @@ async def test_refresh_workflow_schedule_runtime_limits_reupserts_backend_scheducron_expression=None,interval_seconds=18000,first_fire_at=datetime(2026, 10, 30, 15, 0, tzinfo=timezone.utc),+ run_at=None,+ dispatch_status=None,timezone="America/New_York",enabled=False,parameters=None,)+ pending_one_time = SimpleNamespace(+ backend_schedule_id="temporal_3",+ workflow_schedule_id="wfs_3",+ cron_expression=None,+ interval_seconds=None,+ first_fire_at=None,+ run_at=datetime(2026, 11, 2, 8, 1, tzinfo=timezone.utc),+ dispatch_status="pending",+ timezone="America/Los_Angeles",+ enabled=True,+ parameters=None,+ )+ fired_one_time = SimpleNamespace(**{**vars(pending_one_time), "workflow_schedule_id": "wfs_4"})+ fired_one_time.dispatch_status = "fired"schedule_without_backend = SimpleNamespace(backend_schedule_id=None,workflow_schedule_id="wfs_local",@@ -602,7 +620,13 @@ 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, interval_schedule_with_backend, schedule_without_backend]+ return_value=[+ schedule_with_backend,+ interval_schedule_with_backend,+ pending_one_time,+ fired_one_time,+ schedule_without_backend,+ ])mock_app.AGENT_FUNCTION.upsert_workflow_schedule = AsyncMock()@@ -629,6 +653,7 @@ async def test_refresh_workflow_schedule_runtime_limits_reupserts_backend_schedumax_elapsed_time_minutes=360,interval_seconds=None,first_fire_at=None,+ run_at=None,),call(backend_schedule_id="temporal_2",@@ -642,6 +667,21 @@ async def test_refresh_workflow_schedule_runtime_limits_reupserts_backend_schedumax_elapsed_time_minutes=360,interval_seconds=18000,first_fire_at=datetime(2026, 10, 30, 15, 0, tzinfo=timezone.utc),+ run_at=None,+ ),+ call(+ backend_schedule_id="temporal_3",+ organization_id="org_1",+ workflow_permanent_id="wpid_test",+ workflow_schedule_id="wfs_3",+ cron_expression=None,+ timezone="America/Los_Angeles",+ enabled=True,+ parameters=None,+ max_elapsed_time_minutes=360,+ interval_seconds=None,+ first_fire_at=None,+ run_at=datetime(2026, 11, 2, 8, 1, tzinfo=timezone.utc),),]diff --git a/tests/unit/test_workflow_schedule_service.py b/tests/unit/test_workflow_schedule_service.pyindex 2616641b9..c177b22b1 100644--- a/tests/unit/test_workflow_schedule_service.py+++ b/tests/unit/test_workflow_schedule_service.py@@ -1,17 +1,23 @@from __future__ import annotationsimport asyncio-from datetime import UTC, datetime+from datetime import UTC, datetime, timedeltafrom types import SimpleNamespacefrom unittest.mock import AsyncMockimport pytest+from freezegun import freeze_timeimport skyvern.forge.sdk.workflow.retry_policy as retry_policy_moduleimport skyvern.services.workflow_schedule_service as schedule_service+from skyvern.forge.sdk.db.agent_db import AgentDBfrom skyvern.forge.sdk.db.enums import WorkflowRunTriggerType-from skyvern.forge.sdk.schemas.workflow_schedules import WorkflowSchedule+from skyvern.forge.sdk.schemas.workflow_schedules import OneTimeDispatchStatus, WorkflowSchedulefrom skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus+from tests.unit.forge.sdk.db import conftest as db_fixtures++agent_db = db_fixtures.agent_db+db_engine = db_fixtures.db_enginedef _schedule(*, modified_at: datetime | None = None) -> WorkflowSchedule:@@ -217,3 +223,91 @@ async def test_run_schedule_no_policy_initializer_failure_fails_the_run(get_attempts.assert_awaited_once_with(run_id)fake_app.DATABASE.workflow_runs.queue_initial_dispatch.assert_awaited_once_with(run_id, 1)execute.assert_not_awaited()+++async def test_a_late_one_time_schedule_dispatches_from_its_claimed_row_and_reads_back_failed_on_setup_error(+ agent_db: AgentDB, monkeypatch: pytest.MonkeyPatch+) -> None:+ run_at = datetime(2026, 6, 2, 10, 0, tzinfo=UTC)+ with freeze_time(run_at - timedelta(hours=1), real_asyncio=True):+ schedule = await agent_db.schedules.create_workflow_schedule(+ organization_id="org_test",+ workflow_permanent_id="wpid_test",+ cron_expression=None,+ timezone="UTC",+ enabled=True,+ parameters={"city": "Paris"},+ run_at=run_at,+ )+ prepare_workflow = AsyncMock(side_effect=RuntimeError("workflow was deleted"))+ fake_app = SimpleNamespace(+ DATABASE=SimpleNamespace(+ schedules=agent_db.schedules,+ organizations=SimpleNamespace(+ get_organization=AsyncMock(return_value=SimpleNamespace(organization_id="org_test"))+ ),+ ),+ )+ monkeypatch.setattr(schedule_service, "app", fake_app)+ monkeypatch.setattr(schedule_service, "prepare_workflow", prepare_workflow)+ scheduler = schedule_service.LocalWorkflowScheduleScheduler(poll_interval_seconds=1, max_concurrent_runs=1)++ with freeze_time(run_at + timedelta(days=2), real_asyncio=True):+ due = await scheduler._get_due_schedule(schedule)+ assert due is not None and due.previous_fire_time == run_at+ with pytest.raises(RuntimeError, match="workflow was deleted"):+ await scheduler._run_schedule(due)+ assert await agent_db.schedules.get_all_enabled_schedules() == []++ assert prepare_workflow.await_args.kwargs["workflow_request"].data == {"city": "Paris"}+ stored = await agent_db.schedules.get_workflow_schedule_by_id(schedule.workflow_schedule_id, "org_test")+ assert stored is not None+ assert (stored.dispatch_status, stored.workflow_run_id) == (+ OneTimeDispatchStatus.failed,+ schedule_service.build_scheduled_workflow_run_id(schedule.workflow_schedule_id, run_at),+ )+++async def test_a_one_time_fire_scanned_before_run_at_was_edited_starts_no_run(+ agent_db: AgentDB, monkeypatch: pytest.MonkeyPatch+) -> None:+ run_at = datetime(2026, 6, 2, 10, 0, tzinfo=UTC)+ with freeze_time(run_at - timedelta(hours=1), real_asyncio=True):+ schedule = await agent_db.schedules.create_workflow_schedule(+ organization_id="org_test",+ workflow_permanent_id="wpid_test",+ cron_expression=None,+ timezone="UTC",+ enabled=True,+ run_at=run_at,+ )+ await agent_db.schedules.update_workflow_schedule(+ schedule.workflow_schedule_id,+ "org_test",+ cron_expression=None,+ timezone="UTC",+ run_at=run_at + timedelta(days=1),+ )+ prepare_workflow = AsyncMock()+ fake_app = SimpleNamespace(+ DATABASE=SimpleNamespace(+ schedules=agent_db.schedules,+ organizations=SimpleNamespace(+ get_organization=AsyncMock(return_value=SimpleNamespace(organization_id="org_test"))+ ),+ ),+ )+ monkeypatch.setattr(schedule_service, "app", fake_app)+ monkeypatch.setattr(schedule_service, "prepare_workflow", prepare_workflow)+ scheduler = schedule_service.LocalWorkflowScheduleScheduler(poll_interval_seconds=1, max_concurrent_runs=1)++ with freeze_time(run_at + timedelta(days=2), real_asyncio=True):+ await scheduler._run_schedule(+ schedule_service.DueWorkflowSchedule(schedule=schedule, previous_fire_time=run_at)+ )++ prepare_workflow.assert_not_awaited()+ stored = await agent_db.schedules.get_workflow_schedule_by_id(schedule.workflow_schedule_id, "org_test")+ assert stored is not None and stored.dispatch_status == OneTimeDispatchStatus.pending