: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(flags): add a timeline of upcoming scheduled changes (#87844)
James Gill7d0734ff1774
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 29d174f93311..7b630355cd33 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6544,6 +6544,14 @@ snapshots:hash: v1.k794b7964.b21df130430a104352e31173ae34feb16146f03d0688631d35f78052114fd3e7.GA0QgvUydkp96bBYC1RIiHsKN8O6Z_3nX1PXnfaBgeAscenes-app-feature-flags-new-feature-flag-menu--default--light:hash: v1.k794b7964.c58d12ddf9499563916bb71f41ff70dce9db471379ef2215c8b57a0ac88aa76c.jl03AgPo8iB46wC9k3xNkQwobb5SLJcSwYnOphJUt8Y+ scenes-app-feature-flags-schedule-timeline--rollout-ramp--dark:+ hash: v1.k794b7964.2953688108a239d2ec1fed7e9536ba4fe608d7894111f5eeaf6f8a47339d8aff.sgkcFh_IvnLvMdJI7mdrIZEMQFbXUeRMTQxiWJUpalU+ scenes-app-feature-flags-schedule-timeline--rollout-ramp--light:+ hash: v1.k794b7964.0785f69304e857d326d3f0b6fd1d080b98693832830dc27efee8962998071f21.1PukOHY28udTttP75f7GWVgGOqw5NVX8UynvDughGJo+ scenes-app-feature-flags-schedule-timeline--single-occurrence--dark:+ hash: v1.k794b7964.5f56b26c9731f7507c03e0ca3830b20dc9c54e0af644d969931a942054969403.gZwCiTKCj8cQ8GfXJIV5uUG058HQ5g5M4Z2qMVNYaHs+ scenes-app-feature-flags-schedule-timeline--single-occurrence--light:+ hash: v1.k794b7964.b67b362406d51b0c3e8481fef9b7c0c79ce79ba6a46112f2d451c6e297ef64e8.LTGULnRrrYhMIv2FNWKFM3G32QTZ0XRPNLskis8YX0Qscenes-app-features--features-list--dark:hash: v1.k794b7964.0c79c9bfef37ec5ccee5d871ad0849770f5b1c1b5c6ea92b8eddca703d035c31.g_X-ujymWdXk9iFUWXQgNNFUJmo3xzl_EZymFteHpBEscenes-app-features--features-list--light:diff --git a/frontend/src/scenes/feature-flags/FeatureFlagSchedule.test.tsx b/frontend/src/scenes/feature-flags/FeatureFlagSchedule.test.tsxindex 01fbc9776577..a9abf1044579 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagSchedule.test.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagSchedule.test.tsx@@ -1,4 +1,4 @@-import { MOCK_DEFAULT_BASIC_USER, MOCK_DEFAULT_PROJECT } from 'lib/api.mock'+import { MOCK_DEFAULT_PROJECT } from 'lib/api.mock'import '@testing-library/jest-dom'@@ -12,7 +12,6 @@ import { initKeaTests } from '~/test/init'import {FeatureFlagType,RecurrenceInterval,- ScheduledChangeModels,ScheduledChangeOperationType,ScheduledChangeRequestState,ScheduledChangeType,@@ -20,6 +19,7 @@ import {import { NEW_FLAG, featureFlagLogic } from './featureFlagLogic'import FeatureFlagSchedule from './FeatureFlagSchedule'+import { makeScheduledChange } from './makeScheduledChange'jest.mock('./FeatureFlagReleaseConditionsCollapsible', () => ({FeatureFlagReleaseConditionsCollapsible: () => null,@@ -159,45 +159,63 @@ describe('FeatureFlagSchedule', () => {expect(screen.getByText(new RegExp(expectedText))).toBeInTheDocument()})- describe('approval visibility', () => {- const makeScheduledChange = (overrides: Partial<ScheduledChangeType>): ScheduledChangeType => ({- id: 1,- team_id: MOCK_DEFAULT_PROJECT.id,- record_id: 1,- model_name: ScheduledChangeModels.FeatureFlag,- payload: { operation: ScheduledChangeOperationType.UpdateStatus, value: true },- scheduled_at: '2030-01-01T00:00:00Z',- executed_at: null,- failure_reason: null,- created_at: '2026-01-01T00:00:00Z',- created_by: MOCK_DEFAULT_BASIC_USER,- is_recurring: false,- recurrence_interval: null,- cron_expression: null,- last_executed_at: null,- end_date: null,- change_request: null,- ...overrides,+ // useMocks trips the hooks naming lint inside named helpers, so each test registers+ // its own mock before calling this.+ const renderWithSchedules = (): void => {+ renderSchedule(+ buildFeatureFlag({ active: false, rolloutPercentage: 100 }),+ ScheduledChangeOperationType.UpdateStatus+ )+ act(() => {+ featureFlagLogic(logicProps).actions.loadScheduledChanges()})+ }- // useMocks trips the hooks naming lint inside named helpers, so each test registers- // its own mock before calling this.- const renderWithSchedules = (): void => {- renderSchedule(- buildFeatureFlag({ active: false, rolloutPercentage: 100 }),- ScheduledChangeOperationType.UpdateStatus- )- act(() => {- featureFlagLogic(logicProps).actions.loadScheduledChanges()- })- }+ const schedulesMock = (+ schedules: ScheduledChangeType[]+ ): Record<string, () => [number, { results: ScheduledChangeType[] }]> => ({+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/scheduled_changes`]: () => [200, { results: schedules }],+ })- const schedulesMock = (- schedules: ScheduledChangeType[]- ): Record<string, () => [number, { results: ScheduledChangeType[] }]> => ({- [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/scheduled_changes`]: () => [200, { results: schedules }],+ it('gives a viewer without edit rights the banner and no way into the form', async () => {+ // Three separate conditions gate what this user sees: the banner, the collapsed-form+ // button, and the form itself. A regression in any one of them hands a viewer a form whose+ // submit the API rejects.+ useMocks({ get: schedulesMock([makeScheduledChange({})]) })+ const featureFlag = buildFeatureFlag({ active: false, rolloutPercentage: 100 })+ renderWithSchedules()+ // One schedule collapses the form, so the button's own can_edit check is what hides it here.+ await screen.findByText('Active & upcoming')+ // Set can_edit last. The mount loads a flag of its own, and that response would overwrite+ // an earlier value during the await above.+ act(() => {+ featureFlagLogic(logicProps).actions.setFeatureFlag({ ...featureFlag, can_edit: false })})+ expect(screen.getByText(/You don't have the necessary permissions/)).toBeInTheDocument()+ expect(document.querySelector('[data-attr="feature-flag-open-schedule-form"]')).not.toBeInTheDocument()+ expect(+ screen.queryByText('Automatically change flag properties at a future point in time.')+ ).not.toBeInTheDocument()+ })++ it('collapses the creation form behind a button when schedules exist, and toggles via the button and close', async () => {+ useMocks({ get: schedulesMock([makeScheduledChange({})]) })+ renderWithSchedules()++ const formHint = 'Automatically change flag properties at a future point in time.'+ await screen.findByText('Active & upcoming')+ expect(screen.queryByText(formHint)).not.toBeInTheDocument()++ fireEvent.click(document.querySelector('[data-attr="feature-flag-open-schedule-form"]')!)+ expect(screen.getByText(formHint)).toBeInTheDocument()++ fireEvent.click(document.querySelector('[data-attr="feature-flag-close-schedule-form"]')!)+ expect(screen.queryByText(formHint)).not.toBeInTheDocument()+ expect(document.querySelector('[data-attr="feature-flag-open-schedule-form"]')).toBeInTheDocument()+ })++ describe('approval visibility', () => {it('shows the Needs approval tag and an approval link for a pending gated schedule', async () => {useMocks({get: schedulesMock([diff --git a/frontend/src/scenes/feature-flags/FeatureFlagSchedule.tsx b/frontend/src/scenes/feature-flags/FeatureFlagSchedule.tsxindex 3107c8b9bdeb..f056e47244e3 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagSchedule.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagSchedule.tsx@@ -7,8 +7,10 @@ import {IconPause,IconPencil,IconPlay,+ IconPlus,IconToggle,IconTrash,+ IconX,} from '@posthog/icons'import {LemonBanner,@@ -18,6 +20,7 @@ import {LemonInput,LemonModal,LemonSelect,+ LemonSkeleton,LemonSwitch,LemonTag,LemonTagType,@@ -57,6 +60,8 @@ import { FeatureFlagReleaseConditionsCollapsible } from './FeatureFlagReleaseConimport { groupFilters } from './FeatureFlags'import { featureFlagScheduleEditLogic } from './featureFlagScheduleEditLogic'import { FeatureFlagVariantsForm } from './FeatureFlagVariantsForm'+import { isSchedulePaused, maxRolloutPercentage } from './scheduleOccurrences'+import { ScheduleTimeline } from './ScheduleTimeline'export const DAYJS_FORMAT = 'MMMM DD, YYYY h:mm A'@@ -87,11 +92,6 @@ function ScheduleTimezoneHint(): JSX.Element | null {type AggregationLabel = (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun-/** A recurring schedule that has been paused retains its recurrence config but has is_recurring=false. */-function isSchedulePaused(sc: ScheduledChangeType): boolean {- return !sc.is_recurring && (!!sc.recurrence_interval || !!sc.cron_expression)-}-function getScheduledVariantsPayloads(featureFlag: FeatureFlagType,schedulePayload: { variants?: MultivariateFlagVariant[]; payloads?: Record<string, any>; filters?: any }@@ -457,6 +457,9 @@ export default function FeatureFlagSchedule(): JSX.Element {customPairDisableCronPreview,canCreatePairedSchedule,hasEarlyAccessFeatures,+ scheduleTimelineOccurrences,+ scheduleFormState,+ scheduleFormCollapsible,} = useValues(featureFlagLogic)const {deleteScheduledChange,@@ -472,6 +475,7 @@ export default function FeatureFlagSchedule(): JSX.Element {setSchedulePreset,setCustomPairCron,createPairedSchedule,+ setScheduleFormExpanded,} = useActions(featureFlagLogic)const {isEditOpen,@@ -552,16 +556,67 @@ export default function FeatureFlagSchedule(): JSX.Element {(opt) => opt.value !== ScheduledChangeOperationType.UpdateVariants || featureFlag.filters.multivariate)+ const showCollapsedFormButton = featureFlag.can_edit && scheduleFormState === 'collapsed'+return (<div className="flex flex-col gap-4">+ {/* Plan header: what-happens-next timeline, plus the schedule action while the form is collapsed */}+ {scheduleFormState === 'loading' ? (+ <LemonSkeleton className="h-10" />+ ) : (+ (scheduleTimelineOccurrences.length > 0 || showCollapsedFormButton) && (+ <div className="flex flex-col gap-1">+ <div className="flex items-center gap-4 min-h-8">+ {scheduleTimelineOccurrences.length > 0 && (+ <h3 className="font-semibold text-base m-0">What happens next</h3>+ )}+ {showCollapsedFormButton && (+ <LemonButton+ className="ml-auto"+ type="primary"+ icon={<IconPlus />}+ onClick={() => setScheduleFormExpanded(true)}+ data-attr="feature-flag-open-schedule-form"+ >+ Schedule a change+ </LemonButton>+ )}+ </div>+ <ScheduleTimeline+ occurrences={scheduleTimelineOccurrences}+ currentRolloutPercentage={maxRolloutPercentage(featureFlag.filters.groups)}+ timezone={scheduleTimezone}+ />+ </div>+ )+ )}++ {!featureFlag.can_edit && (+ <LemonBanner type="info">+ You don't have the necessary permissions to schedule changes to this flag. Contact your+ administrator to request editing rights.+ </LemonBanner>+ )}+{/* Creation form */}- {featureFlag.can_edit ? (+ {featureFlag.can_edit && scheduleFormState === 'expanded' && (<div className="rounded border p-4 bg-bg-light flex flex-col gap-4">- <div>- <h3 className="font-semibold text-base mb-1">Schedule a change</h3>- <span className="text-sm text-muted">- Automatically change flag properties at a future point in time.- </span>+ <div className="flex items-start justify-between gap-2">+ <div>+ <h3 className="font-semibold text-base mb-1">Schedule a change</h3>+ <span className="text-sm text-muted">+ Automatically change flag properties at a future point in time.+ </span>+ </div>+ {scheduleFormCollapsible && (+ <LemonButton+ size="small"+ icon={<IconX />}+ tooltip="Close"+ onClick={() => setScheduleFormExpanded(false)}+ data-attr="feature-flag-close-schedule-form"+ />+ )}</div>{/* Row 1: Change type + Date/Repeat controls */}@@ -986,11 +1041,6 @@ export default function FeatureFlagSchedule(): JSX.Element {)}</div></div>- ) : (- <LemonBanner type="info">- You don't have the necessary permissions to schedule changes to this flag. Contact your- administrator to request editing rights.- </LemonBanner>)}{/* Schedule list */}diff --git a/frontend/src/scenes/feature-flags/ScheduleTimeline.stories.tsx b/frontend/src/scenes/feature-flags/ScheduleTimeline.stories.tsxnew file mode 100644index 000000000000..4c926ac9594d--- /dev/null+++ b/frontend/src/scenes/feature-flags/ScheduleTimeline.stories.tsx@@ -0,0 +1,94 @@+import { Meta } from '@storybook/react'++import { dayjs } from 'lib/dayjs'++import { ScheduledChangeOperationType, ScheduledChangePayload, ScheduledChangeRequestState } from '~/types'++import { makeScheduledChange } from './makeScheduledChange'+import { ScheduleOccurrence, ScheduleProjectedState } from './scheduleOccurrences'+import { ScheduleTimeline } from './ScheduleTimeline'++const MOCK_NOW = '2026-08-24T12:00:00Z'++const meta: Meta<typeof ScheduleTimeline> = {+ title: 'Scenes-App/Feature Flags/Schedule Timeline',+ component: ScheduleTimeline,+ parameters: { mockDate: MOCK_NOW },+}+export default meta++function occurrence(+ daysFromNow: number,+ payload: ScheduledChangePayload,+ projected: ScheduleProjectedState,+ needsApproval = false+): ScheduleOccurrence {+ const timestamp = dayjs(MOCK_NOW).add(daysFromNow, 'day').toISOString()+ return {+ timestamp,+ operation: payload.operation,+ schedule: makeScheduledChange({+ payload,+ scheduled_at: timestamp,+ change_request: needsApproval ? { id: 'cr-1', state: ScheduledChangeRequestState.Pending } : null,+ }),+ projected,+ addedRolloutPercentage:+ payload.operation === ScheduledChangeOperationType.AddReleaseCondition ? projected.rolloutPercentage : null,+ needsApproval,+ }+}++function rolloutStep(daysFromNow: number, rollout: number, needsApproval = false): ScheduleOccurrence {+ return occurrence(+ daysFromNow,+ {+ operation: ScheduledChangeOperationType.AddReleaseCondition,+ value: { groups: [{ properties: [], rollout_percentage: rollout, variant: null }] },+ },+ { active: true, rolloutPercentage: rollout, variantCount: null },+ needsApproval+ )+}++export function RolloutRamp(): JSX.Element {+ return (+ <div className="max-w-3xl">+ <ScheduleTimeline+ occurrences={[+ rolloutStep(1, 25),+ rolloutStep(3, 50),+ occurrence(+ 4,+ { operation: ScheduledChangeOperationType.UpdateVariants, value: { variants: [] } },+ { active: true, rolloutPercentage: 50, variantCount: 3 }+ ),+ rolloutStep(5, 75, true),+ occurrence(+ 7,+ { operation: ScheduledChangeOperationType.UpdateStatus, value: false },+ { active: false, rolloutPercentage: 75, variantCount: 3 }+ ),+ ]}+ currentRolloutPercentage={10}+ timezone="UTC"+ />+ </div>+ )+}++export function SingleOccurrence(): JSX.Element {+ return (+ <ScheduleTimeline+ occurrences={[+ occurrence(+ 2,+ { operation: ScheduledChangeOperationType.UpdateStatus, value: true },+ { active: true, rolloutPercentage: 100, variantCount: null }+ ),+ ]}+ currentRolloutPercentage={100}+ timezone="UTC"+ />+ )+}diff --git a/frontend/src/scenes/feature-flags/ScheduleTimeline.test.tsx b/frontend/src/scenes/feature-flags/ScheduleTimeline.test.tsxnew file mode 100644index 000000000000..9e97015fe7bb--- /dev/null+++ b/frontend/src/scenes/feature-flags/ScheduleTimeline.test.tsx@@ -0,0 +1,181 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen } from '@testing-library/react'++import { ScheduledChangeOperationType } from '~/types'++import { makeScheduledChange } from './makeScheduledChange'+import { ScheduleOccurrence } from './scheduleOccurrences'+import { ScheduleTimeline } from './ScheduleTimeline'++function occurrence(overrides: Partial<ScheduleOccurrence> = {}): ScheduleOccurrence {+ return {+ timestamp: '2099-08-26T10:22:00Z',+ operation: ScheduledChangeOperationType.UpdateStatus,+ schedule: makeScheduledChange({ scheduled_at: '2099-08-26T10:22:00Z' }),+ projected: { active: true, rolloutPercentage: 50, variantCount: null },+ addedRolloutPercentage: null,+ needsApproval: false,+ ...overrides,+ }+}++describe('ScheduleTimeline', () => {+ // The component reads the wall clock to place marks, so an unpinned clock leaves the fixed+ // fixture dates decades away and squashes every x onto the right edge.+ beforeAll(() => {+ jest.useFakeTimers()+ jest.setSystemTime(new Date('2099-08-25T10:22:00Z'))+ })++ afterAll(() => {+ jest.useRealTimers()+ })++ afterEach(() => {+ cleanup()+ })++ it('renders nothing for zero occurrences', () => {+ const { container } = render(<ScheduleTimeline occurrences={[]} currentRolloutPercentage={10} timezone="UTC" />)++ expect(container).toBeEmptyDOMElement()+ })++ it.each([+ { name: 'this year, without the year', overrides: {}, expected: 'Next: enabled on Aug 26, 10:22 AM' },+ {+ name: 'a later year, with the year',+ overrides: { timestamp: '2100-08-26T10:22:00Z' },+ expected: 'Next: enabled on Aug 26, 2100 10:22 AM',+ },+ {+ name: 'a variant change, with a verb',+ overrides: {+ operation: ScheduledChangeOperationType.UpdateVariants,+ projected: { active: true, rolloutPercentage: 50, variantCount: 3 },+ },+ expected: 'Next: switch to 3 variants on Aug 26, 10:22 AM',+ },+ ])('summarizes one occurrence without a chart: $name', ({ overrides, expected }) => {+ const { container } = render(+ <ScheduleTimeline occurrences={[occurrence(overrides)]} currentRolloutPercentage={10} timezone="UTC" />+ )++ expect(screen.getByText(expected)).toBeInTheDocument()+ expect(container.querySelector('svg')).not.toBeInTheDocument()+ })++ it('summarizes an added condition by its own rollout, not the projected max', () => {+ const addCondition = occurrence({+ operation: ScheduledChangeOperationType.AddReleaseCondition,+ addedRolloutPercentage: 10,+ // Projected max stays at an existing 100% condition set; the summary must not report it.+ projected: { active: true, rolloutPercentage: 100, variantCount: null },+ })+ render(<ScheduleTimeline occurrences={[addCondition]} currentRolloutPercentage={100} timezone="UTC" />)++ expect(screen.getByText('Next: add a condition at 10% rollout on Aug 26, 10:22 AM')).toBeInTheDocument()+ })++ it('renders the step chart for two or more occurrences', () => {+ const { container } = render(+ <ScheduleTimeline+ occurrences={[+ occurrence(),+ occurrence({+ timestamp: '2099-08-28T10:22:00Z',+ operation: ScheduledChangeOperationType.AddReleaseCondition,+ projected: { active: true, rolloutPercentage: 75, variantCount: null },+ }),+ ]}+ currentRolloutPercentage={10}+ timezone="UTC"+ />+ )++ expect(container.querySelector('svg')).toBeInTheDocument()+ expect(screen.queryByText(/^Next:/)).not.toBeInTheDocument()+ })++ it('dashes the jump of an approval-blocked step, and not the level before it', () => {+ const { container } = render(+ <ScheduleTimeline+ occurrences={[+ occurrence({+ operation: ScheduledChangeOperationType.AddReleaseCondition,+ projected: { active: true, rolloutPercentage: 50, variantCount: null },+ }),+ occurrence({+ timestamp: '2099-08-28T10:22:00Z',+ operation: ScheduledChangeOperationType.AddReleaseCondition,+ projected: { active: true, rolloutPercentage: 75, variantCount: null },+ needsApproval: true,+ }),+ ]}+ currentRolloutPercentage={25}+ timezone="UTC"+ />+ )++ const dashed = Array.from(container.querySelectorAll('path[stroke-dasharray]'))+ expect(dashed).toHaveLength(1)+ // A vertical jump only. A dashed horizontal run would claim the flag is not yet at the+ // level it already serves.+ expect(dashed[0].getAttribute('d')).toMatch(/^M [\d.]+ [\d.]+ V [\d.]+$/)+ expect(dashed[0].getAttribute('opacity')).toEqual('0.5')+ // Dash and opacity alone leave a touch user with no way to read the blocked state.+ expect(screen.getByText('75% (needs approval)')).toBeInTheDocument()+ // Nested in the marker's <g>, so RTL's ByTitle query does not reach it.+ expect(container.querySelector('g > title')?.textContent).toEqual('Needs approval')+ })++ it('labels a condition change whose projected rollout is unknown', () => {+ // A flag with no condition sets, and a payload that carries none either, leaves the+ // projection null. The step line cannot plot that, so the marker falls back to a label.+ render(+ <ScheduleTimeline+ occurrences={[+ occurrence(),+ occurrence({+ timestamp: '2099-08-28T10:22:00Z',+ operation: ScheduledChangeOperationType.AddReleaseCondition,+ projected: { active: true, rolloutPercentage: null, variantCount: null },+ }),+ ]}+ currentRolloutPercentage={null}+ timezone="UTC"+ />+ )++ expect(screen.getByText('Condition')).toBeInTheDocument()+ expect(screen.queryByText('0 variants')).not.toBeInTheDocument()+ })++ it('exposes the plan and a focus stop for a user without a mouse', () => {+ const { container } = render(+ <ScheduleTimeline+ occurrences={[+ occurrence(),+ occurrence({+ timestamp: '2099-08-28T10:22:00Z',+ operation: ScheduledChangeOperationType.AddReleaseCondition,+ addedRolloutPercentage: 75,+ projected: { active: true, rolloutPercentage: 75, variantCount: null },+ needsApproval: true,+ }),+ ]}+ currentRolloutPercentage={25}+ timezone="UTC"+ />+ )++ // The region scrolls below 600px, and a plain div with overflow takes no arrow keys.+ expect(container.querySelector('[data-attr="feature-flag-schedule-timeline"]')).toHaveAttribute('tabindex', '0')+ // role="img" hides every mark inside the chart, so this label is all a screen reader gets.+ expect(container.querySelector('svg')).toHaveAttribute(+ 'aria-label',+ 'Timeline of 2 upcoming scheduled changes: enabled on Aug 26, 10:22 AM, then add a condition at 75% rollout on Aug 28, 10:22 AM (needs approval)'+ )+ })+})diff --git a/frontend/src/scenes/feature-flags/ScheduleTimeline.tsx b/frontend/src/scenes/feature-flags/ScheduleTimeline.tsxnew file mode 100644index 000000000000..f0eac082bfef--- /dev/null+++ b/frontend/src/scenes/feature-flags/ScheduleTimeline.tsx@@ -0,0 +1,318 @@+import { Dayjs, dayjs } from 'lib/dayjs'+import { pluralize } from 'lib/utils/strings'++import { ScheduledChangeOperationType } from '~/types'++import { ScheduleOccurrence } from './scheduleOccurrences'++const WIDTH = 600+const HEIGHT = 140+const MARGIN = { top: 26, right: 14, bottom: 24, left: 34 }+const PLOT_WIDTH = WIDTH - MARGIN.left - MARGIN.right+const PLOT_HEIGHT = HEIGHT - MARGIN.top - MARGIN.bottom+const BASELINE_Y = MARGIN.top + PLOT_HEIGHT+/** Minimum viewBox-unit gap between time-axis labels before the later one is dropped. */+const TIME_LABEL_MIN_GAP = 40+/** Minimum viewBox-unit gap between top labels before the later one moves to the second lane. */+const TOP_LABEL_MIN_GAP = 40+/** How far the second lane sits above the first. Tuned against the 9px label size. */+const TOP_LABEL_LANE_OFFSET = 10++function describeOccurrence(occurrence: ScheduleOccurrence): string {+ const { operation, projected, addedRolloutPercentage } = occurrence+ if (operation === ScheduledChangeOperationType.UpdateStatus) {+ return projected.active ? 'enabled' : 'disabled'+ }+ if (operation === ScheduledChangeOperationType.AddReleaseCondition) {+ // Describe the condition this change adds, not the flag's projected max rollout: the change+ // appends a condition set, so an existing higher one would otherwise be misreported here.+ return addedRolloutPercentage !== null+ ? `add a condition at ${addedRolloutPercentage}% rollout`+ : 'add a condition'+ }+ return `switch to ${pluralize(occurrence.projected.variantCount ?? 0, 'variant')}`+}++function markerLabel(occurrence: ScheduleOccurrence): string {+ if (occurrence.operation === ScheduledChangeOperationType.UpdateStatus) {+ return occurrence.projected.active ? 'On' : 'Off'+ }+ // A condition change reaches this label only when its projected rollout is unknown, which the+ // step line cannot plot. Without this branch it borrows the variant wording and reads "0 variants".+ if (occurrence.operation === ScheduledChangeOperationType.AddReleaseCondition) {+ return 'Condition'+ }+ return pluralize(occurrence.projected.variantCount ?? 0, 'variant')+}++function formatOccurrenceTime(timestamp: string, timezone: string): string {+ const at = dayjs(timestamp).tz(timezone)+ const format = at.year() === dayjs().tz(timezone).year() ? 'MMM D, h:mm A' : 'MMM D, YYYY h:mm A'+ return at.format(format)+}++function relativeLabel(at: Dayjs, now: Dayjs): string {+ const minutes = at.diff(now, 'minute')+ if (minutes <= 0) {+ return 'now'+ }+ if (minutes < 60) {+ return `in ${minutes}m`+ }+ const hours = at.diff(now, 'hour')+ if (hours < 48) {+ return `in ${hours}h`+ }+ return `in ${at.diff(now, 'day')}d`+}++function yForRollout(rollout: number): number {+ return MARGIN.top + ((100 - rollout) * PLOT_HEIGHT) / 100+}++/** Where each occurrence's marks and labels land, resolved before render so the JSX map stays pure. */+interface OccurrenceLayout {+ x: number+ /** Null when the previous time label is too close. */+ timeLabel: string | null+ /** Alternates between two heights when top-lane markers land near the same x. */+ topLabelY: number+}++/**+ * Compact projection of upcoming scheduled changes: rollout percentage as a step line over time,+ * with status flips and variant updates as labeled markers on the same time axis.+ */+// Deliberately not memoized: the body reads the wall clock (`now` below) to place marks and write+// the relative time labels, so a shallow prop compare would freeze both until the occurrence list+// changes identity. Memoize once `now` arrives as a prop.+export function ScheduleTimeline({+ occurrences,+ currentRolloutPercentage,+ timezone,+}: {+ occurrences: ScheduleOccurrence[]+ /** The flag's max rollout across condition sets today, the step line's starting level. */+ currentRolloutPercentage: number | null+ timezone: string+}): JSX.Element | null {+ if (occurrences.length === 0) {+ return null+ }++ if (occurrences.length === 1) {+ const occurrence = occurrences[0]+ return (+ <div className="text-sm text-muted" data-attr="feature-flag-schedule-timeline">+ Next: {describeOccurrence(occurrence)} on {formatOccurrenceTime(occurrence.timestamp, timezone)}+ {occurrence.needsApproval ? ' (needs approval)' : ''}+ </div>+ )+ }++ const now = dayjs()+ const times = occurrences.map((occurrence) => dayjs(occurrence.timestamp))+ const spanMs = Math.max(times[times.length - 1].valueOf() - now.valueOf(), 1)+ const xFor = (at: Dayjs): number => {+ const fraction = Math.min(Math.max((at.valueOf() - now.valueOf()) / spanMs, 0), 1)+ return MARGIN.left + fraction * PLOT_WIDTH+ }++ const layouts: OccurrenceLayout[] = []+ let lastTimeLabelX = -Infinity+ let lastTopLabelX = -Infinity+ let topLabelLane = 0+ occurrences.forEach((occurrence, index) => {+ const x = xFor(times[index])+ const timeLabel = x - lastTimeLabelX >= TIME_LABEL_MIN_GAP ? relativeLabel(times[index], now) : null+ if (timeLabel) {+ lastTimeLabelX = x+ }+ let topLabelY = MARGIN.top - 8+ const onStepLine =+ occurrence.operation === ScheduledChangeOperationType.AddReleaseCondition &&+ occurrence.projected.rolloutPercentage !== null+ if (!onStepLine) {+ // Two lanes clear the common case of a pair landing together. Three or more markers+ // inside one gap still overlap, because the lane alternates rather than tracks every+ // occupied slot. The occurrence cap keeps that rare.+ topLabelLane = x - lastTopLabelX < TOP_LABEL_MIN_GAP ? 1 - topLabelLane : 0+ lastTopLabelX = x+ topLabelY -= topLabelLane * TOP_LABEL_LANE_OFFSET+ }+ layouts.push({ x, timeLabel, topLabelY })+ })++ // Step-line segments, split so an approval-blocked step dashes its jump and not its run.+ let previousX = MARGIN.left+ let previousRollout = currentRolloutPercentage+ const stepSegments: { path: string; blocked: boolean }[] = []+ occurrences.forEach((occurrence, index) => {+ const rollout = occurrence.projected.rolloutPercentage+ if (rollout === null) {+ return+ }+ const x = layouts[index].x+ const y = yForRollout(rollout)+ // A first occurrence with no level before it has nothing to draw yet, and the next+ // occurrence starts its run from here.+ if (previousRollout !== null) {+ const previousY = yForRollout(previousRollout)+ // The horizontal run holds the level the flag serves until this change fires, which is+ // certain whatever a reviewer decides. Only the jump to the new level waits on approval.+ stepSegments.push({ path: `M ${previousX} ${previousY} H ${x}`, blocked: false })+ if (previousY !== y) {+ stepSegments.push({ path: `M ${x} ${previousY} V ${y}`, blocked: occurrence.needsApproval })+ }+ }+ previousX = x+ previousRollout = rollout+ })+ if (previousRollout !== null && previousX < MARGIN.left + PLOT_WIDTH) {+ stepSegments.push({+ path: `M ${previousX} ${yForRollout(previousRollout)} H ${MARGIN.left + PLOT_WIDTH}`,+ blocked: false,+ })+ }++ // role="img" makes the chart a single leaf node, so a screen reader never descends into the+ // marks and hears no date, level, or approval state. The label has to carry the plan itself.+ const chartLabel = `Timeline of ${occurrences.length} upcoming scheduled changes: ${occurrences+ .map(+ (occurrence) =>+ `${describeOccurrence(occurrence)} on ${formatOccurrenceTime(occurrence.timestamp, timezone)}${+ occurrence.needsApproval ? ' (needs approval)' : ''+ }`+ )+ .join(', then ')}`++ return (+ // The chart scrolls horizontally rather than scale its 9-unit labels below legibility. The+ // minimum width is WIDTH itself, so at the floor one viewBox unit is one pixel and the+ // labels hold at 9px. A smaller floor would scale them down by the same ratio.+ // A plain div with overflow takes no focus and no arrow keys, so the scroll region needs a+ // focus stop of its own to be reachable without a mouse.+ <div+ className="flex flex-col gap-1 overflow-x-auto"+ tabIndex={0}+ role="group"+ aria-label="Scrollable schedule timeline"+ data-attr="feature-flag-schedule-timeline"+ >+ <svg+ viewBox={`0 0 ${WIDTH} ${HEIGHT}`}+ className="w-full max-w-3xl"+ style={{ minWidth: WIDTH }}+ role="img"+ aria-label={chartLabel}+ >+ {[0, 50, 100].map((rollout) => (+ <g key={rollout}>+ <line+ x1={MARGIN.left}+ x2={MARGIN.left + PLOT_WIDTH}+ y1={yForRollout(rollout)}+ y2={yForRollout(rollout)}+ stroke="var(--color-border-primary)"+ strokeWidth={rollout === 0 ? 1 : 0.5}+ />+ <text+ x={MARGIN.left - 4}+ y={yForRollout(rollout) + 3}+ textAnchor="end"+ fontSize={9}+ fill="var(--color-text-secondary)"+ >+ {rollout}%+ </text>+ </g>+ ))}++ {stepSegments.map((segment, index) => (+ <path+ key={index}+ d={segment.path}+ fill="none"+ stroke="var(--data-color-1)"+ strokeWidth={2}+ strokeDasharray={segment.blocked ? '4 3' : undefined}+ opacity={segment.blocked ? 0.5 : 1}+ />+ ))}++ {occurrences.map((occurrence, index) => {+ const { x, timeLabel, topLabelY } = layouts[index]+ const blocked = occurrence.needsApproval+ const isRolloutStep = occurrence.operation === ScheduledChangeOperationType.AddReleaseCondition+ const rollout = occurrence.projected.rolloutPercentage+ return (+ <g key={`${occurrence.schedule.id}-${occurrence.timestamp}`} opacity={blocked ? 0.5 : 1}>+ {blocked && <title>Needs approval</title>}+ <line+ x1={x}+ x2={x}+ y1={BASELINE_Y}+ y2={BASELINE_Y + 4}+ stroke="var(--color-border-primary)"+ />+ {isRolloutStep && rollout !== null ? (+ <>+ <circle+ cx={x}+ cy={yForRollout(rollout)}+ r={3.5}+ fill="var(--data-color-1)"+ stroke="var(--color-bg-surface-primary)"+ strokeWidth={1.5}+ strokeDasharray={blocked ? '2 2' : undefined}+ />+ <text+ x={x}+ y={yForRollout(rollout) - 7}+ textAnchor="middle"+ fontSize={9}+ fill="var(--color-text-secondary)"+ >+ {rollout}%{blocked ? ' (needs approval)' : ''}+ </text>+ </>+ ) : (+ <>+ <line+ x1={x}+ x2={x}+ y1={MARGIN.top - 4}+ y2={BASELINE_Y}+ stroke="var(--color-border-primary)"+ strokeDasharray="2 3"+ />+ <text+ x={x}+ y={topLabelY}+ textAnchor="middle"+ fontSize={9}+ fill="var(--color-text-secondary)"+ >+ {markerLabel(occurrence)}+ {blocked ? ' (needs approval)' : ''}+ </text>+ </>+ )}+ {timeLabel && (+ <text+ x={x}+ y={BASELINE_Y + 15}+ textAnchor="middle"+ fontSize={9}+ fill="var(--color-text-secondary)"+ >+ {timeLabel}+ </text>+ )}+ </g>+ )+ })}+ </svg>+ </div>+ )+}diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.test.tsindex 6056b8475f8b..f86f9b6aba4e 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts@@ -1891,7 +1891,7 @@ describe('featureFlagLogic', () => {})})- describe('schedule ordering', () => {+ describe('scheduled changes', () => {const makeScheduledChange = (overrides: Partial<ScheduledChangeType>): ScheduledChangeType => ({id: 1,team_id: MOCK_DEFAULT_PROJECT.id,@@ -2097,6 +2097,42 @@ describe('featureFlagLogic', () => {completedSchedules: [partial({ id: 1 }), partial({ id: 2 })],})})++ it('collapses the form again after a create, so the plan stays in front', async () => {+ useMocks({ get: { [schedulesUrl]: () => [200, { results: [makeScheduledChange({ id: 1 })] }] } })+ // The success listener reports to eventUsageLogic, but featureFlagLogic does not mount it via connect().+ eventUsageLogic.mount()+ await expectLogic(logic, () => {+ logic.actions.loadScheduledChanges()+ }).toDispatchActions(['loadScheduledChangesSuccess'])++ logic.actions.setScheduleFormExpanded(true)+ expect(logic.values.scheduleFormState).toEqual('expanded')++ await expectLogic(logic, () => {+ logic.actions.createScheduledChangeSuccess(makeScheduledChange({ id: 2 }))+ }).toFinishAllListeners()++ expect(logic.values.scheduleFormState).toEqual('collapsed')+ })++ it('opens the form again when the last schedule goes, to match the empty state', async () => {+ let results = [makeScheduledChange({ id: 1 })]+ useMocks({ get: { [schedulesUrl]: () => [200, { results }] } })+ await expectLogic(logic, () => {+ logic.actions.loadScheduledChanges()+ }).toDispatchActions(['loadScheduledChangesSuccess'])++ logic.actions.setScheduleFormExpanded(false)+ expect(logic.values.scheduleFormState).toEqual('collapsed')++ results = []+ await expectLogic(logic, () => {+ logic.actions.loadScheduledChanges()+ }).toDispatchActions(['loadScheduledChangesSuccess'])++ expect(logic.values.scheduleFormState).toEqual('expanded')+ })})describe('default release conditions', () => {diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.tsindex 29cbd8e87805..e182863ad8ca 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts@@ -123,6 +123,12 @@ import { uniformAggregationGroupTypeIndex } from './defaultReleaseConditionsUtilimport { FeatureFlagArchivedSource, reportFeatureFlagArchived } from './featureFlagArchiveDialog'import { checkFeatureFlagConfirmation } from './featureFlagConfirmationLogic'import type { FlagIntent } from './featureFlagIntentWarningLogic'+import {+ ScheduleOccurrence,+ expandScheduleOccurrences,+ hasDeniedApprovalRequest,+ isSchedulePaused,+} from './scheduleOccurrences'import { flagToggleKey, updateFlagActiveInProject } from './updateFlagActiveInProject'const VALID_INTENTS: FlagIntent[] = ['local-eval', 'first-page-load']@@ -309,13 +315,7 @@ export function byExecutedAt(a: ScheduledChangeType, b: ScheduledChangeType): nu// applier skips it at fire time. It reads as terminal in the UI and sorts with history.// Recurring schedules are excluded because each occurrence is re-gated with a fresh request.export function isScheduleDeniedApproval(sc: ScheduledChangeType): boolean {- return (- !sc.is_recurring &&- !sc.recurrence_interval &&- !sc.cron_expression &&- (sc.change_request?.state === ScheduledChangeRequestState.Rejected ||- sc.change_request?.state === ScheduledChangeRequestState.Expired)- )+ return !sc.is_recurring && !sc.recurrence_interval && !sc.cron_expression && hasDeniedApprovalRequest(sc)}export const PAIRED_PRESETS: Record<Exclude<PairedPresetKey, 'custom_pair'>, PairedPresetDefinition> = {@@ -333,6 +333,10 @@ export const PAIRED_PRESETS: Record<Exclude<PairedPresetKey, 'custom_pair'>, Pai},}+/** Resolution state of the schedule creation form: unknown while schedules first load,+ * then collapsed behind a button when the flag already has a plan to read. */+export type ScheduleFormState = 'loading' | 'collapsed' | 'expanded'+export type ScheduleFlagPayload = Pick<FeatureFlagType, 'filters' | 'active'> & {variants?: MultivariateFlagVariant[]payloads?: Record<string, any>@@ -909,13 +913,18 @@ export interface featureFlagLogicValues {roleBasedAccessEnabled: booleanscheduleDateMarker: anyscheduleDefaultsAppliedFromFlag: boolean+ scheduleFormCollapsible: boolean+ scheduleFormManuallyExpanded: boolean | null+ scheduleFormState: ScheduleFormStateschedulePayload: ScheduleFlagPayloadschedulePayloadErrors: anyschedulePreset: PairedPresetKey | null+ scheduleTimelineOccurrences: ScheduleOccurrence[]scheduledChange: ScheduledChangeTypescheduledChangeLoading: booleanscheduledChangeOperation: ScheduledChangeOperationTypescheduledChanges: ScheduledChangeType[]+ scheduledChangesLoaded: booleanscheduledChangesLoading: booleanselectedTab: FeatureFlagsTabshowFeatureFlagErrors: boolean@@ -1335,6 +1344,9 @@ export interface featureFlagLogicActions {version: number | null}}+ resetScheduleFormExpanded: () => {+ value: true+ }restoreFeatureFlag: (featureFlag: Partial<FeatureFlagType>) => {featureFlag: Partial<FeatureFlagType>}@@ -1545,6 +1557,9 @@ export interface featureFlagLogicActions {setScheduleDateMarker: (dateMarker: any) => {dateMarker: any}+ setScheduleFormExpanded: (expanded: boolean) => {+ expanded: boolean+ }setSchedulePayload: (filters: FeatureFlagType['filters'] | null,active: FeatureFlagType['active'] | null,@@ -1943,6 +1958,17 @@ export interface featureFlagLogicMeta {pausedRecurringSchedules: ScheduledChangeType[],upcomingOneTimeSchedules: ScheduledChangeType[]) => ScheduledChangeType[]+ scheduleTimelineOccurrences: (+ scheduledChanges: ScheduledChangeType[],+ featureFlag: FeatureFlagType+ ) => ScheduleOccurrence[]+ scheduleFormCollapsible: (activeSchedules: ScheduledChangeType[]) => boolean+ scheduleFormState: (+ scheduleFormManuallyExpanded: boolean | null,+ scheduleFormCollapsible: boolean,+ scheduledChangesLoading: boolean,+ scheduledChangesLoaded: boolean+ ) => ScheduleFormStateemailDomain: (user: UserType | null) => stringtemplates: (emailDomain: string) => Array<{description: string@@ -2032,6 +2058,8 @@ export const featureFlagLogic = kea<featureFlagLogicType>([) => ({ copyDependencyRequirements }),loadCopyDependencyRequirementsFailure: (error: string, errorObject?: unknown) => ({ error, errorObject }),setScheduleDateMarker: (dateMarker: any) => ({ dateMarker }),+ setScheduleFormExpanded: (expanded: boolean) => ({ expanded }),+ resetScheduleFormExpanded: true,setSchedulePayload: (filters: FeatureFlagType['filters'] | null,active: FeatureFlagType['active'] | null,@@ -2458,6 +2486,28 @@ export const featureFlagLogic = kea<featureFlagLogicType>([setScheduleDateMarker: (_, { dateMarker }) => dateMarker,},],+ // Null until the user opens or closes the form; the default is derived from+ // whether the flag already has active schedules (see scheduleFormState).+ scheduleFormManuallyExpanded: [+ null as boolean | null,+ {+ setScheduleFormExpanded: (_, { expanded }) => expanded,+ // A create adds to the plan, so the form returns to the default that the plan+ // implies. Without this the form stays open for the rest of the mount, and the+ // "Schedule a change" button stays hidden behind it.+ createScheduledChangeSuccess: () => null,+ resetScheduleFormExpanded: () => null,+ },+ ],+ // Distinguishes the first load from refetches, so the schedule header only+ // shows a skeleton once per mount instead of on every reload after a mutation.+ scheduledChangesLoaded: [+ false,+ {+ loadScheduledChangesSuccess: () => true,+ loadScheduledChangesFailure: () => true,+ },+ ],schedulePayload: [{filters: { ...NEW_FLAG.filters },@@ -3360,6 +3410,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([},createPairedSchedule: async () => {const resetScheduleForm = (): void => {+ actions.resetScheduleFormExpanded()actions.setSchedulePreset(null)actions.setScheduleDateMarker(null)actions.setIsRecurring(false)@@ -4452,9 +4503,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([pausedRecurringSchedules: [(s) => [s.scheduledChanges],(scheduledChanges: ScheduledChangeType[]) =>- scheduledChanges.filter(- (sc) => !sc.is_recurring && (!!sc.recurrence_interval || !!sc.cron_expression) && !sc.executed_at- ),+ scheduledChanges.filter((sc) => isSchedulePaused(sc) && !sc.executed_at),],upcomingOneTimeSchedules: [(s) => [s.scheduledChanges],@@ -4482,6 +4531,43 @@ export const featureFlagLogic = kea<featureFlagLogicType>([upcomingOneTime: ScheduledChangeType[]) => [...activeRecurring, ...pausedRecurring, ...upcomingOneTime].sort(byScheduledAt),],+ scheduleTimelineOccurrences: [+ // Raw scheduled changes, not activeSchedules: the expansion owns occurrence+ // eligibility (executed, paused, denied) so its filters stay live and tested.+ (s) => [s.scheduledChanges, s.featureFlag],+ (scheduledChanges: ScheduledChangeType[], featureFlag: FeatureFlagType): ScheduleOccurrence[] =>+ expandScheduleOccurrences(scheduledChanges, featureFlag, dayjs()),+ ],+ // The form can collapse only when there is a plan to read; the close button uses this too.+ scheduleFormCollapsible: [+ (s) => [s.activeSchedules],+ (activeSchedules: ScheduledChangeType[]): boolean => activeSchedules.length > 0,+ ],+ scheduleFormState: [+ (s) => [+ s.scheduleFormManuallyExpanded,+ s.scheduleFormCollapsible,+ s.scheduledChangesLoading,+ s.scheduledChangesLoaded,+ ],+ (+ scheduleFormManuallyExpanded: boolean | null,+ scheduleFormCollapsible: boolean,+ scheduledChangesLoading: boolean,+ scheduledChangesLoaded: boolean+ ): ScheduleFormState => {+ if (scheduleFormManuallyExpanded !== null) {+ // A manual collapse holds only while a plan remains to read. When the last+ // schedule goes, the form must open again, because the empty state tells the+ // user to use the form above it.+ return scheduleFormManuallyExpanded || !scheduleFormCollapsible ? 'expanded' : 'collapsed'+ }+ if (scheduledChangesLoading && !scheduledChangesLoaded) {+ return 'loading'+ }+ return scheduleFormCollapsible ? 'collapsed' : 'expanded'+ },+ ],emailDomain: [(s) => [s.user],(user: null | import('~/types').UserType) => user?.email?.split('@')[1] || 'example.com',diff --git a/frontend/src/scenes/feature-flags/makeScheduledChange.ts b/frontend/src/scenes/feature-flags/makeScheduledChange.tsnew file mode 100644index 000000000000..ea9b4fdf7d96--- /dev/null+++ b/frontend/src/scenes/feature-flags/makeScheduledChange.ts@@ -0,0 +1,33 @@+import { MOCK_DEFAULT_BASIC_USER } from 'lib/api.mock'++import { ScheduledChangeModels, ScheduledChangeOperationType, ScheduledChangeType } from '~/types'++let nextScheduledChangeId = 1++/** Reset the auto-incrementing id, for tests that rely on deterministic ids across cases. */+export function resetScheduledChangeIds(): void {+ nextScheduledChangeId = 1+}++/** Test and story factory: one home for the full ScheduledChangeType shape. */+export function makeScheduledChange(overrides: Partial<ScheduledChangeType> = {}): ScheduledChangeType {+ return {+ id: nextScheduledChangeId++,+ team_id: 1,+ record_id: 1,+ model_name: ScheduledChangeModels.FeatureFlag,+ payload: { operation: ScheduledChangeOperationType.UpdateStatus, value: true },+ scheduled_at: '2030-01-01T00:00:00Z',+ executed_at: null,+ failure_reason: null,+ created_at: null,+ created_by: MOCK_DEFAULT_BASIC_USER,+ is_recurring: false,+ recurrence_interval: null,+ cron_expression: null,+ last_executed_at: null,+ end_date: null,+ change_request: null,+ ...overrides,+ }+}diff --git a/frontend/src/scenes/feature-flags/scheduleOccurrences.test.ts b/frontend/src/scenes/feature-flags/scheduleOccurrences.test.tsnew file mode 100644index 000000000000..0ad1915ef0f7--- /dev/null+++ b/frontend/src/scenes/feature-flags/scheduleOccurrences.test.ts@@ -0,0 +1,383 @@+import { dayjs } from 'lib/dayjs'++import {+ FeatureFlagType,+ RecurrenceInterval,+ ScheduledChangeOperationType,+ ScheduledChangePayload,+ ScheduledChangeRequestState,+ ScheduledChangeType,+} from '~/types'++import { makeScheduledChange, resetScheduledChangeIds } from './makeScheduledChange'+import { OCCURRENCE_CAP, expandScheduleOccurrences } from './scheduleOccurrences'++const NOW = dayjs('2026-01-01T00:00:00Z')++function change(overrides: Partial<ScheduledChangeType> & { payload: ScheduledChangePayload }): ScheduledChangeType {+ return makeScheduledChange({ scheduled_at: NOW.add(1, 'day').toISOString(), ...overrides })+}++function conditionPayload(rolloutPercentage: number): ScheduledChangePayload {+ return {+ operation: ScheduledChangeOperationType.AddReleaseCondition,+ value: { groups: [{ properties: [], rollout_percentage: rolloutPercentage, variant: null }] },+ }+}++const STATUS_ON: ScheduledChangePayload = { operation: ScheduledChangeOperationType.UpdateStatus, value: true }++function flag(+ overrides: Partial<Pick<FeatureFlagType, 'active' | 'filters'>> = {}+): Pick<FeatureFlagType, 'active' | 'filters'> {+ return {+ active: true,+ filters: {+ groups: [{ properties: [], rollout_percentage: 10, variant: null }],+ multivariate: null,+ },+ ...overrides,+ }+}++describe('expandScheduleOccurrences', () => {+ beforeEach(() => {+ resetScheduledChangeIds()+ })++ it('projects a rollout ramp cumulatively and in chronological order', () => {+ // Deliberately out of order: expansion must sort by time, not input order.+ const schedules = [+ change({ payload: conditionPayload(75), scheduled_at: NOW.add(3, 'day').toISOString() }),+ change({ payload: conditionPayload(25), scheduled_at: NOW.add(1, 'day').toISOString() }),+ change({ payload: conditionPayload(100), scheduled_at: NOW.add(4, 'day').toISOString() }),+ change({ payload: conditionPayload(50), scheduled_at: NOW.add(2, 'day').toISOString() }),+ ]++ const occurrences = expandScheduleOccurrences(schedules, flag(), NOW)++ expect(occurrences.map((o) => o.projected.rolloutPercentage)).toEqual([25, 50, 75, 100])+ expect(occurrences.map((o) => o.addedRolloutPercentage)).toEqual([25, 50, 75, 100])+ expect(occurrences.map((o) => o.timestamp)).toEqual([+ NOW.add(1, 'day').toISOString(),+ NOW.add(2, 'day').toISOString(),+ NOW.add(3, 'day').toISOString(),+ NOW.add(4, 'day').toISOString(),+ ])+ })++ it('carries status, rollout, and variant projections through a mixed plan', () => {+ const schedules = [+ change({+ payload: { operation: ScheduledChangeOperationType.UpdateStatus, value: false },+ scheduled_at: NOW.add(1, 'day').toISOString(),+ }),+ change({ payload: conditionPayload(5), scheduled_at: NOW.add(2, 'day').toISOString() }),+ change({+ payload: {+ operation: ScheduledChangeOperationType.UpdateVariants,+ value: {+ variants: [+ { key: 'a', rollout_percentage: 50 },+ { key: 'b', rollout_percentage: 50 },+ ],+ },+ },+ scheduled_at: NOW.add(3, 'day').toISOString(),+ }),+ ]++ const occurrences = expandScheduleOccurrences(schedules, flag(), NOW)++ expect(occurrences.map((o) => o.projected)).toEqual([+ { active: false, rolloutPercentage: 10, variantCount: null },+ // A 5% condition does not lower the flag's existing 10% max rollout.+ { active: false, rolloutPercentage: 10, variantCount: null },+ { active: false, rolloutPercentage: 10, variantCount: 2 },+ ])+ })++ it.each([+ {+ name: 'a condition set with no rollout percentage as 100%',+ groups: [{ properties: [], rollout_percentage: null, variant: null }],+ expected: 100,+ },+ { name: 'no condition sets as unknown', groups: [], expected: null },+ ])('reads $name', ({ groups, expected }) => {+ // Null means the set matches all of its targets. Coercing it to 0 would floor the step+ // line and describe a scheduled condition as a 0% rollout.+ const schedules = [+ change({+ payload: { operation: ScheduledChangeOperationType.AddReleaseCondition, value: { groups } },+ }),+ ]++ const occurrences = expandScheduleOccurrences(schedules, flag({ filters: { groups, multivariate: null } }), NOW)++ expect(occurrences[0].addedRolloutPercentage).toEqual(expected)+ expect(occurrences[0].projected.rolloutPercentage).toEqual(expected)+ })++ it('expands a fixed-interval recurring schedule up to its end date', () => {+ const schedules = [+ change({+ payload: STATUS_ON,+ is_recurring: true,+ recurrence_interval: RecurrenceInterval.Daily,+ scheduled_at: NOW.add(1, 'day').toISOString(),+ end_date: NOW.add(3, 'day').add(12, 'hour').toISOString(),+ }),+ ]++ const occurrences = expandScheduleOccurrences(schedules, flag(), NOW)++ expect(occurrences.map((o) => o.timestamp)).toEqual([+ NOW.add(1, 'day').toISOString(),+ NOW.add(2, 'day').toISOString(),+ NOW.add(3, 'day').toISOString(),+ ])+ })++ it('stops recurring expansion at the horizon', () => {+ const schedules = [+ change({+ payload: STATUS_ON,+ is_recurring: true,+ recurrence_interval: RecurrenceInterval.Monthly,+ scheduled_at: NOW.add(10, 'day').toISOString(),+ }),+ ]++ // Jan 11, Feb 11, and Mar 11 fall inside the 90-day horizon; Apr 11 does not.+ expect(expandScheduleOccurrences(schedules, flag(), NOW)).toHaveLength(3)+ })++ it('clamps month-end recurring dates iteratively, matching the backend', () => {+ // A monthly schedule starting Jan 31 must not restore the 31st after a short month: the+ // backend advances from the previous run (Jan 31 -> Feb 28 -> Mar 28), so the projection must too.+ const schedules = [+ change({+ payload: STATUS_ON,+ is_recurring: true,+ recurrence_interval: RecurrenceInterval.Monthly,+ scheduled_at: dayjs('2026-01-31T09:00:00Z').toISOString(),+ }),+ ]++ const occurrences = expandScheduleOccurrences(schedules, flag(), NOW)++ expect(occurrences.map((o) => o.timestamp)).toEqual([+ '2026-01-31T09:00:00.000Z',+ '2026-02-28T09:00:00.000Z',+ '2026-03-28T09:00:00.000Z',+ ])+ })++ it('gives a denied recurring cron schedule no occurrences', () => {+ // The next cron run after the denied one is not computed client-side.+ const schedules = [+ change({+ payload: STATUS_ON,+ is_recurring: true,+ cron_expression: '0 9 * * 1-5',+ change_request: { id: 'cr-5', state: ScheduledChangeRequestState.Expired },+ }),+ ]++ expect(expandScheduleOccurrences(schedules, flag(), NOW)).toEqual([])+ })++ it('caps the total number of occurrences', () => {+ const schedules = [+ change({+ payload: STATUS_ON,+ is_recurring: true,+ recurrence_interval: RecurrenceInterval.Daily,+ scheduled_at: NOW.add(1, 'day').toISOString(),+ }),+ ]++ expect(expandScheduleOccurrences(schedules, flag(), NOW)).toHaveLength(OCCURRENCE_CAP)+ })++ it('gives a cron schedule exactly one occurrence, at its next run', () => {+ const scheduledAt = NOW.add(1, 'day').toISOString()+ const schedules = [+ change({+ payload: STATUS_ON,+ is_recurring: true,+ cron_expression: '0 9 * * 1-5',+ scheduled_at: scheduledAt,+ }),+ ]++ const occurrences = expandScheduleOccurrences(schedules, flag(), NOW)++ expect(occurrences).toHaveLength(1)+ expect(occurrences[0].timestamp).toEqual(scheduledAt)+ })++ it.each([+ { state: ScheduledChangeRequestState.Pending, expected: true },+ { state: ScheduledChangeRequestState.Approved, expected: false },+ ])('marks occurrences with a $state approval request as needsApproval=$expected', ({ state, expected }) => {+ const schedules = [change({ payload: STATUS_ON, change_request: { id: 'cr-1', state } })]++ expect(expandScheduleOccurrences(schedules, flag(), NOW)[0].needsApproval).toBe(expected)+ })++ it.each([+ { state: ScheduledChangeRequestState.Approved, firstNeedsApproval: false },+ { state: ScheduledChangeRequestState.Pending, firstNeedsApproval: true },+ ])(+ 're-gates every occurrence after the first of a $state gated recurring schedule',+ ({ state, firstNeedsApproval }) => {+ // The bound request covers one fire. The backend binds a fresh pending request to each+ // later occurrence, so an approved request must not project the whole ramp as certain.+ const schedules = [+ change({+ payload: STATUS_ON,+ is_recurring: true,+ recurrence_interval: RecurrenceInterval.Daily,+ scheduled_at: NOW.add(1, 'day').toISOString(),+ change_request: { id: 'cr-1', state },+ }),+ ]++ const occurrences = expandScheduleOccurrences(schedules, flag(), NOW)++ expect(occurrences[0].needsApproval).toBe(firstNeedsApproval)+ expect(occurrences.slice(1).map((o) => o.needsApproval)).toEqual(occurrences.slice(1).map(() => true))+ }+ )++ it('leaves an ungated recurring schedule unmarked throughout', () => {+ const schedules = [+ change({+ payload: STATUS_ON,+ is_recurring: true,+ recurrence_interval: RecurrenceInterval.Daily,+ scheduled_at: NOW.add(1, 'day').toISOString(),+ }),+ ]++ const occurrences = expandScheduleOccurrences(schedules, flag(), NOW)++ expect(occurrences.every((o) => !o.needsApproval)).toBe(true)+ })++ it.each([{ state: ScheduledChangeRequestState.Rejected }, { state: ScheduledChangeRequestState.Expired }])(+ 'drops a $state recurring occurrence but keeps expanding the rest',+ ({ state }) => {+ const schedules = [+ change({+ payload: STATUS_ON,+ is_recurring: true,+ recurrence_interval: RecurrenceInterval.Daily,+ scheduled_at: NOW.add(1, 'day').toISOString(),+ change_request: { id: 'cr-denied', state },+ }),+ ]++ const occurrences = expandScheduleOccurrences(schedules, flag(), NOW)++ // The backend skips this occurrence and re-gates the next, so the timeline must not+ // project the denied change as applied; expansion resumes at the following day.+ expect(occurrences.map((o) => o.timestamp)).not.toContain(NOW.add(1, 'day').toISOString())+ expect(occurrences[0].timestamp).toEqual(NOW.add(2, 'day').toISOString())+ }+ )++ it.each([+ {+ name: 'paused recurring',+ overrides: { is_recurring: false, recurrence_interval: RecurrenceInterval.Daily },+ },+ { name: 'executed', overrides: { executed_at: NOW.subtract(1, 'day').toISOString() } },+ {+ name: 'rejected one-time',+ overrides: { change_request: { id: 'cr-2', state: ScheduledChangeRequestState.Rejected } },+ },+ {+ name: 'expired one-time',+ overrides: { change_request: { id: 'cr-3', state: ScheduledChangeRequestState.Expired } },+ },+ { name: 'unparseable scheduled_at', overrides: { scheduled_at: 'not-a-date' } },+ {+ // A recoverable failure leaves executed_at null with a now-past scheduled_at+ // (process_scheduled_changes: "leave executed_at=NULL to allow retries").+ name: 'past-due one-time',+ overrides: { scheduled_at: NOW.subtract(2, 'day').toISOString() },+ },+ {+ name: 'past-due cron',+ overrides: {+ scheduled_at: NOW.subtract(2, 'day').toISOString(),+ is_recurring: true,+ cron_expression: '0 9 * * 1-5',+ },+ },+ {+ name: 'recurring past its end date',+ overrides: {+ scheduled_at: NOW.subtract(10, 'day').toISOString(),+ is_recurring: true,+ recurrence_interval: RecurrenceInterval.Daily,+ end_date: NOW.subtract(5, 'day').toISOString(),+ },+ },+ {+ // The sweep advances scheduled_at without reading end_date, so a closed window can+ // hold a future date until the sweep reaches it and stamps executed_at.+ name: 'recurring past its end date with a future scheduled_at',+ overrides: {+ scheduled_at: NOW.add(1, 'day').toISOString(),+ is_recurring: true,+ recurrence_interval: RecurrenceInterval.Daily,+ end_date: NOW.subtract(1, 'day').toISOString(),+ },+ },+ ])('excludes $name schedules', ({ overrides }) => {+ const schedules = [change({ payload: STATUS_ON, ...overrides })]++ expect(expandScheduleOccurrences(schedules, flag(), NOW)).toEqual([])+ })++ it('catches a stalled recurring schedule up to its next fire, and re-gates it', () => {+ // The sweep leaves scheduled_at in the past when it defers on a conflicting approval, then+ // skips the missed fires. An approved request covered the fire that never happened, so the+ // caught-up occurrence must still read as needing approval.+ const schedules = [+ change({+ payload: STATUS_ON,+ is_recurring: true,+ recurrence_interval: RecurrenceInterval.Daily,+ scheduled_at: NOW.subtract(3, 'day').add(9, 'hour').toISOString(),+ change_request: { id: 'cr-1', state: ScheduledChangeRequestState.Approved },+ }),+ ]++ const occurrences = expandScheduleOccurrences(schedules, flag(), NOW)++ expect(occurrences[0].timestamp).toEqual(NOW.add(9, 'hour').toISOString())+ expect(occurrences[0].needsApproval).toBe(true)+ })++ it('clamps a stalled monthly schedule along the path the sweep took', () => {+ // Oct 31 monthly gives Nov 30, then Dec 30, then Jan 30. Adding three months to the origin+ // would restore the 31st and paint a date the flag never fires on.+ const schedules = [+ change({+ payload: STATUS_ON,+ is_recurring: true,+ recurrence_interval: RecurrenceInterval.Monthly,+ scheduled_at: dayjs('2025-10-31T09:00:00Z').toISOString(),+ }),+ ]++ const occurrences = expandScheduleOccurrences(schedules, flag(), NOW)++ expect(occurrences[0].timestamp).toEqual('2026-01-30T09:00:00.000Z')+ })+})diff --git a/frontend/src/scenes/feature-flags/scheduleOccurrences.ts b/frontend/src/scenes/feature-flags/scheduleOccurrences.tsnew file mode 100644index 000000000000..aa77c60cba45--- /dev/null+++ b/frontend/src/scenes/feature-flags/scheduleOccurrences.ts@@ -0,0 +1,209 @@+import { Dayjs, dayjs } from 'lib/dayjs'++import {+ FeatureFlagGroupType,+ FeatureFlagType,+ RecurrenceInterval,+ ScheduledChangeOperationType,+ ScheduledChangeRequestState,+ ScheduledChangeType,+} from '~/types'++/** Flag state as projected after a scheduled change occurrence has applied. */+export interface ScheduleProjectedState {+ active: boolean+ /** Max rollout percentage across release condition sets. Null when no condition sets exist. */+ rolloutPercentage: number | null+ /** Null for flags with no variants. */+ variantCount: number | null+}++export interface ScheduleOccurrence {+ /** ISO timestamp of when this occurrence fires. */+ timestamp: string+ operation: ScheduledChangeOperationType+ schedule: ScheduledChangeType+ projected: ScheduleProjectedState+ /** Max rollout of the condition this occurrence adds; null for other operations. */+ addedRolloutPercentage: number | null+ /** The occurrence will be skipped at fire time unless its approval request is approved first. */+ needsApproval: boolean+}++export const OCCURRENCE_CAP = 10+export const OCCURRENCE_HORIZON_DAYS = 90++const INTERVAL_UNIT: Record<RecurrenceInterval, 'day' | 'week' | 'month' | 'year'> = {+ [RecurrenceInterval.Daily]: 'day',+ [RecurrenceInterval.Weekly]: 'week',+ [RecurrenceInterval.Monthly]: 'month',+ [RecurrenceInterval.Yearly]: 'year',+}++/** Matches MAX_CATCHUP_ITERATIONS in posthog/tasks/process_scheduled_changes.py. */+const CATCHUP_CAP = 1000++/**+ * Advances a stalled recurring date to its first fire after `now`, as the sweep's catch-up loop+ * does. The sweep skips the missed fires instead of replaying them, so this projects one date.+ */+function catchUpToFuture(from: Dayjs, unit: 'day' | 'week' | 'month' | 'year', now: Dayjs): Dayjs {+ // Step from the previous date rather than add N intervals to the origin, because month-end+ // clamping is path dependent: a monthly schedule from Oct 31 gives Nov 30, then Dec 30.+ let next = from+ for (let step = 0; step < CATCHUP_CAP && !next.isAfter(now); step++) {+ next = next.add(1, unit)+ }+ // The sweep gives up the same way at its own cap and computes the next run from now.+ return next.isAfter(now) ? next : now.add(1, unit)+}++/** Null/undefined rollout means the condition set matches 100% of its targets. */+export function maxRolloutPercentage(groups: FeatureFlagGroupType[] | undefined): number | null {+ if (!groups?.length) {+ return null+ }+ return Math.max(...groups.map((group) => group.rollout_percentage ?? 100))+}++/** A paused recurring schedule keeps its recurrence config but has is_recurring=false. */+export function isSchedulePaused(sc: ScheduledChangeType): boolean {+ return !sc.is_recurring && (!!sc.recurrence_interval || !!sc.cron_expression)+}++// A bound approval request that was rejected or expired means its current occurrence will not+// apply: apply_gated_scheduled_change skips it. A one-time change is then dropped entirely; a+// recurring one loses only this occurrence — the backend advances scheduled_at and re-gates the next.+export function hasDeniedApprovalRequest(sc: ScheduledChangeType): boolean {+ return (+ sc.change_request?.state === ScheduledChangeRequestState.Rejected ||+ sc.change_request?.state === ScheduledChangeRequestState.Expired+ )+}++/**+ * Expands active scheduled changes into the chronological list of upcoming occurrences, each with+ * the flag state projected after it applies (starting from the flag's current state).+ *+ * Every schedule contributes its `scheduled_at` occurrence. Cron schedules contribute only that one:+ * the backend keeps `scheduled_at` pointed at the next cron run, and further runs are deliberately+ * not expanded here (lib/cron could compute them; one next-run point is enough for this panel).+ * Fixed-interval recurring schedules expand further with date arithmetic, bounded by their end+ * date, the horizon, and the overall cap.+ */+export function expandScheduleOccurrences(+ schedules: ScheduledChangeType[],+ flag: Pick<FeatureFlagType, 'active' | 'filters'>,+ now: Dayjs+): ScheduleOccurrence[] {+ const horizon = now.add(OCCURRENCE_HORIZON_DAYS, 'day')+ const raw: { at: Dayjs; schedule: ScheduledChangeType; isFirst: boolean }[] = []++ for (const schedule of schedules) {+ if (schedule.executed_at || isSchedulePaused(schedule)) {+ continue+ }+ // Parse in UTC so recurrence arithmetic below adds fixed 24h days/weeks, matching the+ // backend's relativedelta on the stored UTC instant. Browser-local .add() would preserve+ // wall-clock across a DST transition and drift the projected fire time by an hour.+ const parsed = dayjs.utc(schedule.scheduled_at)+ if (!parsed.isValid()) {+ continue+ }+ const end = schedule.end_date ? dayjs.utc(schedule.end_date) : null+ // The sweep closes out a recurring window whose end_date has passed, and it fires nothing+ // (process_scheduled_changes stamps executed_at when end_date <= now). Such a row can still+ // hold a future scheduled_at, because the sweep advances that date without reading end_date+ // and closes the row only once the date arrives.+ if (end && !end.isAfter(now) && (schedule.recurrence_interval || schedule.cron_expression)) {+ continue+ }+ // Only a fixed-interval recurrence expands here. A cron schedule contributes its stored+ // next run alone, because the client does not evaluate cron expressions.+ const unit =+ schedule.is_recurring && schedule.recurrence_interval && !schedule.cron_expression+ ? INTERVAL_UNIT[schedule.recurrence_interval]+ : null++ let first = parsed+ // isFirst distinguishes the occurrence the schedule's current change request covers from+ // the later ones the backend will re-gate. See needsApproval below.+ let isFirst = true+ if (!first.isAfter(now)) {+ // A stalled schedule keeps a past scheduled_at with executed_at still null: the sweep+ // defers on ApprovalRequired, and a recoverable failure retries in place. Projecting+ // that instant as upcoming clamps it to the axis origin and labels it "now".+ if (!unit) {+ continue+ }+ first = catchUpToFuture(first, unit, now)+ // The bound request covered the fire that never happened, so the sweep re-gates this+ // one and it must not read as certain.+ isFirst = false+ }+ if (end && first.isAfter(end)) {+ continue+ }+ // Skip a denied change's current occurrence; the backend re-gates the next, which the+ // recurrence expansion below still projects. A denied one-time schedule then ends up with+ // no occurrence at all, and so does a denied recurring cron schedule, because its next run+ // is not computed client-side.+ if (!(isFirst && hasDeniedApprovalRequest(schedule))) {+ raw.push({ at: first, schedule, isFirst })+ }++ if (unit) {+ // Derive each occurrence from the previous one, as the backend does when it advances+ // scheduled_at (process_scheduled_changes.compute_next_run). A month-end start then stays+ // clamped (Jan 31 -> Feb 28 -> Mar 28); adding from the origin each step would restore the+ // 31st and paint flip dates the flag never fires on.+ let next = first+ for (let step = 1; step < OCCURRENCE_CAP; step++) {+ next = next.add(1, unit)+ if (next.isAfter(horizon) || (end && next.isAfter(end))) {+ break+ }+ raw.push({ at: next, schedule, isFirst: false })+ }+ }+ }++ raw.sort((a, b) => a.at.valueOf() - b.at.valueOf() || a.schedule.id - b.schedule.id)++ let active = flag.active+ let rolloutPercentage = maxRolloutPercentage(flag.filters.groups)+ let variantCount = flag.filters.multivariate?.variants.length ?? null++ return raw.slice(0, OCCURRENCE_CAP).map(({ at, schedule, isFirst }) => {+ const { payload } = schedule+ let addedRolloutPercentage: number | null = null+ if (payload.operation === ScheduledChangeOperationType.UpdateStatus) {+ active = payload.value+ } else if (payload.operation === ScheduledChangeOperationType.AddReleaseCondition) {+ addedRolloutPercentage = maxRolloutPercentage(payload.value.groups)+ if (addedRolloutPercentage !== null) {+ rolloutPercentage =+ rolloutPercentage === null+ ? addedRolloutPercentage+ : Math.max(rolloutPercentage, addedRolloutPercentage)+ }+ } else if (payload.operation === ScheduledChangeOperationType.UpdateVariants) {+ variantCount = payload.value.variants.length+ }+ return {+ timestamp: at.toISOString(),+ operation: payload.operation,+ schedule,+ projected: { active, rolloutPercentage, variantCount },+ addedRolloutPercentage,+ // A bound change request covers one occurrence only. The first occurrence needs approval+ // when its own request is still pending. Every later occurrence of a gated schedule+ // needs one too: regate_recurring_scheduled_change binds a fresh pending request after+ // each fire, and apply_gated_scheduled_change skips an occurrence whose request is still+ // pending when the fire window closes.+ needsApproval: isFirst+ ? schedule.change_request?.state === ScheduledChangeRequestState.Pending+ : !!schedule.change_request,+ }+ })+}