Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(workflows): list every schedule a workflow holds (#123820)

Meikel Ratzf4f6b321d926
diff --git a/products/workflows/backend/services/hog_flow_schedules.py b/products/workflows/backend/services/hog_flow_schedules.py
index 17d038bb2387..58493c053400 100644
--- a/products/workflows/backend/services/hog_flow_schedules.py
+++ b/products/workflows/backend/services/hog_flow_schedules.py
@@ -47,7 +47,9 @@ def _get_schedule_row(team_id: int, hog_flow_id: UUID, schedule_id: str | UUID)
def list_schedules(*, team_id: int, hog_flow_id: UUID) -> list[WorkflowSchedule]:
- schedules = HogFlowSchedule.objects.filter(hog_flow_id=hog_flow_id, team_id=team_id).order_by("-created_at")
+ # Same order as the schedules a workflow response embeds, so the editor and the broadcast
+ # screens agree on which schedule is the first one.
+ schedules = HogFlowSchedule.objects.filter(hog_flow_id=hog_flow_id, team_id=team_id).order_by("created_at", "id")
return [_to_schedule(s) for s in schedules]
diff --git a/products/workflows/backend/test/test_hog_flow_schedule.py b/products/workflows/backend/test/test_hog_flow_schedule.py
index c607f7e8016f..78ae7aca67f2 100644
--- a/products/workflows/backend/test/test_hog_flow_schedule.py
+++ b/products/workflows/backend/test/test_hog_flow_schedule.py
@@ -101,7 +101,12 @@ class TestHogFlowScheduleAPI(APIBaseTest):
response = self.client.get(self._schedules_url(workflow["id"]))
assert response.status_code == status.HTTP_200_OK
- assert len(response.json()) == 2
+ # Oldest first, the order the workflow response embeds them in, so both screens call the
+ # same schedule the first one.
+ assert [schedule["rrule"] for schedule in response.json()] == [
+ SCHEDULE_DATA["rrule"],
+ "FREQ=DAILY;INTERVAL=1",
+ ]
def test_update_schedule(self):
workflow = self._create_batch_workflow()
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx
index 6e8bb2fd7935..db9002e04bbe 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx
@@ -68,6 +68,7 @@ import { EmailSendingRateLimitPicker } from './components/EmailSendingRateLimitP
import { HogFlowFunctionConfiguration } from './components/HogFlowFunctionConfiguration'
import { RealtimeCohortAudienceNotice } from './components/RealtimeCohortAudienceNotice'
import { RecurringSchedulePicker } from './components/RecurringSchedulePicker'
+import { ScheduleList } from './components/ScheduleList'
import { ScheduleStatusBadge } from './components/ScheduleStatusBadge'
import { TriggerVolumeEstimate } from './components/TriggerVolumeEstimate'
import { keepOnlyRealtimeCohort } from './realtimeCohortStatus'
@@ -377,6 +378,7 @@ export function StepTriggerConfiguration({ node }: { node: Node<TriggerAction> }
Schedule triggers run without a person or event. If your workflow needs to target specific
users, use a batch trigger instead.
</p>
+ <ScheduleList />
<LemonField.Pure error={validationResult?.errors?.schedule}>
<WorkflowRecurringSchedulePicker />
</LemonField.Pure>
@@ -642,6 +644,7 @@ function BatchScheduleSection(): JSX.Element {
<>
<LemonDivider />
<LemonLabel showOptional>Schedule</LemonLabel>
+ <ScheduleList />
<WorkflowRecurringSchedulePicker />
</>
)
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/ScheduleList.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/ScheduleList.tsx
new file mode 100644
index 000000000000..f3deef0895a3
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/ScheduleList.tsx
@@ -0,0 +1,156 @@
+import { useActions, useValues } from 'kea'
+
+import { IconPlus, IconTrash } from '@posthog/icons'
+import { LemonButton, LemonDialog, LemonTag } from '@posthog/lemon-ui'
+
+import { dayjs } from 'lib/dayjs'
+
+import { workflowLogic } from '../../../workflowLogic'
+import { HogFlowSchedule } from '../../types'
+import { summarizeSchedule } from './rrule-helpers'
+
+function ScheduleStateTag({ status }: { status?: string }): JSX.Element | null {
+ if (status === 'completed') {
+ return (
+ <LemonTag type="default" size="small">
+ Completed
+ </LemonTag>
+ )
+ }
+ if (status === 'paused') {
+ return (
+ <LemonTag type="warning" size="small">
+ Paused
+ </LemonTag>
+ )
+ }
+ return null
+}
+
+function ScheduleRow({ schedule, editing }: { schedule: HogFlowSchedule; editing: boolean }): JSX.Element {
+ const { deleteSchedule, selectSchedule } = useActions(workflowLogic)
+ const { pendingSchedule } = useValues(workflowLogic)
+
+ // Picking another row rebaselines the picker from the saved schedule, so an unsaved change to
+ // the current one would go without the author noticing.
+ const pickThisRow = (): void => {
+ if (editing) {
+ return
+ }
+ if (pendingSchedule !== false) {
+ LemonDialog.open({
+ title: 'Discard your unsaved schedule change?',
+ description: 'You changed the schedule you are editing and have not saved it yet.',
+ primaryButton: {
+ children: 'Discard and switch',
+ status: 'danger',
+ onClick: () => selectSchedule(schedule),
+ },
+ secondaryButton: { children: 'Keep editing' },
+ })
+ return
+ }
+ selectSchedule(schedule)
+ }
+
+ const summary = summarizeSchedule(schedule.rrule, schedule.starts_at, schedule.timezone)
+
+ return (
+ <div className="flex items-center gap-1 p-1">
+ <LemonButton
+ fullWidth
+ className="flex-1 min-w-0"
+ active={editing}
+ onClick={pickThisRow}
+ data-attr="workflow-schedule-row"
+ >
+ <div className="flex-1 min-w-0 py-1">
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className="truncate">{summary}</span>
+ <ScheduleStateTag status={schedule.status} />
+ {editing && (
+ <LemonTag type="highlight" size="small">
+ Editing below
+ </LemonTag>
+ )}
+ </div>
+ <div className="text-xs text-muted font-normal">
+ {schedule.timezone ?? 'UTC'}
+ {schedule.next_run_at
+ ? ` · next run ${dayjs(schedule.next_run_at)
+ .tz(schedule.timezone ?? 'UTC')
+ .format('D MMM, HH:mm')}`
+ : ''}
+ </div>
+ </div>
+ </LemonButton>
+ <LemonButton
+ icon={<IconTrash />}
+ size="small"
+ status="danger"
+ tooltip="Remove this schedule"
+ data-attr="remove-workflow-schedule"
+ onClick={() =>
+ LemonDialog.open({
+ title: 'Remove this schedule?',
+ description: `${summary}. The workflow stops running on it. Any other schedules keep going.`,
+ primaryButton: {
+ children: 'Remove',
+ status: 'danger',
+ onClick: () => deleteSchedule(schedule.id),
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ }
+ />
+ </div>
+ )
+}
+
+// Every surface used to read schedules[0], so a workflow that holds more than one showed a single
+// schedule and silently ran the rest. Listing them is what lets an author pick, add or remove one.
+export function ScheduleList(): JSX.Element | null {
+ const { schedules, currentSchedule, logicProps, addingSchedule } = useValues(workflowLogic)
+ const { addSchedule } = useActions(workflowLogic)
+
+ if (schedules.length === 0) {
+ return null
+ }
+
+ const addButton = (
+ <LemonButton
+ icon={<IconPlus />}
+ size="small"
+ type="secondary"
+ data-attr="add-workflow-schedule"
+ loading={addingSchedule}
+ disabledReason={
+ logicProps.id === 'new' ? 'Save the workflow first' : addingSchedule ? 'Adding a schedule' : undefined
+ }
+ onClick={() => addSchedule()}
+ >
+ Add schedule
+ </LemonButton>
+ )
+
+ if (schedules.length === 1) {
+ return <div className="flex">{addButton}</div>
+ }
+
+ return (
+ <div className="flex flex-col gap-1">
+ <div className="flex items-center justify-between gap-2">
+ <span className="font-semibold text-sm">This workflow has {schedules.length} schedules</span>
+ {addButton}
+ </div>
+ <p className="text-xs text-muted mb-0">
+ They all run. Pick one to edit it below, or remove any you did not mean to add.
+ </p>
+ <div className="border rounded bg-surface-primary divide-y">
+ {schedules.map((schedule) => (
+ <ScheduleRow key={schedule.id} schedule={schedule} editing={schedule.id === currentSchedule?.id} />
+ ))}
+ </div>
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/rrule-helpers.test.ts b/products/workflows/frontend/Workflows/hogflows/steps/components/rrule-helpers.test.ts
index 032c7c15b064..ad137c1e4d72 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/components/rrule-helpers.test.ts
+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/rrule-helpers.test.ts
@@ -16,6 +16,7 @@ import {
ScheduleState,
scheduleToText,
stateToRRule,
+ summarizeSchedule,
} from './rrule-helpers'
describe('rrule-helpers', () => {
@@ -432,4 +433,20 @@ describe('rrule-helpers', () => {
expect(scheduleToText(state, null)).toBe(expected)
})
})
+
+ describe('summarizeSchedule', () => {
+ const STARTS = '2026-11-02T09:00:00.000Z'
+
+ it('names the date of a one-time schedule so two of them can be told apart', () => {
+ expect(summarizeSchedule(ONE_TIME_RRULE, STARTS, 'UTC')).toBe('Runs once on 2 Nov 2026, 09:00')
+ })
+
+ it('shows a rule the picker cannot model as written rather than describing it wrongly', () => {
+ expect(summarizeSchedule('FREQ=HOURLY;INTERVAL=1', STARTS, 'UTC')).toBe('FREQ=HOURLY;INTERVAL=1')
+ })
+
+ it('describes a rule the picker does model', () => {
+ expect(summarizeSchedule('FREQ=DAILY;INTERVAL=3', STARTS, 'UTC')).toContain('every 3 days')
+ })
+ })
})
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/rrule-helpers.ts b/products/workflows/frontend/Workflows/hogflows/steps/components/rrule-helpers.ts
index 709b2aa6e937..63ab9c5115dd 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/components/rrule-helpers.ts
+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/rrule-helpers.ts
@@ -278,6 +278,22 @@ export function buildSummary(state: ScheduleState, startsAt: string | null, time
}
/** Parse natural language like "every week on Monday and Wednesday" into a ScheduleState. */
+// parseRRuleToState falls back to weekly outside these four, and the API accepts any rule
+// dateutil parses, so anything else is shown as written rather than described wrongly.
+const SUMMARIZABLE_FREQUENCIES = ['DAILY', 'WEEKLY', 'MONTHLY', 'YEARLY']
+
+export function summarizeSchedule(rrule: string, startsAt: string | null, timezone?: string): string {
+ if (isOneTimeSchedule(rrule)) {
+ const at = startsAt ? (timezone ? dayjs(startsAt).tz(timezone) : dayjs(startsAt)) : null
+ return at ? `Runs once on ${at.format('D MMM YYYY, HH:mm')}` : 'Runs once'
+ }
+ const frequency = rrule.match(/FREQ=([A-Z]+)/)?.[1]
+ if (!frequency || !SUMMARIZABLE_FREQUENCIES.includes(frequency)) {
+ return rrule
+ }
+ return buildSummary(parseRRuleToState(rrule), startsAt, timezone)
+}
+
export function parseNaturalLanguage(text: string): ScheduleState | null {
const trimmed = text.trim().toLowerCase()
if (!trimmed || !trimmed.includes('every')) {
diff --git a/products/workflows/frontend/Workflows/workflowLogic.schedule.test.ts b/products/workflows/frontend/Workflows/workflowLogic.schedule.test.ts
index f3825b508398..89991beb8949 100644
--- a/products/workflows/frontend/Workflows/workflowLogic.schedule.test.ts
+++ b/products/workflows/frontend/Workflows/workflowLogic.schedule.test.ts
@@ -1,8 +1,9 @@
import { expectLogic } from 'kea-test-utils'
+import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
-import { DEFAULT_STATE, ONE_TIME_RRULE } from './hogflows/steps/components/rrule-helpers'
+import { DEFAULT_STATE, ONE_TIME_RRULE, parseRRuleToState } from './hogflows/steps/components/rrule-helpers'
import { HogFlowSchedule } from './hogflows/types'
import { workflowLogic } from './workflowLogic'
@@ -348,4 +349,152 @@ describe('workflowLogic schedule reducers', () => {
})
})
})
+
+ describe('removing one of several schedules', () => {
+ const FLOW_ID = 'wf-schedule-list'
+ let deleted: string[]
+
+ beforeEach(() => {
+ deleted = []
+ useMocks({
+ get: {
+ '/api/environments/:team_id/hog_flows/:id/': { id: FLOW_ID, name: 'Listed', actions: [] },
+ '/api/projects/:team_id/hog_function_templates/': { results: [], count: 0 },
+ },
+ delete: {
+ '/api/projects/:project_id/hog_flows/:id/schedules/:schedule_id/': (req: any) => {
+ deleted.push(req.params.schedule_id as string)
+ return [204, {}]
+ },
+ },
+ })
+ logic.unmount()
+ logic = workflowLogic({ id: FLOW_ID })
+ logic.mount()
+ })
+
+ it('drops only the schedule that was removed', async () => {
+ logic.actions.setSchedules([makeSchedule(), makeSchedule({ id: 'schedule-2', rrule: ONE_TIME_RRULE })])
+
+ await expectLogic(logic, () => {
+ logic.actions.deleteSchedule('schedule-2')
+ }).toFinishAllListeners()
+
+ expect(deleted).toEqual(['schedule-2'])
+ expect(logic.values.schedules.map((s) => s.id)).toEqual(['schedule-1'])
+ })
+
+ it('edits the schedule the author picks, not the first one', async () => {
+ const second = makeSchedule({ id: 'schedule-2', rrule: 'FREQ=DAILY;INTERVAL=3' })
+ logic.actions.setSchedules([makeSchedule(), second])
+
+ await expectLogic(logic, () => {
+ logic.actions.selectSchedule(second)
+ }).toMatchValues({
+ selectedScheduleId: 'schedule-2',
+ scheduleState: expect.objectContaining({ frequency: 'daily', interval: 3 }),
+ })
+
+ expect(logic.values.currentSchedule?.id).toBe('schedule-2')
+ })
+
+ it('keeps editing the picked schedule when the list reloads', async () => {
+ const second = makeSchedule({ id: 'schedule-2', rrule: 'FREQ=DAILY;INTERVAL=3' })
+ logic.actions.setSchedules([makeSchedule(), second])
+ logic.actions.selectSchedule(second)
+
+ await expectLogic(logic, () => {
+ logic.actions.setSchedules([makeSchedule(), second])
+ }).toFinishAllListeners()
+
+ expect(logic.values.currentSchedule?.id).toBe('schedule-2')
+ expect(logic.values.scheduleState).toEqual(expect.objectContaining({ frequency: 'daily', interval: 3 }))
+ })
+
+ it('adds a schedule and moves the editor onto it', async () => {
+ useMocks({
+ post: {
+ '/api/projects/:project_id/hog_flows/:id/schedules/': () => [
+ 201,
+ { id: 'schedule-new', rrule: WEEKLY_MONDAY_RRULE, starts_at: STARTS_AT, timezone: 'UTC' },
+ ],
+ },
+ })
+ logic.actions.setSchedules([makeSchedule()])
+
+ await expectLogic(logic, () => {
+ logic.actions.addSchedule()
+ }).toFinishAllListeners()
+
+ expect(logic.values.schedules.map((s) => s.id)).toEqual(['schedule-1', 'schedule-new'])
+ expect(logic.values.currentSchedule?.id).toBe('schedule-new')
+ })
+
+ it('keeps unsaved picker edits when a different schedule is removed', async () => {
+ logic.actions.setSchedules([makeSchedule(), makeSchedule({ id: 'schedule-2' })])
+ logic.actions.setScheduleState({ ...DEFAULT_STATE, frequency: 'daily', interval: 4 })
+
+ await expectLogic(logic, () => {
+ logic.actions.deleteSchedule('schedule-2')
+ }).toFinishAllListeners()
+
+ expect(logic.values.scheduleState).toEqual(expect.objectContaining({ frequency: 'daily', interval: 4 }))
+ expect(logic.values.pendingSchedule).not.toBe(false)
+ })
+
+ it('stages no edits against the schedule picked while the removal was in flight', async () => {
+ const second = makeSchedule({ id: 'schedule-2' })
+ logic.actions.setSchedules([makeSchedule(), second, makeSchedule({ id: 'schedule-3' })])
+ logic.actions.setScheduleState({ ...DEFAULT_STATE, frequency: 'daily', interval: 4 })
+
+ await expectLogic(logic, () => {
+ logic.actions.deleteSchedule('schedule-3')
+ logic.actions.selectSchedule(second)
+ }).toFinishAllListeners()
+
+ expect(logic.values.currentSchedule?.id).toBe('schedule-2')
+ expect(logic.values.scheduleState).toEqual(parseRRuleToState(WEEKLY_MONDAY_RRULE))
+ })
+
+ it('ignores a second add while the first is still in flight', async () => {
+ let creates = 0
+ useMocks({
+ post: {
+ '/api/projects/:project_id/hog_flows/:id/schedules/': () => {
+ creates += 1
+ return [
+ 201,
+ {
+ id: `schedule-new-${creates}`,
+ rrule: WEEKLY_MONDAY_RRULE,
+ starts_at: STARTS_AT,
+ timezone: 'UTC',
+ },
+ ]
+ },
+ },
+ })
+ logic.actions.setSchedules([makeSchedule()])
+
+ await expectLogic(logic, () => {
+ logic.actions.addSchedule()
+ logic.actions.addSchedule()
+ }).toFinishAllListeners()
+
+ expect(creates).toBe(1)
+ })
+
+ it('keeps the schedule listed when the delete fails', async () => {
+ useMocks({
+ delete: { '/api/projects/:project_id/hog_flows/:id/schedules/:schedule_id/': () => [500, {}] },
+ })
+ logic.actions.setSchedules([makeSchedule(), makeSchedule({ id: 'schedule-2' })])
+
+ await expectLogic(logic, () => {
+ logic.actions.deleteSchedule('schedule-2')
+ }).toFinishAllListeners()
+
+ expect(logic.values.schedules.map((s) => s.id)).toEqual(['schedule-1', 'schedule-2'])
+ })
+ })
})
diff --git a/products/workflows/frontend/Workflows/workflowLogic.ts b/products/workflows/frontend/Workflows/workflowLogic.ts
index a52d570e765a..5eb0536c19e9 100644
--- a/products/workflows/frontend/Workflows/workflowLogic.ts
+++ b/products/workflows/frontend/Workflows/workflowLogic.ts
@@ -28,7 +28,12 @@ import { userLogic } from 'scenes/userLogic'
import { AccessControlLevel, HogFunctionTemplateType, IntegrationType } from '~/types'
import { resourceEditedLogic } from 'products/notifications/frontend/resourceEditedLogic'
-import { hogFlowsCreate, hogFlowsResumeEmailSending } from 'products/workflows/frontend/generated/api'
+import {
+ hogFlowsCreate,
+ hogFlowsResumeEmailSending,
+ hogFlowsSchedulesCreate,
+ hogFlowsSchedulesDestroy,
+} from 'products/workflows/frontend/generated/api'
import type { EmailDraftRequestApi } from 'products/workflows/frontend/generated/api.schemas'
import type { ResourceEditedEvent, UserBasicType, UserType } from '../../../../frontend/src/types'
@@ -244,6 +249,9 @@ function pickWorkflowEdits(workflow: HogFlow): Partial<HogFlow> {
interface SaveContext {
initiatedByAutoSave: boolean
pendingSchedule: { rrule: string; starts_at: string; timezone?: string } | null | false
+ // The schedule the pending change belongs to. The author can pick another row while the save
+ // is in flight, and the write must still land on the schedule they edited.
+ scheduleId: string | undefined
// Existing workflows to move to broadcasts once this save creates a broadcast.
moveToBroadcastIds: string[]
// How many of them moved. The save sets it before it finishes.
@@ -276,6 +284,7 @@ export interface workflowLogicValues {
currentProjectId: number | null // projectLogic
user: UserType | null // userLogic
actionValidationErrorsById: Record<string, HogFlowActionValidationResult | null>
+ addingSchedule: boolean
aiEmailDraft: AiEmailDraftResult | null
aiEmailDraftApplied: boolean
aiEmailDraftLoading: boolean
@@ -327,6 +336,7 @@ export interface workflowLogicValues {
scheduleState: ScheduleState
scheduleTimezone: string
schedules: HogFlowSchedule[]
+ selectedScheduleId: string | null
showDraftActions: boolean
showWorkflowErrors: boolean
statusToggleDisabledReason: string | undefined
@@ -355,6 +365,9 @@ export interface workflowLogicActions {
archiveWorkflow: (workflow: HogFlow) => {
workflow: HogFlow
} // workflowsLogic
+ addSchedule: () => {
+ value: true
+ }
autoSaveWorkflow: () => {
value: true
}
@@ -370,6 +383,12 @@ export interface workflowLogicActions {
confirmResumeEmailSending: () => {
value: true
}
+ deleteSchedule: (scheduleId: string) => {
+ scheduleId: string
+ }
+ deleteScheduleFailure: (scheduleId: string) => {
+ scheduleId: string
+ }
discardChanges: () => {
value: true
}
@@ -2555,6 +2574,12 @@ export interface workflowLogicActions {
originalWorkflow: HogFlow
payload?: HogFlow
}
+ selectSchedule: (schedule: HogFlowSchedule) => {
+ schedule: HogFlowSchedule
+ }
+ setAddingSchedule: (adding: boolean) => {
+ adding: boolean
+ }
setAutoSaveEnabled: (enabled: boolean) => {
enabled: boolean
}
@@ -3007,7 +3032,7 @@ export interface workflowLogicMeta {
) => AiEmailDraftStatusProps | null
logicProps: (arg: WorkflowLogicProps) => WorkflowLogicProps
workflowUserAccessLevel: (originalWorkflow: HogFlow | null) => AccessControlLevel | null
- currentSchedule: (schedules: HogFlowSchedule[]) => HogFlowSchedule | null
+ currentSchedule: (schedules: HogFlowSchedule[], selectedScheduleId: string | null) => HogFlowSchedule | null
pendingSchedule: (
currentSchedule: HogFlowSchedule | null,
scheduleState: ScheduleState,
@@ -3298,6 +3323,11 @@ export const workflowLogic = kea<workflowLogicType>([
variables,
filters,
}),
+ addSchedule: true,
+ setAddingSchedule: (adding: boolean) => ({ adding }),
+ selectSchedule: (schedule: HogFlowSchedule) => ({ schedule }),
+ deleteSchedule: (scheduleId: string) => ({ scheduleId }),
+ deleteScheduleFailure: (scheduleId: string) => ({ scheduleId }),
discardChanges: true,
duplicate: true,
autoSaveWorkflow: true,
@@ -3389,6 +3419,7 @@ export const workflowLogic = kea<workflowLogicType>([
initiatedByAutoSave,
// A status change keeps schedule edits unsaved, like the other edits in the form.
pendingSchedule: keepsFormEdits ? false : values.pendingSchedule,
+ scheduleId: values.currentSchedule?.id,
moveToBroadcastIds: (cache.nextSaveMovesWorkflowIds ?? []) as string[],
keepsFormEdits,
}
@@ -3646,6 +3677,20 @@ export const workflowLogic = kea<workflowLogicType>([
setSchedules: (_, { schedules }) => schedules,
},
],
+ addingSchedule: [
+ false as boolean,
+ {
+ setAddingSchedule: (_, { adding }) => adding,
+ },
+ ],
+ selectedScheduleId: [
+ null as string | null,
+ {
+ selectSchedule: (_, { schedule }) => schedule.id,
+ setSchedules: (selectedId, { schedules }) =>
+ schedules.some((schedule) => schedule.id === selectedId) ? selectedId : (schedules[0]?.id ?? null),
+ },
+ ],
scheduleState: [
{ ...DEFAULT_STATE } as ScheduleState,
{
@@ -3658,6 +3703,8 @@ export const workflowLogic = kea<workflowLogicType>([
}
return { ...DEFAULT_STATE }
},
+ selectSchedule: (_, { schedule }) =>
+ isOneTimeSchedule(schedule.rrule) ? { ...DEFAULT_STATE } : parseRRuleToState(schedule.rrule),
},
],
scheduleStartsAt: [
@@ -3666,6 +3713,7 @@ export const workflowLogic = kea<workflowLogicType>([
setScheduleStartsAt: (_, { startsAt }) => startsAt,
restoreScheduleEdits: (_, { edits }) => edits.scheduleStartsAt,
setSchedules: (_, { schedules }) => schedules[0]?.starts_at ?? null,
+ selectSchedule: (_, { schedule }) => schedule.starts_at,
},
],
scheduleTimezone: [
@@ -3674,6 +3722,7 @@ export const workflowLogic = kea<workflowLogicType>([
setScheduleTimezone: (_, { timezone }) => timezone,
restoreScheduleEdits: (_, { edits }) => edits.scheduleTimezone,
setSchedules: (_, { schedules }) => schedules[0]?.timezone ?? dayjs.tz.guess(),
+ selectSchedule: (_, { schedule }) => schedule.timezone ?? dayjs.tz.guess(),
},
],
isScheduleRepeating: [
@@ -3685,6 +3734,7 @@ export const workflowLogic = kea<workflowLogicType>([
const schedule = schedules[0]
return !!schedule && !isOneTimeSchedule(schedule.rrule)
},
+ selectSchedule: (_, { schedule }) => !isOneTimeSchedule(schedule.rrule),
},
],
// Tracks which configuration methods the user touched during the current editing
@@ -3826,8 +3876,9 @@ export const workflowLogic = kea<workflowLogicType>([
originalWorkflow?.user_access_level ?? null,
],
currentSchedule: [
- (s) => [s.schedules],
- (schedules: HogFlowSchedule[]): HogFlowSchedule | null => schedules[0] ?? null,
+ (s) => [s.schedules, s.selectedScheduleId],
+ (schedules: HogFlowSchedule[], selectedScheduleId: string | null): HogFlowSchedule | null =>
+ schedules.find((schedule) => schedule.id === selectedScheduleId) ?? schedules[0] ?? null,
],
pendingSchedule: [
(s) => [s.currentSchedule, s.scheduleState, s.scheduleStartsAt, s.scheduleTimezone, s.isScheduleRepeating],
@@ -4503,7 +4554,7 @@ export const workflowLogic = kea<workflowLogicType>([
// Read the schedule this save carried. An auto-save that landed first has already
// reset the reducers, so the live value no longer describes what the user staged.
const pendingSchedule = saveContext ? saveContext.pendingSchedule : values.pendingSchedule
- const existingScheduleId = values.currentSchedule?.id
+ const existingScheduleId = saveContext ? saveContext.scheduleId : values.currentSchedule?.id
const hasScheduleChanges = pendingSchedule !== false && !!workflowId
if (hasScheduleChanges) {
@@ -4652,6 +4703,68 @@ export const workflowLogic = kea<workflowLogicType>([
}
actions.replayDeferredResourceEdited()
},
+ addSchedule: async () => {
+ const workflowId = props.id
+ if (!workflowId || workflowId === 'new' || values.addingSchedule) {
+ return
+ }
+ actions.setAddingSchedule(true)
+ // A fan-out varies one field of a cadence, so a new schedule copies the selected one.
+ const startsAt = values.currentSchedule?.starts_at ?? dayjs().add(1, 'hour').startOf('hour').toISOString()
+ try {
+ const created = await hogFlowsSchedulesCreate(String(ApiConfig.getCurrentTeamId()), workflowId, {
+ rrule: values.currentSchedule?.rrule ?? stateToRRule(DEFAULT_STATE, startsAt),
+ starts_at: startsAt,
+ timezone: values.currentSchedule?.timezone ?? dayjs.tz.guess(),
+ } as never)
+ const schedule = created as unknown as HogFlowSchedule
+ actions.setSchedules([...values.schedules, schedule])
+ actions.selectSchedule(schedule)
+ } catch (e) {
+ console.error('Failed to add schedule', e)
+ lemonToast.error('Could not add a schedule')
+ } finally {
+ actions.setAddingSchedule(false)
+ }
+ },
+ setSchedules: ({ schedules }) => {
+ // The editor reducers rebaseline from the first schedule, so a selection on any other
+ // one has to reapply itself or the picker edits a schedule it does not show.
+ const selected = schedules.find((schedule) => schedule.id === values.selectedScheduleId)
+ if (selected && selected.id !== schedules[0]?.id) {
+ actions.selectSchedule(selected)
+ }
+ },
+ deleteSchedule: async ({ scheduleId }) => {
+ const workflowId = props.id
+ if (!workflowId || workflowId === 'new') {
+ return
+ }
+ // setSchedules rebaselines the picker, so edits to a surviving schedule go back after.
+ const editedScheduleId = values.currentSchedule?.id
+ const stagedEdits: ScheduleEdits | null =
+ values.pendingSchedule !== false && editedScheduleId !== scheduleId
+ ? {
+ scheduleState: values.scheduleState,
+ scheduleStartsAt: values.scheduleStartsAt,
+ scheduleTimezone: values.scheduleTimezone,
+ isScheduleRepeating: values.isScheduleRepeating,
+ scheduleConfigSources: values.scheduleConfigSources,
+ }
+ : null
+ try {
+ await hogFlowsSchedulesDestroy(String(ApiConfig.getCurrentTeamId()), workflowId, scheduleId)
+ actions.setSchedules(values.schedules.filter((schedule) => schedule.id !== scheduleId))
+ if (stagedEdits && values.currentSchedule?.id === editedScheduleId) {
+ actions.restoreScheduleEdits(stagedEdits)
+ }
+ lemonToast.success('Schedule removed')
+ } catch (e) {
+ console.error('Failed to remove schedule', e)
+ actions.deleteScheduleFailure(scheduleId)
+ lemonToast.error('Could not remove the schedule')
+ }
+ },
discardChanges: () => {
if (!values.originalWorkflow) {
return