: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(signals): let the scout schedule picker set weekly and custom crons (#94481)
posthog[bot]68ad0bcb39dc
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex d4643ffb44fc..26de7574672d 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7340,18 +7340,26 @@ snapshots:hash: v1.k794b7964.77e43b36fdcd81befecf4de80e489050f525840924ec6ddef37c23a9179dbe8a.B3qkZFYBncFaPn2EBg4cBoYu_LIwW29imNwBdLXF5eoscenes-app-inbox-scene--triage--light:hash: v1.k794b7964.ea1f0a1a3cd9c029a33e39277a276be15a04555ba2addee17df2aacb108316dc.CFYN_7EjRWTlSCsBQMuZ6Bq_ViTyRy7_RqqtqKfg05w+ scenes-app-inbox-scoutconfigform--custom-cron-schedule--dark:+ hash: v1.k794b7964.ff4ef27dccb3a4c125819d689f6acfd37e5fbd261e76a4f995961944ab8a9910.60V_49goLz2sButl6r1k8XDQTmFf3AtbeEW9pqtZEto+ scenes-app-inbox-scoutconfigform--custom-cron-schedule--light:+ hash: v1.k794b7964.665a9290f570f1a1a1b867e059360dd4f8031e6b218d3e3931cabc11ee7e53c5.45YrUO0kVbyPueLEp07JAsMNDLeCssZQeh0rZRBsKhwscenes-app-inbox-scoutconfigform--disabled--dark:- hash: v1.k794b7964.9e9e262f07b97a0b655fa6ca799ff35c3b37b42f211b11c6a8c3fbcc5adcd577.UoegfVUyhTCj8GE9rRIrVcmmNL8UxCXUrBi3A2A9Fgg+ hash: v1.k794b7964.6c167931929e0ad3acb577560169cb38afd1aa07a90969499666ad35fc9917d1.3VYD3M6RzaMTYw_r3TiuZesSnVpsBMKH_Y6G9IB55Vsscenes-app-inbox-scoutconfigform--disabled--light:- hash: v1.k794b7964.c72fe1c0eaed734d8a717e845e2cac8844b3d25028550f14fc85b045cf507b63.94Ly7oLXdu33YSM8HurGkh0rtEOWA3Vsof5a2YyOi0s+ hash: v1.k794b7964.758d757dd52cf8a456e0b6e4fd9faf888745b686b69686b2df3623b4fc905b43.1njiIHAcecfyN7fcGAoHb2Yfwf8SGnJtJimEskPIOd0scenes-app-inbox-scoutconfigform--dry-run--dark:- hash: v1.k794b7964.e35e69dddd1ab502c263a195956afeca5dc804e29a776f561e179a08c007d202.kKe0rEPK3zMBTA8FYxju8TFiNYPTr-m1_avWpC3j_yA+ hash: v1.k794b7964.f8ffdb9f3e8c657e3bbbd8c1d58dc6a2bffc2bda07d3592bd6a119dda54e14c4.-gnvrlWJ3XKORBo52HWAVVEd0DHshC4f7ZSSctNuL7Iscenes-app-inbox-scoutconfigform--dry-run--light:- hash: v1.k794b7964.9b5445debb3c3e8f0ff9b8da44cc1869765b12ad50280661cebb24e1c9b96cdc.dbiut5M8mR2-wwXQVXZtWH824OawCBrfJAdUpY5yl80+ hash: v1.k794b7964.c54296174e99f7cca68e2ff39c778138fc73658768127094efe860ac361ef691.CldSMSHIwz6oo-pBWIvR9VMkagMXItKbrmYnC4RcgTUscenes-app-inbox-scoutconfigform--live--dark:- hash: v1.k794b7964.47bfb32dffa10ff6bd2c2278dec2b09dc79ee47b1889749297c8399060c0b5ab.ivheHFGlHioXbXYYur2C0mJ0pF-R5sRodnaiDazvaxk+ hash: v1.k794b7964.825d3e5cbf13769804b3262662742dee15001f4d024da8338de3500cdb9c2d24.7m2xWzVlSuduUMF3Jw1gc1KlUqfPq2pUxlagfsn8mx4scenes-app-inbox-scoutconfigform--live--light:- hash: v1.k794b7964.813f8f15eb8ca411579bfb532f78e247c810477c3893b2dd70de574dfe21fa19.soEpeg28h3M5JbJw71Sf5JmCXuWRZq6Ms6NXefJwUTU+ hash: v1.k794b7964.544d0262da6eca15b5ff2c6f6251bab3e8e69e39bfe167a35957f63ef9e75361.Yrk8HaWCKD9qGuHbePegXi9Bxg3tx6PPLI8G319kW28+ scenes-app-inbox-scoutconfigform--weekly-schedule--dark:+ hash: v1.k794b7964.57810c746c0e7339ab028405cccfffcf2a939b62a113bbc9d2600d991bfc932f.jxmufvcL0kB59f5lfUn0XW1LR57JkREGzlPtYCQrjX4+ scenes-app-inbox-scoutconfigform--weekly-schedule--light:+ hash: v1.k794b7964.f73cea12dc224b772cd7f6e6c69c9406eb5c978c194f9a620a6c24f1ff7a82a7.IZSn1HtvrOVH2rP_om5YJhZ4n11apTGE8bI1fVK7E8gscenes-app-inbox-scoutmcpserverspicker--create-dialog-variant--dark:hash: v1.k794b7964.afe2203f4dd53373a3203fcfa611b5b65555341bdc2fc7fd73c15c2d83914600.O4kSRnOgICuQDkyD2HJCwBXdzE-KwsfzWT98nm43_5Ascenes-app-inbox-scoutmcpserverspicker--create-dialog-variant--light:diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.tsindex bb88224c1aae..f4b8c457ef72 100644--- a/products/desktop/packages/api-client/src/posthog-client.ts+++ b/products/desktop/packages/api-client/src/posthog-client.ts@@ -558,6 +558,12 @@ export interface ScoutConfig {*/scout_origin?: "canonical" | "custom";run_interval_minutes: number;+ /**+ * Cron schedule the scout runs on, evaluated in the project timezone. Null when+ * the scout runs on the rolling `run_interval_minutes` cadence instead, and+ * absent entirely on backends predating the field.+ */+ run_cron_schedule?: string | null;last_run_at: string | null;created_at: string;}@@ -2392,6 +2398,8 @@ export class PostHogAPIClient {enabled?: boolean;emit?: boolean;run_interval_minutes?: number;+ /** A cron expression puts the scout on a calendar; null returns it to the rolling cadence. */+ run_cron_schedule?: string | null;auto_pause_exempt?: boolean;},): Promise<ScoutConfig> {diff --git a/products/desktop/packages/core/src/scouts/scoutPresentation.test.ts b/products/desktop/packages/core/src/scouts/scoutPresentation.test.tsindex f5c56efc7179..dd13803e43a0 100644--- a/products/desktop/packages/core/src/scouts/scoutPresentation.test.ts+++ b/products/desktop/packages/core/src/scouts/scoutPresentation.test.ts@@ -4,13 +4,16 @@ import {buildScoutCreatorIndex,computeFleetSummary,computeScoutRollups,+ dayTimeToWeeklyCron,deriveRunFailureKind,deriveRunOutcome,deriveScoutLifecycle,formatRunDuration,formatRunInterval,formatRunIntervalShort,+ formatScoutScheduleShort,getScoutOrigin,+ getScoutScheduleMode,isRunStuck,isScoutCreatedByUser,listScoutCreatorOptions,@@ -18,14 +21,19 @@ import {prettifyScoutSkillName,runDurationSeconds,runMatchesFilter,+ SCOUT_CUSTOM_CRON_SCHEDULE_MODE,+ SCOUT_DAILY_AT_SCHEDULE_MODE,+ SCOUT_WEEKLY_ON_SCHEDULE_MODE,type ScoutOrigin,type ScoutRunFilter,scoutCreatorDisplayName,scoutCreatorKey,+ scoutCronScheduleError,scoutRunOutcomeLabel,scoutSkillNameFromSlug,scoutSkillSlug,sortConfigsForDisplay,+ weeklyCronToDayTime,} from "./scoutPresentation";const NOW = new Date("2026-06-10T12:00:00Z");@@ -693,3 +701,76 @@ describe("creators", () => {});});});++describe("schedule modes", () => {+ it.each([+ ["a rolling interval", null, 1440, "daily"],+ ["a plain daily cron", "0 9 * * *", 1440, "daily at 09:00"],+ ["a weekly cron", "30 8 * * 4", 1440, "thursdays at 08:30"],+ ["a Sunday cron written as 7", "0 9 * * 7", 1440, "sundays at 09:00"],+ ["a cron the presets cannot name", "0 9 * * 1-5", 1440, "0 9 * * 1-5"],+ ])("labels %s", (_label, cron, minutes, expected) => {+ expect(+ formatScoutScheduleShort({+ run_interval_minutes: minutes as number,+ run_cron_schedule: cron as string | null,+ }),+ ).toBe(expected);+ });++ it.each([+ ["a rolling interval", null, "1440"],+ ["a plain daily cron", "0 9 * * *", SCOUT_DAILY_AT_SCHEDULE_MODE],+ ["a single weekday cron", "30 8 * * 4", SCOUT_WEEKLY_ON_SCHEDULE_MODE],+ ["a Sunday cron written as 7", "30 8 * * 7", SCOUT_WEEKLY_ON_SCHEDULE_MODE],+ ["a weekday-range cron", "0 9 * * 1-5", SCOUT_CUSTOM_CRON_SCHEDULE_MODE],+ ])("reads %s as its own mode", (_label, cron, expected) => {+ expect(+ getScoutScheduleMode({+ run_interval_minutes: 1440,+ run_cron_schedule: cron as string | null,+ }),+ ).toBe(expected);+ });++ it("round-trips a weekly day and time through the cron it writes", () => {+ expect(dayTimeToWeeklyCron("4", "08:30")).toBe("30 8 * * 4");+ expect(weeklyCronToDayTime("30 8 * * 4")).toEqual({+ day: "4",+ time: "08:30",+ });+ });++ it.each([+ ["0 9 * * 1-5"],+ ["30 8 * * 1,4"],+ ["0 9 1 * *"],+ ["0 9,17 * * *"],+ ["0 9 * * MON"],+ ["0 9 31 2,3 MON"],+ ["0 9 * * 5#2"],+ ["0 0 L * *"],+ ["10,50 0,23 * * 1"],+ ["R 9 * * *"],+ ])("accepts %s", (expression) => {+ expect(scoutCronScheduleError(expression)).toBeNull();+ });++ it.each([+ ["0 9 * *", "Enter a five-field cron expression, like 0 9 * * 1-5."],+ ["70 9 * * *", "Enter a five-field cron expression, like 0 9 * * 1-5."],+ [+ "0 0 31 2 *",+ "This schedule never matches a real date. Check the day and month.",+ ],+ [+ "0 0 31 2 MON",+ "This schedule never matches a real date. Check the day and month.",+ ],+ ["*/20 * * * *", "Runs must be at least 30 minutes apart."],+ ["10,50 0,23 * * *", "Runs must be at least 30 minutes apart."],+ ["0 9 * * @", "Enter a five-field cron expression, like 0 9 * * 1-5."],+ ])("refuses %s", (expression, expected) => {+ expect(scoutCronScheduleError(expression)).toBe(expected);+ });+});diff --git a/products/desktop/packages/core/src/scouts/scoutPresentation.ts b/products/desktop/packages/core/src/scouts/scoutPresentation.tsindex d92866759ffc..81a7f08b74cb 100644--- a/products/desktop/packages/core/src/scouts/scoutPresentation.ts+++ b/products/desktop/packages/core/src/scouts/scoutPresentation.ts@@ -584,6 +584,247 @@ export function formatRunInterval(minutes: number): string {return `Every ${minutes} minutes`;}+export const SCOUT_DAILY_AT_SCHEDULE_MODE = "daily_at";+export const SCOUT_WEEKLY_ON_SCHEDULE_MODE = "weekly_on";+export const SCOUT_CUSTOM_CRON_SCHEDULE_MODE = "custom_cron";+export const DEFAULT_SCOUT_DAILY_TIME = "09:00";+export const DEFAULT_SCOUT_WEEKLY_DAY = "1";++/** Cron day-of-week numbers, offered from Monday so the working week reads first. */+export const SCOUT_WEEKDAY_OPTIONS: { value: string; label: string }[] = [+ { value: "1", label: "Monday" },+ { value: "2", label: "Tuesday" },+ { value: "3", label: "Wednesday" },+ { value: "4", label: "Thursday" },+ { value: "5", label: "Friday" },+ { value: "6", label: "Saturday" },+ { value: "0", label: "Sunday" },+];++interface ScoutScheduleFields {+ run_interval_minutes: number;+ run_cron_schedule?: string | null;+}++/**+ * "30 9 * * *" → "09:30" when the cron is a plain daily time (the shape the settings form+ * writes). Anything richer returns null and is edited as raw cron instead.+ */+export function dailyCronToTime(+ cron: string | null | undefined,+): string | null {+ const match = cron?.trim().match(/^(\d{1,2}) (\d{1,2}) \* \* \*$/);+ if (!match) return null;+ return `${match[2].padStart(2, "0")}:${match[1].padStart(2, "0")}`;+}++/** "09:30" → "30 9 * * *" — the inverse of `dailyCronToTime`. */+export function timeToDailyCron(time: string): string {+ const [hours, minutes] = time.split(":");+ return `${Number(minutes)} ${Number(hours)} * * *`;+}++/**+ * "30 9 * * 4" → `{ day: "4", time: "09:30" }` when the cron is a plain weekly slot. Cron takes+ * both 0 and 7 for Sunday; the dropdown offers 0, so 7 maps onto it.+ */+export function weeklyCronToDayTime(+ cron: string | null | undefined,+): { day: string; time: string } | null {+ const match = cron?.trim().match(/^(\d{1,2}) (\d{1,2}) \* \* ([0-7])$/);+ if (!match) return null;+ return {+ day: match[3] === "7" ? "0" : match[3],+ time: `${match[2].padStart(2, "0")}:${match[1].padStart(2, "0")}`,+ };+}++/** `("4", "09:30")` → "30 9 * * 4" — the inverse of `weeklyCronToDayTime`. */+export function dayTimeToWeeklyCron(day: string, time: string): string {+ const [hours, minutes] = time.split(":");+ return `${Number(minutes)} ${Number(hours)} * * ${day}`;+}++export function getScoutScheduleMode(config: ScoutScheduleFields): string {+ if (!config.run_cron_schedule) return String(config.run_interval_minutes);+ if (dailyCronToTime(config.run_cron_schedule))+ return SCOUT_DAILY_AT_SCHEDULE_MODE;+ if (weeklyCronToDayTime(config.run_cron_schedule))+ return SCOUT_WEEKLY_ON_SCHEDULE_MODE;+ return SCOUT_CUSTOM_CRON_SCHEDULE_MODE;+}++export function getScoutScheduleOptions(+ config: ScoutScheduleFields,+): { value: string; label: string }[] {+ const options = RUN_INTERVAL_OPTIONS.map((option) => ({+ value: String(option.minutes),+ label: option.label,+ }));+ if (+ !RUN_INTERVAL_OPTIONS.some(+ (option) => option.minutes === config.run_interval_minutes,+ )+ ) {+ options.push({+ value: String(config.run_interval_minutes),+ label: formatRunInterval(config.run_interval_minutes),+ });+ }+ options.push({+ value: SCOUT_DAILY_AT_SCHEDULE_MODE,+ label: "Daily at a set time",+ });+ options.push({+ value: SCOUT_WEEKLY_ON_SCHEDULE_MODE,+ label: "Weekly on a set day",+ });+ options.push({+ value: SCOUT_CUSTOM_CRON_SCHEDULE_MODE,+ label: "Custom cron",+ });+ return options;+}++/** Longest cron expression the config API stores. */+export const SCOUT_CRON_MAX_LENGTH = 100;++/** Shortest gap the scheduler allows between two runs, the same floor as `run_interval_minutes`. */+const SCOUT_CRON_MIN_GAP_MINUTES = 30;++const CRON_MONTH_NAMES = [+ "jan",+ "feb",+ "mar",+ "apr",+ "may",+ "jun",+ "jul",+ "aug",+ "sep",+ "oct",+ "nov",+ "dec",+];+const CRON_DAY_NAMES = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];+const DAYS_IN_MONTH = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];++type CronFieldParse =+ | { kind: "values"; values: number[] }+ | { kind: "unmodeled" }+ | { kind: "invalid" };++function cronFieldNumber(+ token: string,+ offset: number,+ names: string[] | undefined,+): number | null {+ const named = names?.indexOf(token.toLowerCase());+ if (named !== undefined && named >= 0) return named + offset;+ return /^\d{1,2}$/.test(token) ? Number(token) : null;+}++/**+ * The values a single cron field matches. `unmodeled` covers the syntax this check does not+ * model (`L`, `R`, `#`, `?`): the backend decides those, because a client that guessed would+ * refuse an expression the scheduler accepts. Everything else croniter refuses, so a typo is+ * answered here instead of on the next save.+ */+function parseCronField(+ field: string,+ min: number,+ max: number,+ names?: string[],+): CronFieldParse {+ if (/[#?]/.test(field)) return { kind: "unmodeled" };+ if (!field || /[^0-9a-zA-Z*/,-]/.test(field)) return { kind: "invalid" };+ const values = new Set<number>();+ for (const part of field.split(",")) {+ const [spec, stepToken, ...extra] = part.split("/");+ if (extra.length > 0 || spec === undefined) return { kind: "invalid" };+ const step = stepToken === undefined ? 1 : Number(stepToken);+ if (!Number.isInteger(step) || step < 1) return { kind: "invalid" };+ let from = min;+ let to = max;+ if (spec !== "*") {+ // croniter's own markers: "L" is the last day of the month, "R" a random slot in the field.+ // Neither is a calendar this check models, and it refuses every other letter form anyway.+ if (/^[lr]$/i.test(spec)) return { kind: "unmodeled" };+ const bounds = spec.split("-");+ if (bounds.length > 2) return { kind: "invalid" };+ const parsed = bounds.map((token) =>+ cronFieldNumber(token, min === 0 ? 0 : 1, names),+ );+ if (parsed.some((value) => value === null || value < min || value > max))+ return { kind: "invalid" };+ from = parsed[0] as number;+ // "5/10" is an open-ended step from 5, while a bare "5" is that one value.+ to =+ bounds.length === 2+ ? (parsed[1] as number)+ : stepToken === undefined+ ? from+ : max;+ // A wrapping range like "22-2" is an extension some parsers take and others reject.+ if (to < from) return { kind: "unmodeled" };+ }+ for (let value = from; value <= to; value += step) values.add(value);+ }+ return { kind: "values", values: [...values].sort((a, b) => a - b) };+}++/**+ * Why `expression` is not an acceptable scout cron schedule, or null when it is. Mirrors the four+ * rules the config API applies (`cron_schedule_error`) so the picker rejects a typo before the+ * PATCH. Expressions using syntax this check does not model pass and are left to the backend.+ */+export function scoutCronScheduleError(expression: string): string | null {+ const expr = expression.trim();+ if (expr.length > SCOUT_CRON_MAX_LENGTH)+ return `Cron expressions must be ${SCOUT_CRON_MAX_LENGTH} characters or fewer.`;+ const fields = expr.split(/\s+/);+ const invalidShape = "Enter a five-field cron expression, like 0 9 * * 1-5.";+ if (fields.length !== 5) return invalidShape;+ const minutes = parseCronField(fields[0], 0, 59);+ const hours = parseCronField(fields[1], 0, 23);+ const daysOfMonth = parseCronField(fields[2], 1, 31);+ const months = parseCronField(fields[3], 1, 12, CRON_MONTH_NAMES);+ const daysOfWeek = parseCronField(fields[4], 0, 7, CRON_DAY_NAMES);+ if (+ [minutes, hours, daysOfMonth, months, daysOfWeek].some(+ (field) => field.kind === "invalid",+ )+ )+ return invalidShape;+ // A day-of-month no month in the set reaches kills the schedule, whatever the weekday field+ // says: croniter refuses "0 0 31 2 MON" the same as "0 0 31 2 *".+ if (+ fields[2] !== "*" &&+ daysOfMonth.kind === "values" &&+ months.kind === "values"+ ) {+ const occurs = months.values.some((month) =>+ daysOfMonth.values.some((day) => day <= DAYS_IN_MONTH[month - 1]),+ );+ if (!occurs)+ return "This schedule never matches a real date. Check the day and month.";+ }+ if (minutes.kind === "values" && hours.kind === "values") {+ const slots = hours.values.flatMap((hour) =>+ minutes.values.map((minute) => hour * 60 + minute),+ );+ const gaps = slots.slice(1).map((slot, index) => slot - slots[index]);+ // A schedule that runs every day also runs across midnight, so the last slot of one day and+ // the first of the next are one more gap. A day-restricted schedule can skip days, so how far+ // its wrap reaches is left to the backend.+ if (fields[2] === "*" && fields[4] === "*")+ gaps.push(slots[0] + 1440 - slots[slots.length - 1]);+ if (gaps.some((gap) => gap < SCOUT_CRON_MIN_GAP_MINUTES))+ return `Runs must be at least ${SCOUT_CRON_MIN_GAP_MINUTES} minutes apart.`;+ }+ return null;+}+/** Short form for row badges: "hourly", "every 3h". */export function formatRunIntervalShort(minutes: number): string {if (minutes === 60) return "hourly";@@ -593,6 +834,24 @@ export function formatRunIntervalShort(minutes: number): string {return `every ${minutes}m`;}+/**+ * Short schedule label for row badges: "daily at 09:00", "thursdays at 08:30", the raw expression+ * for a cron the presets cannot name, and the rolling cadence when the scout runs on one.+ */+export function formatScoutScheduleShort(config: ScoutScheduleFields): string {+ const dailyTime = dailyCronToTime(config.run_cron_schedule);+ if (dailyTime) return `daily at ${dailyTime}`;+ const weekly = weeklyCronToDayTime(config.run_cron_schedule);+ if (weekly) {+ const day = SCOUT_WEEKDAY_OPTIONS.find(+ (option) => option.value === weekly.day,+ );+ if (day) return `${day.label.toLowerCase()}s at ${weekly.time}`;+ }+ if (config.run_cron_schedule) return config.run_cron_schedule;+ return formatRunIntervalShort(config.run_interval_minutes);+}+/*** Enabled scouts first, then the ones the system switched off (they need a* human to switch them back on, so they lead the off-block), then the restdiff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.tsindex d0bb4241602f..6cf61a27520b 100644--- a/products/desktop/packages/shared/src/analytics-events.ts+++ b/products/desktop/packages/shared/src/analytics-events.ts@@ -994,10 +994,15 @@ export interface ScoutDetailViewedProperties {export interface ScoutConfigChangedProperties {skill_name: string;scout_origin: "canonical" | "custom";- setting: "enabled" | "emit" | "run_interval_minutes" | "auto_pause_exempt";- new_value: boolean | number;+ setting:+ | "enabled"+ | "emit"+ | "run_interval_minutes"+ | "run_cron_schedule"+ | "auto_pause_exempt";+ new_value: boolean | number | string | null;/** Null when the backend predates the setting and never sent a value. */- old_value: boolean | number | null;+ old_value: boolean | number | string | null;/** False when the server rejected the update and the change rolled back. */success: boolean;}diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutConfigControls.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutConfigControls.tsxindex 4df26db7824c..654287f7348b 100644--- a/products/desktop/packages/ui/src/features/scouts/components/ScoutConfigControls.tsx+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutConfigControls.tsx@@ -1,13 +1,29 @@import type { ScoutConfig } from "@posthog/api-client/posthog-client";import {+ DEFAULT_SCOUT_DAILY_TIME,+ DEFAULT_SCOUT_WEEKLY_DAY,+ dailyCronToTime,+ dayTimeToWeeklyCron,deriveScoutLifecycle,- formatRunInterval,- RUN_INTERVAL_OPTIONS,+ getScoutScheduleMode,+ getScoutScheduleOptions,+ SCOUT_CRON_MAX_LENGTH,+ SCOUT_CUSTOM_CRON_SCHEDULE_MODE,+ SCOUT_DAILY_AT_SCHEDULE_MODE,+ SCOUT_WEEKDAY_OPTIONS,+ SCOUT_WEEKLY_ON_SCHEDULE_MODE,+ scoutCronScheduleError,+ timeToDailyCron,+ weeklyCronToDayTime,} from "@posthog/core/scouts/scoutPresentation";-import { Switch as QuillSwitch, Text as QuillText } from "@posthog/quill";+import {+ Input as QuillInput,+ Switch as QuillSwitch,+ Text as QuillText,+} from "@posthog/quill";import { SettingsOptionSelect } from "@posthog/ui/features/settings/SettingsOptionSelect";import { Flex, Switch, Text, Tooltip } from "@radix-ui/themes";-import { useMemo } from "react";+import { useId, useState } from "react";import type { ScoutConfigUpdate } from "../hooks/useScoutConfigMutations";const MODE_OPTIONS = [@@ -20,26 +36,6 @@ interface ScoutConfigControlsProps {onUpdate: (configId: string, updates: ScoutConfigUpdate) => void;}-function useIntervalOptions(config: ScoutConfig) {- return useMemo(() => {- const options = RUN_INTERVAL_OPTIONS.map((option) => ({- value: String(option.minutes),- label: option.label,- }));- if (- !RUN_INTERVAL_OPTIONS.some(- (option) => option.minutes === config.run_interval_minutes,- )- ) {- options.push({- value: String(config.run_interval_minutes),- label: formatRunInterval(config.run_interval_minutes),- });- }- return options;- }, [config.run_interval_minutes]);-}-export function ScoutEnabledSwitch({config,onUpdate,@@ -79,8 +75,21 @@ export function ScoutConfigForm({config,onUpdate,}: ScoutConfigControlsProps) {- const intervalOptions = useIntervalOptions(config);const lifecycle = deriveScoutLifecycle(config);+ const weekly = weeklyCronToDayTime(config.run_cron_schedule);+ const runTime =+ dailyCronToTime(config.run_cron_schedule) ??+ weekly?.time ??+ DEFAULT_SCOUT_DAILY_TIME;+ const weeklyDay = weekly?.day ?? DEFAULT_SCOUT_WEEKLY_DAY;+ const savedScheduleMode = getScoutScheduleMode(config);+ // The saved config cannot express "the user opened the custom mode but has not typed a valid+ // expression yet", so that one pick is held here. Every other mode writes at once, so the config+ // stays the truth for them, including when a failed write rolls it back.+ const [customModePicked, setCustomModePicked] = useState(false);+ const scheduleMode = customModePicked+ ? SCOUT_CUSTOM_CRON_SCHEDULE_MODE+ : savedScheduleMode;return (<Flex direction="column" gap="2">@@ -106,20 +115,101 @@ export function ScoutConfigForm({<Flex direction="column" className="min-w-0"><Text className="text-[12px] text-gray-12">Cadence</Text><Text className="text-[11.5px] text-gray-10">- How often the scout is dispatched+ A rolling cadence, a set time each day or week, or a cron expression</Text></Flex><SettingsOptionSelect- value={String(config.run_interval_minutes)}- options={intervalOptions}+ value={scheduleMode}+ options={getScoutScheduleOptions(config)}ariaLabel={`${config.skill_name} run interval`}disabled={!config.enabled}className="w-36"- onValueChange={(value) =>- onUpdate(config.id, { run_interval_minutes: Number(value) })- }+ onValueChange={(value) => {+ setCustomModePicked(value === SCOUT_CUSTOM_CRON_SCHEDULE_MODE);+ if (+ value === savedScheduleMode ||+ value === SCOUT_CUSTOM_CRON_SCHEDULE_MODE+ ) {+ return;+ }+ if (value === SCOUT_DAILY_AT_SCHEDULE_MODE) {+ onUpdate(config.id, {+ run_cron_schedule: timeToDailyCron(runTime),+ });+ return;+ }+ if (value === SCOUT_WEEKLY_ON_SCHEDULE_MODE) {+ onUpdate(config.id, {+ run_cron_schedule: dayTimeToWeeklyCron(weeklyDay, runTime),+ });+ return;+ }+ // A rolling cadence replaces any cron — the schedule is one or the other.+ onUpdate(config.id, {+ run_interval_minutes: Number(value),+ run_cron_schedule: null,+ });+ }}/></Flex>+ {scheduleMode === SCOUT_WEEKLY_ON_SCHEDULE_MODE ? (+ <Flex align="center" justify="between" gap="4">+ <Flex direction="column" className="min-w-0">+ <Text className="text-[12px] text-gray-12">Run day</Text>+ <Text className="text-[11.5px] text-gray-10">+ The scout runs once a week, on this day+ </Text>+ </Flex>+ <SettingsOptionSelect+ value={weeklyDay}+ options={SCOUT_WEEKDAY_OPTIONS}+ ariaLabel={`${config.skill_name} run day`}+ disabled={!config.enabled}+ className="w-36"+ onValueChange={(day) =>+ onUpdate(config.id, {+ run_cron_schedule: dayTimeToWeeklyCron(day, runTime),+ })+ }+ />+ </Flex>+ ) : null}+ {scheduleMode === SCOUT_DAILY_AT_SCHEDULE_MODE ||+ scheduleMode === SCOUT_WEEKLY_ON_SCHEDULE_MODE ? (+ <Flex align="center" justify="between" gap="4">+ <Flex direction="column" className="min-w-0">+ <Text className="text-[12px] text-gray-12">Run time</Text>+ <Text className="text-[11.5px] text-gray-10">+ Uses the project timezone+ </Text>+ </Flex>+ <QuillInput+ key={config.run_cron_schedule ?? "unset"}+ type="time"+ step={60}+ defaultValue={runTime}+ disabled={!config.enabled}+ className="w-36"+ aria-label={`${config.skill_name} run time`}+ onBlur={(event) => {+ const value = event.currentTarget.value;+ // Empty means a half-finished edit, never "clear" — switching the schedule+ // off is the cadence picker's job, so fall back to the saved time.+ if (!value) return;+ const runCronSchedule =+ scheduleMode === SCOUT_WEEKLY_ON_SCHEDULE_MODE+ ? dayTimeToWeeklyCron(weeklyDay, value)+ : timeToDailyCron(value);+ if (runCronSchedule !== config.run_cron_schedule) {+ onUpdate(config.id, { run_cron_schedule: runCronSchedule });+ }+ }}+ />+ </Flex>+ ) : null}+ {scheduleMode === SCOUT_CUSTOM_CRON_SCHEDULE_MODE ? (+ <ScoutCustomCronField config={config} onUpdate={onUpdate} />+ ) : null}{/* Null means the backend never sent the field, so a PATCH carrying itcould not persist. Offer the control only where it writes. */}{lifecycle.autoPauseExempt !== null ? (@@ -146,3 +236,54 @@ export function ScoutConfigForm({</Flex>);}++/**+ * Raw cron editor for the schedule the presets cannot express — weekday runs, several days a+ * week, monthly. Validated against the same rules the config API applies, so a typo is caught+ * before the PATCH, and saved on blur or Enter.+ */+function ScoutCustomCronField({ config, onUpdate }: ScoutConfigControlsProps) {+ const errorId = useId();+ const [draft, setDraft] = useState(config.run_cron_schedule ?? "");+ const expression = draft.trim();+ // An empty field is a half-finished edit, not a mistake, so it stays neutral and saves nothing.+ const error = expression ? scoutCronScheduleError(expression) : null;+ const save = () => {+ if (!expression || error || expression === config.run_cron_schedule) return;+ onUpdate(config.id, { run_cron_schedule: expression });+ };++ return (+ <Flex align="start" justify="between" gap="4">+ <Flex direction="column" className="min-w-0">+ <Text className="text-[12px] text-gray-12">Cron expression</Text>+ <Text className="text-[11.5px] text-gray-10">+ Minute, hour, day of month, month, day of week, in the project+ timezone+ </Text>+ </Flex>+ <Flex direction="column" gap="1" className="w-36 shrink-0">+ <QuillInput+ value={draft}+ placeholder="0 9 * * 1-5"+ maxLength={SCOUT_CRON_MAX_LENGTH}+ disabled={!config.enabled}+ className="font-mono"+ aria-label={`${config.skill_name} cron expression`}+ aria-invalid={error ? true : undefined}+ aria-describedby={error ? errorId : undefined}+ onChange={(event) => setDraft(event.currentTarget.value)}+ onBlur={save}+ onKeyDown={(event) => {+ if (event.key === "Enter") save();+ }}+ />+ {error ? (+ <QuillText id={errorId} size="xxs" className="text-red-11">+ {error}+ </QuillText>+ ) : null}+ </Flex>+ </Flex>+ );+}diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutDetailHeader.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutDetailHeader.tsxindex e6375ec40698..17471b67f3f0 100644--- a/products/desktop/packages/ui/src/features/scouts/components/ScoutDetailHeader.tsx+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutDetailHeader.tsx@@ -1,7 +1,7 @@import { ArrowSquareOutIcon, GearSixIcon } from "@phosphor-icons/react";import type { ScoutConfig } from "@posthog/api-client/posthog-client";import {- formatRunIntervalShort,+ formatScoutScheduleShort,type ScoutRollup,} from "@posthog/core/scouts/scoutPresentation";import { ANALYTICS_EVENTS } from "@posthog/shared";@@ -74,8 +74,8 @@ export function ScoutDetailHeader({</a></Tooltip>) : null}- <Text className="whitespace-nowrap text-[12px] text-gray-10">- {formatRunIntervalShort(config.run_interval_minutes)}+ <Text className="max-w-[14rem] truncate text-[12px] text-gray-10">+ {formatScoutScheduleShort(config)}</Text><span className="flex-1" /><ScoutChatButton skillName={config.skill_name} surface="scout_detail" />diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutRowCard.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutRowCard.tsxindex 616e71ac2528..bced92b66c78 100644--- a/products/desktop/packages/ui/src/features/scouts/components/ScoutRowCard.tsx+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutRowCard.tsx@@ -5,7 +5,7 @@ import {} from "@phosphor-icons/react";import type { ScoutConfig } from "@posthog/api-client/posthog-client";import {- formatRunIntervalShort,+ formatScoutScheduleShort,prettifyScoutSkillName,type ScoutRollup,scoutSkillSlug,@@ -106,8 +106,8 @@ export function ScoutRowCard({<ScoutOriginBadge config={config} /><DryRunBadge config={config} /><ScoutLifecycleBadge config={config} />- <Text className="whitespace-nowrap text-[11px] text-gray-10">- {formatRunIntervalShort(config.run_interval_minutes)}+ <Text className="max-w-[14rem] truncate text-[11px] text-gray-10">+ {formatScoutScheduleShort(config)}</Text>{rollup && rollup.emittedCount > 0 ? (<Text className="whitespace-nowrap text-[11px] text-gray-10">diff --git a/products/desktop/packages/ui/src/features/scouts/hooks/useScoutConfigMutations.test.tsx b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutConfigMutations.test.tsxnew file mode 100644index 000000000000..9499b6ac5a6a--- /dev/null+++ b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutConfigMutations.test.tsx@@ -0,0 +1,116 @@+import type { ScoutConfig } from "@posthog/api-client/posthog-client";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { act, renderHook, waitFor } from "@testing-library/react";+import type { ReactNode } from "react";+import { beforeEach, describe, expect, it, vi } from "vitest";++const updateScoutConfig = vi.hoisted(() => vi.fn());++vi.mock("@posthog/ui/features/auth/store", () => ({+ useAuthStateValue: (+ select: (state: { currentProjectId: number | null }) => unknown,+ ) => select({ currentProjectId: 42 }),+}));+vi.mock("@posthog/ui/features/auth/authClient", () => ({+ useAuthenticatedClient: () => ({ updateScoutConfig }),+}));+const toastError = vi.hoisted(() => vi.fn());+vi.mock("@posthog/ui/primitives/toast", () => ({+ toast: { error: toastError },+}));+vi.mock("@posthog/ui/shell/analytics", () => ({ track: vi.fn() }));++import { scoutQueryKeys } from "./scoutQueryKeys";+import { useScoutConfigMutations } from "./useScoutConfigMutations";++const CONFIG = {+ id: "config-1",+ skill_name: "signals-scout-error-tracking",+ enabled: true,+ emit: true,+ run_interval_minutes: 1440,+ run_cron_schedule: "0 9 * * 1",+} as ScoutConfig;++let queryClient: QueryClient;++function wrapper({ children }: { children: ReactNode }) {+ return (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );+}++function savedCron(): string | null | undefined {+ return queryClient+ .getQueryData<ScoutConfig[]>(scoutQueryKeys.configs(42))+ ?.find((config) => config.id === CONFIG.id)?.run_cron_schedule;+}++describe("useScoutConfigMutations", () => {+ beforeEach(() => {+ updateScoutConfig.mockReset();+ toastError.mockReset();+ queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ queryClient.setQueryData(scoutQueryKeys.configs(42), [CONFIG]);+ });++ // Picking weekly reveals the run day picker straight away, so a second choice can be made while+ // the first PATCH is still out. Both writing `run_cron_schedule` at once lets the server commit+ // them in either order and keep the earlier one.+ it("sends a second schedule choice only after the first request settles", async () => {+ let resolveFirst: (config: ScoutConfig) => void = () => {};+ updateScoutConfig+ .mockImplementationOnce(+ () =>+ new Promise<ScoutConfig>((resolve) => {+ resolveFirst = resolve;+ }),+ )+ .mockImplementation(async (_project, _id, updates) => ({+ ...CONFIG,+ ...updates,+ }));++ const { result } = renderHook(() => useScoutConfigMutations(), { wrapper });++ act(() => {+ void result.current.updateConfig(CONFIG.id, {+ run_cron_schedule: "0 9 * * 1",+ });+ void result.current.updateConfig(CONFIG.id, {+ run_cron_schedule: "0 9 * * 4",+ });+ });++ expect(updateScoutConfig).toHaveBeenCalledTimes(1);+ // The later choice still shows while it waits its turn.+ expect(savedCron()).toBe("0 9 * * 4");++ await act(async () => {+ resolveFirst({ ...CONFIG, run_cron_schedule: "0 9 * * 1" });+ });++ await waitFor(() => expect(updateScoutConfig).toHaveBeenCalledTimes(2));+ expect(updateScoutConfig).toHaveBeenLastCalledWith(42, CONFIG.id, {+ run_cron_schedule: "0 9 * * 4",+ });+ await waitFor(() => expect(savedCron()).toBe("0 9 * * 4"));+ });++ it("rolls the schedule back to the saved one when the write is refused", async () => {+ updateScoutConfig.mockRejectedValue(new Error("Not a valid cron"));++ const { result } = renderHook(() => useScoutConfigMutations(), { wrapper });++ await act(async () => {+ await result.current.updateConfig(CONFIG.id, {+ run_cron_schedule: "0 9 * * 4",+ });+ });++ expect(savedCron()).toBe("0 9 * * 1");+ expect(toastError).toHaveBeenCalledWith("Not a valid cron");+ });+});diff --git a/products/desktop/packages/ui/src/features/scouts/hooks/useScoutConfigMutations.ts b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutConfigMutations.tsindex e628797aa570..686be45f712b 100644--- a/products/desktop/packages/ui/src/features/scouts/hooks/useScoutConfigMutations.ts+++ b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutConfigMutations.ts@@ -13,6 +13,7 @@ export interface ScoutConfigUpdate {enabled?: boolean;emit?: boolean;run_interval_minutes?: number;+ run_cron_schedule?: string | null;auto_pause_exempt?: boolean;}@@ -20,6 +21,7 @@ const CONFIG_SETTINGS = ["enabled","emit","run_interval_minutes",+ "run_cron_schedule","auto_pause_exempt",] as const;@@ -55,47 +57,74 @@ export function useScoutConfigMutations() {const queryClient = useQueryClient();const projectId = useAuthStateValue((state) => state.currentProjectId);const inFlightCount = useRef(0);+ const inFlightConfigIds = useRef(new Set<string>());+ const queuedUpdates = useRef(new Map<string, ScoutConfigUpdate>());const updateConfig = useCallback(async (configId: string, updates: ScoutConfigUpdate) => {if (!client || !projectId) return;const queryKey = scoutQueryKeys.configs(projectId);- const previousConfig = queryClient+ const patchLocally = (patch: Partial<ScoutConfig>) =>+ queryClient.setQueryData<ScoutConfig[]>(queryKey, (configs) =>+ configs?.map((config) =>+ config.id === configId ? { ...config, ...patch } : config,+ ),+ );+ // The schedule mode, the run day and the run time all write `run_cron_schedule`, so a+ // second choice can arrive while the first PATCH is still out. Sending both at once lets+ // the server commit them in either order and keep the earlier one, so queue the later+ // update behind the active request instead.+ if (inFlightConfigIds.current.has(configId)) {+ patchLocally(updates);+ queuedUpdates.current.set(configId, {+ ...queuedUpdates.current.get(configId),+ ...updates,+ });+ return;+ }+ let confirmedConfig = queryClient.getQueryData<ScoutConfig[]>(queryKey)?.find((config) => config.id === configId);- queryClient.setQueryData<ScoutConfig[]>(queryKey, (configs) =>- configs?.map((config) =>- config.id === configId ? { ...config, ...updates } : config,- ),- );+ patchLocally(updates);+ inFlightConfigIds.current.add(configId);inFlightCount.current++;+ let updatesToSend: ScoutConfigUpdate | undefined = updates;try {- const updated = await client.updateScoutConfig(- projectId,- configId,- updates,- );- queryClient.setQueryData<ScoutConfig[]>(queryKey, (configs) =>- configs?.map((config) => (config.id === configId ? updated : config)),- );- trackConfigChange(previousConfig, updates, true);+ while (updatesToSend) {+ const previousConfig = confirmedConfig;+ const updated = await client.updateScoutConfig(+ projectId,+ configId,+ updatesToSend,+ );+ trackConfigChange(previousConfig, updatesToSend, true);+ confirmedConfig = updated;+ updatesToSend = queuedUpdates.current.get(configId);+ queuedUpdates.current.delete(configId);+ // Keep a queued choice on screen while its own request runs.+ patchLocally({ ...updated, ...updatesToSend });+ }} catch (error: unknown) {- // Roll back only this config so concurrent edits to other scouts- // survive; same-scout overlap reconciles via the settle invalidation.- if (previousConfig) {+ // Roll back only this config, so edits to other scouts survive.+ if (confirmedConfig) {+ const rolledBack = confirmedConfig;queryClient.setQueryData<ScoutConfig[]>(queryKey, (configs) =>configs?.map((config) =>- config.id === configId ? previousConfig : config,+ config.id === configId ? rolledBack : config,),);}- trackConfigChange(previousConfig, updates, false);+ trackConfigChange(confirmedConfig, updatesToSend ?? updates, false);const message =error instanceof Error? error.message: "Failed to update scout config";toast.error(message);} finally {+ // A queued update belongs to the schedule the failed request was building on, so it is+ // dropped with the rollback rather than sent against a state the server never took.+ queuedUpdates.current.delete(configId);+ inFlightConfigIds.current.delete(configId);// Concurrent PATCHes to one scout can settle out of order; once the// last one lands, reconcile the cache against the server.inFlightCount.current--;diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.stories.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.stories.tsxindex a90965a19837..a79cf41e0fef 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.stories.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.stories.tsx@@ -49,3 +49,13 @@ export const DryRun: Story = {export const Disabled: Story = {render: () => <EditableConfigForm initialConfig={{ ...mockScoutConfigs[0], enabled: false }} />,}++// A weekly schedule: the day picker and the time picker together write a `30 8 * * 4`-style cron.+export const WeeklySchedule: Story = {+ render: () => <EditableConfigForm initialConfig={{ ...mockScoutConfigs[0], run_cron_schedule: '30 8 * * 4' }} />,+}++// A schedule the presets cannot express. The expression is editable, and validated as it is typed.+export const CustomCronSchedule: Story = {+ render: () => <EditableConfigForm initialConfig={{ ...mockScoutConfigs[0], run_cron_schedule: '0 9 * * 1-5' }} />,+}diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.test.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.test.tsxindex 939c71638b87..7e7b5c0d73bd 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.test.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.test.tsx@@ -103,14 +103,95 @@ describe('ScoutConfigForm', () => {unmount()})- it('shows an unexpressible cron as a read-only custom mode without a time picker', () => {+ it('saves a weekly run day and keeps the run time', () => {const onUpdate = jest.fn()- const { container, getByText, unmount } = render(- <ScoutConfigForm config={{ ...config, run_cron_schedule: '0 9 * * 1-5' }} onUpdate={onUpdate} />+ const { getByLabelText, getByText, container, unmount } = render(+ <ScoutConfigForm config={{ ...config, run_cron_schedule: '30 8 * * 1' }} onUpdate={onUpdate} />)+ expect(container.querySelector<HTMLInputElement>('input[type="time"]')?.value).toBe('08:30')++ fireEvent.click(getByLabelText('signals-scout-general run day'))+ fireEvent.click(getByText('Thursday'))+ expect(onUpdate).toHaveBeenCalledWith('config-1', { run_cron_schedule: '30 8 * * 4' })+ unmount()+ })++ // A failed write rolls the config back, so the picker has to follow it. Holding the picked mode+ // would report a schedule the scout does not run on, and the obvious retry sends nothing.+ it('follows the config back when a schedule write does not stick', () => {+ const onUpdate = jest.fn()+ const rollingConfig = { ...config, run_cron_schedule: null }+ const { getByText, container, rerender, unmount } = render(+ <ScoutConfigForm config={rollingConfig} onUpdate={onUpdate} />+ )++ expect(container.querySelector('input[type="time"]')).toBeNull()++ fireEvent.click(getByText('Daily'))+ fireEvent.click(getByText('Daily at a set time'))+ expect(onUpdate).toHaveBeenCalledWith('config-1', { run_cron_schedule: '0 9 * * *' })++ rerender(<ScoutConfigForm config={{ ...rollingConfig, run_cron_schedule: '0 9 * * *' }} onUpdate={onUpdate} />)+ expect(container.querySelector('input[type="time"]')).not.toBeNull()++ rerender(<ScoutConfigForm config={rollingConfig} onUpdate={onUpdate} />)expect(container.querySelector('input[type="time"]')).toBeNull()- expect(getByText('Custom (0 9 * * 1-5)')).toBeTruthy()+ unmount()+ })++ // Custom is the one mode no config can express while the field is still empty, so the picker+ // holds it locally instead of waiting for a write.+ it('opens an empty custom field without writing anything', () => {+ const onUpdate = jest.fn()+ const { getByText, getByLabelText, unmount } = render(+ <ScoutConfigForm config={{ ...config, run_cron_schedule: null }} onUpdate={onUpdate} />+ )++ fireEvent.click(getByText('Daily'))+ fireEvent.click(getByText('Custom cron'))+ expect(getByLabelText('signals-scout-general cron expression')).toBeTruthy()+ expect(onUpdate).not.toHaveBeenCalled()+ unmount()+ })++ it('edits a day-restricted cron in place and refuses one the scheduler would reject', () => {+ const onUpdate = jest.fn()+ const { getByLabelText, getByText, unmount } = render(+ <ScoutConfigForm config={{ ...config, run_cron_schedule: '0 9 1 2 *' }} onUpdate={onUpdate} />+ )+ const input = getByLabelText('signals-scout-general cron expression')++ fireEvent.change(input, { target: { value: '0,15 9 * * *' } })+ fireEvent.blur(input)+ expect(getByText('Runs must be at least 30 minutes apart.')).toBeTruthy()+ expect(onUpdate).not.toHaveBeenCalled()++ fireEvent.change(input, { target: { value: '0 9 * * 1-5' } })+ fireEvent.blur(input)+ expect(onUpdate).toHaveBeenCalledWith('config-1', { run_cron_schedule: '0 9 * * 1-5' })+ unmount()+ })++ // The fleet polls while the panel is open, so a schedule set from another tab or by a teammate+ // reaches the form under the open field. An untouched field must follow it, and leaving the+ // field without typing must not write the expression it opened with back over it.+ it('follows a cron set elsewhere until the field is typed in', () => {+ const onUpdate = jest.fn()+ const customConfig = { ...config, run_cron_schedule: '0 9 1 2 *' }+ const { getByLabelText, rerender, unmount } = render(+ <ScoutConfigForm config={customConfig} onUpdate={onUpdate} />+ )+ const input = getByLabelText('signals-scout-general cron expression')++ expect(input).toHaveValue('0 9 1 2 *')++ rerender(<ScoutConfigForm config={{ ...customConfig, run_cron_schedule: '0 9 * * 1-5' }} onUpdate={onUpdate} />)+ expect(input).toHaveValue('0 9 * * 1-5')++ fireEvent.focus(input)+ fireEvent.blur(input)+ expect(onUpdate).not.toHaveBeenCalled()unmount()})diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.tsxindex 4e8ebfcd82ef..8d9cb65e5c97 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.tsx@@ -1,9 +1,11 @@import { useValues } from 'kea'+import { useState } from 'react'import { IconTrash } from '@posthog/icons'import { LemonButton, LemonDialog, LemonInput, LemonSelect, LemonSwitch, Tooltip } from '@posthog/lemon-ui'import { FEATURE_FLAGS } from 'lib/constants'+import { describeCron } from 'lib/cron'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { teamLogic } from 'scenes/teamLogic'@@ -15,13 +17,20 @@ import { SignalScoutConfigNetworkAccessEnumApi } from 'products/signals/frontendimport {dailyCronToTime,+ dayTimeToWeeklyCron,DEFAULT_SCOUT_DAILY_TIME,+ DEFAULT_SCOUT_WEEKLY_DAY,getScoutScheduleMode,getScoutScheduleOptions,prettifyScoutSkillName,+ SCOUT_CRON_MAX_LENGTH,SCOUT_CUSTOM_CRON_SCHEDULE_MODE,SCOUT_DAILY_AT_SCHEDULE_MODE,+ SCOUT_WEEKDAY_OPTIONS,+ SCOUT_WEEKLY_ON_SCHEDULE_MODE,+ scoutCronScheduleError,timeToDailyCron,+ weeklyCronToDayTime,} from '../../../utils/scoutRunsWindow'import { ScoutMcpServersPicker } from './ScoutMcpServersPicker'import { ScoutSlackDestination } from './ScoutSlackDestination'@@ -81,8 +90,15 @@ export function ScoutConfigForm({}: ScoutConfigFormProps): JSX.Element {const { timezone: projectTimezone } = useValues(teamLogic)const { featureFlags } = useValues(featureFlagLogic)- const dailyTime = dailyCronToTime(config.run_cron_schedule)- const scheduleMode = getScoutScheduleMode(config)+ const weekly = weeklyCronToDayTime(config.run_cron_schedule)+ const runTime = dailyCronToTime(config.run_cron_schedule) ?? weekly?.time ?? DEFAULT_SCOUT_DAILY_TIME+ const weeklyDay = weekly?.day ?? DEFAULT_SCOUT_WEEKLY_DAY+ const savedScheduleMode = getScoutScheduleMode(config)+ // The saved config cannot express "the user opened the custom mode but has not typed a valid+ // expression yet", so that one pick is held here. Every other mode writes at once, so the+ // config stays the truth for them, including when a failed write rolls it back.+ const [customModePicked, setCustomModePicked] = useState(false)+ const scheduleMode = customModePicked ? SCOUT_CUSTOM_CRON_SCHEDULE_MODE : savedScheduleModeconst controlsDisabledReason = updating? 'Saving scout settings': config.enabled@@ -114,25 +130,26 @@ export function ScoutConfigForm({<div className="flex flex-col min-w-0"><span className="text-xs text-default">Schedule</span><span className="text-[11.5px] text-muted">- {scheduleMode === SCOUT_CUSTOM_CRON_SCHEDULE_MODE- ? 'A cron schedule set via the API'- : 'A rolling cadence, or a set time each day'}+ A rolling cadence, a set time each day or week, or a cron expression</span></div><LemonSelectsize="small"value={scheduleMode}- options={getScoutScheduleOptions(config)}+ options={getScoutScheduleOptions(config, { customCronEditable: true })}disabledReason={controlsDisabledReason}className="w-44"onChange={(value) => {- if (value === scheduleMode || value === SCOUT_CUSTOM_CRON_SCHEDULE_MODE) {+ setCustomModePicked(value === SCOUT_CUSTOM_CRON_SCHEDULE_MODE)+ if (value === savedScheduleMode || value === SCOUT_CUSTOM_CRON_SCHEDULE_MODE) {return}if (value === SCOUT_DAILY_AT_SCHEDULE_MODE) {- onUpdate(config.id, {- run_cron_schedule: timeToDailyCron(dailyTime ?? DEFAULT_SCOUT_DAILY_TIME),- })+ onUpdate(config.id, { run_cron_schedule: timeToDailyCron(runTime) })+ return+ }+ if (value === SCOUT_WEEKLY_ON_SCHEDULE_MODE) {+ onUpdate(config.id, { run_cron_schedule: dayTimeToWeeklyCron(weeklyDay, runTime) })return}// A rolling cadence replaces any cron — the schedule is one or the other.@@ -140,7 +157,29 @@ export function ScoutConfigForm({}}/></div>- {scheduleMode === SCOUT_DAILY_AT_SCHEDULE_MODE ? (+ {scheduleMode === SCOUT_WEEKLY_ON_SCHEDULE_MODE ? (+ <div className="flex items-center justify-between gap-4">+ <div className="flex flex-col min-w-0">+ <span className="text-xs text-default">Run day</span>+ <span className="text-[11.5px] text-muted">The scout runs once a week, on this day</span>+ </div>+ <LemonSelect+ size="small"+ value={weeklyDay}+ options={SCOUT_WEEKDAY_OPTIONS}+ disabledReason={controlsDisabledReason}+ className="w-44"+ onChange={(value) => {+ const runCronSchedule = dayTimeToWeeklyCron(value, runTime)+ if (runCronSchedule !== config.run_cron_schedule) {+ onUpdate(config.id, { run_cron_schedule: runCronSchedule })+ }+ }}+ aria-label={`${config.skill_name} run day`}+ />+ </div>+ ) : null}+ {scheduleMode === SCOUT_DAILY_AT_SCHEDULE_MODE || scheduleMode === SCOUT_WEEKLY_ON_SCHEDULE_MODE ? (<div className="flex items-center justify-between gap-4"><div className="flex flex-col min-w-0"><span className="text-xs text-default">Run time</span>@@ -151,7 +190,7 @@ export function ScoutConfigForm({type="time"step={60}size="small"- defaultValue={dailyTime ?? DEFAULT_SCOUT_DAILY_TIME}+ defaultValue={runTime}disabledReason={controlsDisabledReason}className="w-44"onBlur={(event) => {@@ -161,7 +200,10 @@ export function ScoutConfigForm({if (!value) {return}- const runCronSchedule = timeToDailyCron(value)+ const runCronSchedule =+ scheduleMode === SCOUT_WEEKLY_ON_SCHEDULE_MODE+ ? dayTimeToWeeklyCron(weeklyDay, value)+ : timeToDailyCron(value)if (runCronSchedule !== config.run_cron_schedule) {onUpdate(config.id, { run_cron_schedule: runCronSchedule })}@@ -169,6 +211,14 @@ export function ScoutConfigForm({/></div>) : null}+ {scheduleMode === SCOUT_CUSTOM_CRON_SCHEDULE_MODE ? (+ <ScoutCustomCronField+ config={config}+ onUpdate={onUpdate}+ disabledReason={controlsDisabledReason}+ projectTimezone={projectTimezone}+ />+ ) : null}<div className="flex items-center justify-between gap-4"><div className="flex flex-col min-w-0"><span className="text-xs text-default">Network access</span>@@ -287,6 +337,65 @@ export function ScoutConfigForm({)}+/**+ * Raw cron editor for the schedule the presets cannot express — weekday runs, several days a week,+ * monthly. Validated against the same rules the config API applies, so a typo is caught before the+ * PATCH, and saved on blur or Enter.+ */+function ScoutCustomCronField({+ config,+ onUpdate,+ disabledReason,+ projectTimezone,+}: {+ config: SignalScoutConfig+ onUpdate: (configId: string, updates: SignalScoutConfigUpdate) => void+ disabledReason?: string+ projectTimezone: string+}): JSX.Element {+ // Null until something is typed, so an untouched field follows a schedule set elsewhere and a+ // blur that changed nothing writes nothing. Once typed, the text stays put — a rejected save+ // must leave the expression on screen to correct.+ const [draft, setDraft] = useState<string | null>(null)+ const expression = (draft ?? config.run_cron_schedule ?? '').trim()+ // An empty field is a half-finished edit, not a mistake, so it stays neutral and saves nothing.+ const error = expression ? scoutCronScheduleError(expression) : null+ const hint = error ?? describeCron(expression)+ const save = (): void => {+ if (draft === null || !expression || error || expression === config.run_cron_schedule) {+ return+ }+ onUpdate(config.id, { run_cron_schedule: expression })+ }++ return (+ <div className="flex items-start justify-between gap-4">+ <div className="flex flex-col min-w-0">+ <span className="text-xs text-default">Cron expression</span>+ <span className="text-[11.5px] text-muted">+ Minute, hour, day of month, month, day of week, in the project timezone ({projectTimezone})+ </span>+ </div>+ <div className="flex flex-col gap-1 w-44 shrink-0">+ <LemonInput+ size="small"+ value={draft ?? config.run_cron_schedule ?? ''}+ placeholder="0 9 * * 1-5"+ maxLength={SCOUT_CRON_MAX_LENGTH}+ className="font-mono"+ status={error ? 'danger' : 'default'}+ disabledReason={disabledReason}+ onChange={setDraft}+ onBlur={save}+ onPressEnter={save}+ aria-label={`${config.skill_name} cron expression`}+ />+ {hint ? <span className={`text-[11.5px] ${error ? 'text-danger' : 'text-muted'}`}>{hint}</span> : null}+ </div>+ </div>+ )+}+/*** Confirm-then-delete for a custom scout. Deletion archives the scout's skill (the permanent off* switch — the coordinator won't re-seed a tombstoned skill or re-create its config) and removesdiff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutCreateModal.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutCreateModal.tsxindex 7ec925f05e0b..00620ac4eb01 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutCreateModal.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutCreateModal.tsx@@ -29,6 +29,8 @@ import {getScoutScheduleOptions,SCOUT_CUSTOM_CRON_SCHEDULE_MODE,SCOUT_DAILY_AT_SCHEDULE_MODE,+ SCOUT_WEEKDAY_OPTIONS,+ SCOUT_WEEKLY_ON_SCHEDULE_MODE,SIGNALS_SCOUT_SKILL_PREFIX,} from '../../../utils/scoutRunsWindow'import { MAX_SCOUT_TAGS, normalizeScoutTags } from '../../../utils/scoutTags'@@ -56,8 +58,13 @@ export function ScoutCreateModal({ isOpen, onClose, initialValues, onCreated }:scoutCreateFormTouches,showScoutCreateFormErrors,} = useValues(logic)- const { resetScoutCreateForm, resetMcpServersDefaulted, setScoutCreateDailyTime, setScoutCreateScheduleMode } =- useActions(logic)+ const {+ resetScoutCreateForm,+ resetMcpServersDefaulted,+ setScoutCreateDailyTime,+ setScoutCreateWeeklyDay,+ setScoutCreateScheduleMode,+ } = useActions(logic)const { timezone: projectTimezone } = useValues(teamLogic)const scheduleMode = getScoutScheduleMode(scoutCreateForm.config)@@ -228,7 +235,7 @@ export function ScoutCreateModal({ isOpen, onClose, initialValues, onCreated }:help={scheduleMode === SCOUT_CUSTOM_CRON_SCHEDULE_MODE? 'A cron schedule provided by the opening context'- : 'Choose a rolling cadence, or a set time each day'+ : 'Choose a rolling cadence, or a set time each day or week'}><LemonSelect@@ -237,7 +244,17 @@ export function ScoutCreateModal({ isOpen, onClose, initialValues, onCreated }:onChange={setScoutCreateScheduleMode}/></LemonField.Pure>- {scheduleMode === SCOUT_DAILY_AT_SCHEDULE_MODE ? (+ {scheduleMode === SCOUT_WEEKLY_ON_SCHEDULE_MODE ? (+ <LemonField.Pure label="Run day" help="The scout runs once a week, on this day">+ <LemonSelect+ value={scoutCreateForm.weeklyDay}+ options={SCOUT_WEEKDAY_OPTIONS}+ onChange={setScoutCreateWeeklyDay}+ />+ </LemonField.Pure>+ ) : null}+ {scheduleMode === SCOUT_DAILY_AT_SCHEDULE_MODE ||+ scheduleMode === SCOUT_WEEKLY_ON_SCHEDULE_MODE ? (<LemonField.Pure label="Run time" help={`Uses the project timezone (${projectTimezone})`}><LemonInputtype="time"diff --git a/products/signals/frontend/inbox/logics/scoutCreateModalLogic.test.ts b/products/signals/frontend/inbox/logics/scoutCreateModalLogic.test.tsindex 3a6d81d077a2..c78fe02d89d8 100644--- a/products/signals/frontend/inbox/logics/scoutCreateModalLogic.test.ts+++ b/products/signals/frontend/inbox/logics/scoutCreateModalLogic.test.ts@@ -16,7 +16,7 @@ import type {import { signalsScoutCreate } from 'products/signals/frontend/generated/api'import type { SignalScoutCreateResponseApi } from 'products/signals/frontend/generated/api.schemas'-import { SCOUT_DAILY_AT_SCHEDULE_MODE } from '../utils/scoutRunsWindow'+import { SCOUT_DAILY_AT_SCHEDULE_MODE, SCOUT_WEEKLY_ON_SCHEDULE_MODE } from '../utils/scoutRunsWindow'import { ScoutCreateModalLogicProps, scoutCreateModalLogic, scoutCreateModalLogicKey } from './scoutCreateModalLogic'jest.mock('products/signals/frontend/generated/api', () => ({@@ -156,6 +156,7 @@ describe('scoutCreateModalLogic', () => {description: 'Investigates recurring checkout failures.',body: 'Inspect checkout failure signals and report meaningful regressions.',dailyTime: '09:00',+ weeklyDay: '1',config: {enabled: false,emit: false,@@ -309,6 +310,41 @@ describe('scoutCreateModalLogic', () => {)})+ it('submits a weekly day and run time as a cron schedule', async () => {+ mockSignalsScoutCreate.mockResolvedValue(CREATED_SCOUT)+ logic = scoutCreateModalLogic({+ logicKey: 'weekly-scout',+ initialValues: {+ name: 'signals-scout-checkout-failures',+ description: 'Investigates recurring checkout failures.',+ body: 'Inspect checkout failure signals and report meaningful regressions.',+ },+ onClose,+ onCreated,+ })+ logic.mount()++ logic.actions.setScoutCreateScheduleMode(SCOUT_WEEKLY_ON_SCHEDULE_MODE)+ logic.actions.setScoutCreateWeeklyDay('4')+ logic.actions.setScoutCreateDailyTime('14:45')++ await expectLogic(logic).toMatchValues({+ scoutCreateForm: expect.objectContaining({+ weeklyDay: '4',+ dailyTime: '14:45',+ config: expect.objectContaining({ run_cron_schedule: '45 14 * * 4' }),+ }),+ })+ await expectLogic(logic, () => logic.actions.submitScoutCreateForm()).toFinishAllListeners()++ expect(mockSignalsScoutCreate).toHaveBeenCalledWith(+ String(MOCK_TEAM_ID),+ expect.objectContaining({+ config: expect.objectContaining({ run_cron_schedule: '45 14 * * 4' }),+ })+ )+ })+it('does not submit a daily schedule without a run time', async () => {mockSignalsScoutCreate.mockResolvedValue(CREATED_SCOUT)logic = scoutCreateModalLogic({@@ -424,6 +460,38 @@ describe('scoutCreateModalLogic', () => {reopened.unmount()})+ it('picks a run day for a draft persisted before the weekly mode existed', async () => {+ const logicKey = scoutCreateModalLogicKey(undefined)+ const first = scoutCreateModalLogic({ logicKey, onClose })+ first.mount()+ first.actions.setScoutCreateFormValue('body', 'Watch checkout latency and report spikes.')+ await expectLogic(first).toFinishAllListeners()+ first.unmount()++ // kea-localstorage restores the stored object over the whole reducer default instead of+ // merging in fields added since, so a draft written before the weekly mode shipped comes+ // back with no run day at all. Strip the key to reproduce that draft.+ for (const key of Object.keys(localStorage)) {+ const stored = localStorage.getItem(key)+ if (stored?.includes('"weeklyDay"')) {+ const draft = JSON.parse(stored)+ delete draft.weeklyDay+ localStorage.setItem(key, JSON.stringify(draft))+ }+ }++ logic = scoutCreateModalLogic({ logicKey, onClose })+ logic.mount()+ logic.actions.setScoutCreateScheduleMode(SCOUT_WEEKLY_ON_SCHEDULE_MODE)++ await expectLogic(logic).toMatchValues({+ scoutCreateForm: expect.objectContaining({+ weeklyDay: '1',+ config: expect.objectContaining({ run_cron_schedule: '0 9 * * 1' }),+ }),+ })+ })+it('does not restore a persisted draft after switching to another project', async () => {const logicKey = scoutCreateModalLogicKey(undefined)const first = scoutCreateModalLogic({ logicKey, onClose })diff --git a/products/signals/frontend/inbox/logics/scoutCreateModalLogic.ts b/products/signals/frontend/inbox/logics/scoutCreateModalLogic.tsindex 3b99cf80ed8e..62593dc18cf5 100644--- a/products/signals/frontend/inbox/logics/scoutCreateModalLogic.ts+++ b/products/signals/frontend/inbox/logics/scoutCreateModalLogic.ts@@ -24,12 +24,16 @@ import { SKILL_DESCRIPTION_MAX_LENGTH, validateSkillName } from 'products/skillsimport { isInboxRedesignEnabled } from '../utils/inboxRedesign'import {dailyCronToTime,+ dayTimeToWeeklyCron,DEFAULT_SCOUT_DAILY_TIME,+ DEFAULT_SCOUT_WEEKLY_DAY,SCOUT_CUSTOM_CRON_SCHEDULE_MODE,SCOUT_DAILY_AT_SCHEDULE_MODE,+ SCOUT_WEEKLY_ON_SCHEDULE_MODE,SIGNALS_SCOUT_SKILL_PREFIX,stripScoutPrefix,timeToDailyCron,+ weeklyCronToDayTime,} from '../utils/scoutRunsWindow'import { MAX_SCOUT_TAG_LENGTH, MAX_SCOUT_TAGS, normalizeScoutTag } from '../utils/scoutTags'import { scoutMcpServersLogic } from './scoutMcpServersLogic'@@ -44,7 +48,10 @@ type ScoutCreateConfigFormValues = Required<export type ScoutCreateFormValues = Pick<SignalScoutCreateApi, 'name' | 'description' | 'body'> & {config: ScoutCreateConfigFormValues+ /** Run time for both the daily and the weekly mode, so switching between them keeps it. */dailyTime: string+ /** Cron day-of-week the weekly mode runs on. */+ weeklyDay: string}export type ScoutCreateInitialValues = Partial<Pick<SignalScoutCreateApi, 'name' | 'description' | 'body'>> & {@@ -63,6 +70,7 @@ export const DEFAULT_SCOUT_CREATE_FORM_VALUES: ScoutCreateFormValues = {description: '',body: '',dailyTime: DEFAULT_SCOUT_DAILY_TIME,+ weeklyDay: DEFAULT_SCOUT_WEEKLY_DAY,config: {enabled: true,emit: true,@@ -93,7 +101,11 @@ export function getScoutCreateFormValues(? stripScoutPrefix((initialValues?.name ?? '').trim()): (initialValues?.name ?? SIGNALS_SCOUT_SKILL_PREFIX),config,- dailyTime: dailyCronToTime(config.run_cron_schedule) ?? DEFAULT_SCOUT_DAILY_TIME,+ dailyTime:+ dailyCronToTime(config.run_cron_schedule) ??+ weeklyCronToDayTime(config.run_cron_schedule)?.time ??+ DEFAULT_SCOUT_DAILY_TIME,+ weeklyDay: weeklyCronToDayTime(config.run_cron_schedule)?.day ?? DEFAULT_SCOUT_WEEKLY_DAY,}}@@ -132,6 +144,20 @@ function isValidScoutDailyTime(dailyTime: string): boolean {return /^(?:[01]\d|2[0-3]):[0-5]\d$/.test(dailyTime)}+function isWeeklySchedule(config: ScoutCreateConfigFormValues): boolean {+ return weeklyCronToDayTime(config.run_cron_schedule) !== null+}++/**+ * The day the weekly mode writes. A draft persisted before that mode existed carries no day of its+ * own — kea-localstorage restores the stored object over the whole default rather than merging new+ * fields — so read the saved cron first and fall back to the default.+ */+function scoutWeeklyDay(form: ScoutCreateFormValues): string {+ const day = weeklyCronToDayTime(form.config.run_cron_schedule)?.day ?? form.weeklyDay+ return day && /^[0-6]$/.test(day) ? day : DEFAULT_SCOUT_WEEKLY_DAY+}+function scoutNameError(name: string, redesign: boolean): string | undefined {if (!redesign) {const normalizedName = name.trim()@@ -216,6 +242,9 @@ export interface scoutCreateModalLogicActions {setScoutCreateScheduleMode: (scheduleMode: string) => {scheduleMode: string}+ setScoutCreateWeeklyDay: (weeklyDay: string) => {+ weeklyDay: string+ }submitScoutCreateForm: () => {value: boolean}@@ -266,6 +295,7 @@ export const scoutCreateModalLogic: LogicWrapper<scoutCreateModalLogicType> = keactions({setScoutCreateScheduleMode: (scheduleMode: string) => ({ scheduleMode }),setScoutCreateDailyTime: (dailyTime: string) => ({ dailyTime }),+ setScoutCreateWeeklyDay: (weeklyDay: string) => ({ weeklyDay }),markMcpServersDefaulted: true,resetMcpServersDefaulted: true,}),@@ -307,7 +337,9 @@ export const scoutCreateModalLogic: LogicWrapper<scoutCreateModalLogicType> = ke: undefined,body: !body.trim() ? 'Instructions are required' : undefined,dailyTime:- dailyCronToTime(config.run_cron_schedule) !== null && !isValidScoutDailyTime(dailyTime)+ (dailyCronToTime(config.run_cron_schedule) !== null ||+ weeklyCronToDayTime(config.run_cron_schedule) !== null) &&+ !isValidScoutDailyTime(dailyTime)? 'Run time is required': undefined,config:@@ -394,15 +426,20 @@ export const scoutCreateModalLogic: LogicWrapper<scoutCreateModalLogicType> = keif (scheduleMode === SCOUT_CUSTOM_CRON_SCHEDULE_MODE) {return}- if (scheduleMode === SCOUT_DAILY_AT_SCHEDULE_MODE) {+ if (scheduleMode === SCOUT_DAILY_AT_SCHEDULE_MODE || scheduleMode === SCOUT_WEEKLY_ON_SCHEDULE_MODE) {const dailyTime = isValidScoutDailyTime(values.scoutCreateForm.dailyTime)? values.scoutCreateForm.dailyTime: DEFAULT_SCOUT_DAILY_TIME+ const weeklyDay = scoutWeeklyDay(values.scoutCreateForm)actions.setScoutCreateFormValues({dailyTime,+ weeklyDay,config: {...values.scoutCreateForm.config,- run_cron_schedule: timeToDailyCron(dailyTime),+ run_cron_schedule:+ scheduleMode === SCOUT_WEEKLY_ON_SCHEDULE_MODE+ ? dayTimeToWeeklyCron(weeklyDay, dailyTime)+ : timeToDailyCron(dailyTime),},})return@@ -429,7 +466,22 @@ export const scoutCreateModalLogic: LogicWrapper<scoutCreateModalLogicType> = kedailyTime,config: {...values.scoutCreateForm.config,- run_cron_schedule: timeToDailyCron(dailyTime),+ run_cron_schedule: isWeeklySchedule(values.scoutCreateForm.config)+ ? dayTimeToWeeklyCron(scoutWeeklyDay(values.scoutCreateForm), dailyTime)+ : timeToDailyCron(dailyTime),+ },+ })+ },+ setScoutCreateWeeklyDay: ({ weeklyDay }) => {+ const dailyTime = isValidScoutDailyTime(values.scoutCreateForm.dailyTime)+ ? values.scoutCreateForm.dailyTime+ : DEFAULT_SCOUT_DAILY_TIME+ actions.setScoutCreateFormValues({+ weeklyDay,+ dailyTime,+ config: {+ ...values.scoutCreateForm.config,+ run_cron_schedule: dayTimeToWeeklyCron(weeklyDay, dailyTime),},})},diff --git a/products/signals/frontend/inbox/utils/scoutRunsWindow.test.ts b/products/signals/frontend/inbox/utils/scoutRunsWindow.test.tsindex f397d253371b..f934064eab04 100644--- a/products/signals/frontend/inbox/utils/scoutRunsWindow.test.ts+++ b/products/signals/frontend/inbox/utils/scoutRunsWindow.test.ts@@ -7,8 +7,15 @@ import {deriveRunOutcome,mostRecentEmittedRuns,runMatchesFilter,+ dayTimeToWeeklyCron,+ getScoutScheduleMode,+ SCOUT_CUSTOM_CRON_SCHEDULE_MODE,+ SCOUT_DAILY_AT_SCHEDULE_MODE,+ SCOUT_WEEKLY_ON_SCHEDULE_MODE,ScoutRunOutcome,+ scoutCronScheduleError,scoutReportActivityLabel,+ weeklyCronToDayTime,} from './scoutRunsWindow'const NOW = new Date('2026-06-27T22:00:00Z')@@ -135,3 +142,60 @@ describe('scoutRunsWindow report channel', () => {})})})++describe('scout schedule modes', () => {+ it.each<[string, string | null, string]>([+ ['a rolling interval', null, '1440'],+ ['a plain daily cron', '0 9 * * *', SCOUT_DAILY_AT_SCHEDULE_MODE],+ ['a single weekday cron', '30 8 * * 4', SCOUT_WEEKLY_ON_SCHEDULE_MODE],+ ['a Sunday cron written as 7', '30 8 * * 7', SCOUT_WEEKLY_ON_SCHEDULE_MODE],+ ['a weekday-range cron', '0 9 * * 1-5', SCOUT_CUSTOM_CRON_SCHEDULE_MODE],+ ['a monthly cron', '0 9 1 * *', SCOUT_CUSTOM_CRON_SCHEDULE_MODE],+ ])('reads %s as its own mode', (_label, runCronSchedule, expected) => {+ expect(getScoutScheduleMode({ run_interval_minutes: 1440, run_cron_schedule: runCronSchedule })).toEqual(+ expected+ )+ })++ it('round-trips a weekly day and time through the cron it writes', () => {+ expect(dayTimeToWeeklyCron('4', '08:30')).toEqual('30 8 * * 4')+ expect(weeklyCronToDayTime('30 8 * * 4')).toEqual({ day: '4', time: '08:30' })+ })++ it('reads the other Sunday spelling as the dropdown value', () => {+ expect(weeklyCronToDayTime('30 8 * * 7')).toEqual({ day: '0', time: '08:30' })+ })++ describe('scoutCronScheduleError', () => {+ it.each<[string, string]>([+ ['0 9 * * 1-5', 'weekdays'],+ ['30 8 * * 1,4', 'two days a week'],+ ['0 9 1 * *', 'the first of the month'],+ ['0 9,17 * * *', 'twice a day'],+ ['0 9 * * MON', 'a named weekday'],+ ['0 9 15 2 *', 'a real February date'],+ ['0 9 31 2,3 MON', 'a real date in one of the months'],+ ['10,50 0,23 * * 1', 'slots either side of midnight, but only one day a week'],+ ['0 9 * * 5#2', 'syntax only the backend models'],+ ['0 9 L * *', 'the last day of the month'],+ ['R 9 * * *', 'a random minute the scheduler picks'],+ ])('accepts %s (%s)', (expression) => {+ expect(scoutCronScheduleError(expression)).toBeNull()+ })++ it.each<[string, string]>([+ ['0 9 * *', 'Enter a five-field cron expression, like 0 9 * * 1-5.'],+ ['70 9 * * *', 'Enter a five-field cron expression, like 0 9 * * 1-5.'],+ ['not a cron at all', 'Enter a five-field cron expression, like 0 9 * * 1-5.'],+ ['0 0 31 2 *', 'This schedule never matches a real date. Check the day and month.'],+ ['0 0 31 2 MON', 'This schedule never matches a real date. Check the day and month.'],+ ['*/20 * * * *', 'Runs must be at least 30 minutes apart.'],+ ['0,15 9 * * *', 'Runs must be at least 30 minutes apart.'],+ ['10,50 0,23 * * *', 'Runs must be at least 30 minutes apart.'],+ ['*/1e2 9 * * *', 'Enter a five-field cron expression, like 0 9 * * 1-5.'],+ ['0 9 * * @', 'Enter a five-field cron expression, like 0 9 * * 1-5.'],+ ])('refuses %s', (expression, expected) => {+ expect(scoutCronScheduleError(expression)).toEqual(expected)+ })+ })+})diff --git a/products/signals/frontend/inbox/utils/scoutRunsWindow.ts b/products/signals/frontend/inbox/utils/scoutRunsWindow.tsindex 15b899b838c6..cece1e9de228 100644--- a/products/signals/frontend/inbox/utils/scoutRunsWindow.ts+++ b/products/signals/frontend/inbox/utils/scoutRunsWindow.ts@@ -456,9 +456,23 @@ export const RUN_INTERVAL_OPTIONS: RunIntervalOption[] = []export const SCOUT_DAILY_AT_SCHEDULE_MODE = 'daily_at'+export const SCOUT_WEEKLY_ON_SCHEDULE_MODE = 'weekly_on'export const SCOUT_CUSTOM_CRON_SCHEDULE_MODE = 'custom_cron'export const DEFAULT_SCOUT_DAILY_TIME = '09:00'+/** Cron day-of-week numbers, offered from Monday so the working week reads first. */+export const SCOUT_WEEKDAY_OPTIONS: { value: string; label: string }[] = [+ { value: '1', label: 'Monday' },+ { value: '2', label: 'Tuesday' },+ { value: '3', label: 'Wednesday' },+ { value: '4', label: 'Thursday' },+ { value: '5', label: 'Friday' },+ { value: '6', label: 'Saturday' },+ { value: '0', label: 'Sunday' },+]++export const DEFAULT_SCOUT_WEEKLY_DAY = '1'+interface ScoutScheduleFields {run_interval_minutes: numberrun_cron_schedule?: string | null@@ -468,11 +482,24 @@ export function getScoutScheduleMode(config: ScoutScheduleFields): string {if (!config.run_cron_schedule) {return String(config.run_interval_minutes)}- return dailyCronToTime(config.run_cron_schedule) ? SCOUT_DAILY_AT_SCHEDULE_MODE : SCOUT_CUSTOM_CRON_SCHEDULE_MODE+ if (dailyCronToTime(config.run_cron_schedule)) {+ return SCOUT_DAILY_AT_SCHEDULE_MODE+ }+ if (weeklyCronToDayTime(config.run_cron_schedule)) {+ return SCOUT_WEEKLY_ON_SCHEDULE_MODE+ }+ return SCOUT_CUSTOM_CRON_SCHEDULE_MODE}-export function getScoutScheduleOptions(config: ScoutScheduleFields): { value: string; label: string }[] {- const scheduleMode = getScoutScheduleMode(config)+/**+ * `customCronEditable` says whether the surface can edit a raw expression. Where it cannot, the+ * custom option only appears for a config that already carries one, so the picker still shows what+ * the scout runs on.+ */+export function getScoutScheduleOptions(+ config: ScoutScheduleFields,+ { customCronEditable = false }: { customCronEditable?: boolean } = {}+): { value: string; label: string }[] {const options = RUN_INTERVAL_OPTIONS.map((option) => ({value: String(option.minutes),label: option.label,@@ -484,11 +511,11 @@ export function getScoutScheduleOptions(config: ScoutScheduleFields): { value: s})}options.push({ value: SCOUT_DAILY_AT_SCHEDULE_MODE, label: 'Daily at a set time' })- if (scheduleMode === SCOUT_CUSTOM_CRON_SCHEDULE_MODE) {- options.push({- value: SCOUT_CUSTOM_CRON_SCHEDULE_MODE,- label: `Custom (${config.run_cron_schedule})`,- })+ options.push({ value: SCOUT_WEEKLY_ON_SCHEDULE_MODE, label: 'Weekly on a set day' })+ if (customCronEditable) {+ options.push({ value: SCOUT_CUSTOM_CRON_SCHEDULE_MODE, label: 'Custom cron' })+ } else if (getScoutScheduleMode(config) === SCOUT_CUSTOM_CRON_SCHEDULE_MODE) {+ options.push({ value: SCOUT_CUSTOM_CRON_SCHEDULE_MODE, label: `Custom (${config.run_cron_schedule})` })}return options}@@ -526,6 +553,153 @@ export function timeToDailyCron(time: string): string {return `${Number(minutes)} ${Number(hours)} * * *`}+/**+ * "30 9 * * 4" → `{ day: '4', time: '09:30' }` when the cron is a plain weekly slot (the shape the+ * settings form writes). Multi-day and month-restricted expressions return null and are edited as+ * raw cron instead. Cron takes both 0 and 7 for Sunday; the dropdown offers 0, so 7 maps onto it.+ */+export function weeklyCronToDayTime(cron: string | null | undefined): { day: string; time: string } | null {+ const match = cron?.trim().match(/^(\d{1,2}) (\d{1,2}) \* \* ([0-7])$/)+ if (!match) {+ return null+ }+ return {+ day: match[3] === '7' ? '0' : match[3],+ time: `${match[2].padStart(2, '0')}:${match[1].padStart(2, '0')}`,+ }+}++/** `('4', '09:30')` → "30 9 * * 4" — the inverse of `weeklyCronToDayTime`. */+export function dayTimeToWeeklyCron(day: string, time: string): string {+ const [hours, minutes] = time.split(':')+ return `${Number(minutes)} ${Number(hours)} * * ${day}`+}++/** Longest cron expression the config API stores. */+export const SCOUT_CRON_MAX_LENGTH = 100++/** Shortest gap the scheduler allows between two runs, the same floor as `run_interval_minutes`. */+const SCOUT_CRON_MIN_GAP_MINUTES = 30++const CRON_MONTH_NAMES = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']+const CRON_DAY_NAMES = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']+const DAYS_IN_MONTH = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]++type CronFieldParse = { kind: 'values'; values: number[] } | { kind: 'unmodeled' } | { kind: 'invalid' }++function cronFieldNumber(token: string, offset: number, names: string[] | undefined): number | null {+ const named = names?.indexOf(token.toLowerCase())+ if (named !== undefined && named >= 0) {+ return named + offset+ }+ return /^\d{1,2}$/.test(token) ? Number(token) : null+}++/**+ * The values a single cron field matches. `unmodeled` covers the syntax this check does not+ * model (`L`, `R`, `#`, `?`): the backend decides those, because a client that guessed would+ * refuse an expression the scheduler accepts. Everything else croniter refuses, so a typo is+ * answered here instead of on the next save.+ */+function parseCronField(field: string, min: number, max: number, names?: string[]): CronFieldParse {+ if (/[#?]/.test(field)) {+ return { kind: 'unmodeled' }+ }+ if (!field || /[^0-9a-zA-Z*/,-]/.test(field)) {+ return { kind: 'invalid' }+ }+ const values = new Set<number>()+ for (const part of field.split(',')) {+ const [spec, stepToken, ...extra] = part.split('/')+ if (extra.length > 0 || spec === undefined) {+ return { kind: 'invalid' }+ }+ // A step is plain digits. `Number` alone would also read "1e2" and "0x10", which the+ // scheduler refuses.+ const step = stepToken === undefined ? 1 : /^\d+$/.test(stepToken) ? Number(stepToken) : 0+ if (step < 1) {+ return { kind: 'invalid' }+ }+ let from = min+ let to = max+ if (spec !== '*') {+ // croniter's own markers: "L" is the last day of the month, "R" a random slot in the+ // field. Neither is a calendar this check models, and it refuses every other letter+ // form anyway.+ if (/^[lr]$/i.test(spec)) {+ return { kind: 'unmodeled' }+ }+ const bounds = spec.split('-')+ if (bounds.length > 2) {+ return { kind: 'invalid' }+ }+ const parsed = bounds.map((token) => cronFieldNumber(token, min === 0 ? 0 : 1, names))+ if (parsed.some((value) => value === null || value < min || value > max)) {+ return { kind: 'invalid' }+ }+ from = parsed[0] as number+ // "5/10" is an open-ended step from 5, while a bare "5" is that one value.+ to = bounds.length === 2 ? (parsed[1] as number) : stepToken === undefined ? from : max+ // A wrapping range like "22-2" is an extension some parsers take and others reject.+ if (to < from) {+ return { kind: 'unmodeled' }+ }+ }+ for (let value = from; value <= to; value += step) {+ values.add(value)+ }+ }+ return { kind: 'values', values: [...values].sort((a, b) => a - b) }+}++/**+ * Why `expression` is not an acceptable scout cron schedule, or null when it is. Mirrors the four+ * rules the config API applies (`cron_schedule_error`) so the picker rejects a typo before the+ * PATCH. Expressions using syntax this check does not model pass and are left to the backend.+ */+export function scoutCronScheduleError(expression: string): string | null {+ const expr = expression.trim()+ if (expr.length > SCOUT_CRON_MAX_LENGTH) {+ return `Cron expressions must be ${SCOUT_CRON_MAX_LENGTH} characters or fewer.`+ }+ const fields = expr.split(/\s+/)+ const invalidShape = 'Enter a five-field cron expression, like 0 9 * * 1-5.'+ if (fields.length !== 5) {+ return invalidShape+ }+ const minutes = parseCronField(fields[0], 0, 59)+ const hours = parseCronField(fields[1], 0, 23)+ const daysOfMonth = parseCronField(fields[2], 1, 31)+ const months = parseCronField(fields[3], 1, 12, CRON_MONTH_NAMES)+ const daysOfWeek = parseCronField(fields[4], 0, 7, CRON_DAY_NAMES)+ const parsedFields = [minutes, hours, daysOfMonth, months, daysOfWeek]+ if (parsedFields.some((field) => field.kind === 'invalid')) {+ return invalidShape+ }+ // A day-of-month no month in the set reaches kills the schedule, whatever the weekday field+ // says: croniter refuses "0 0 31 2 MON" the same as "0 0 31 2 *".+ if (fields[2] !== '*' && daysOfMonth.kind === 'values' && months.kind === 'values') {+ const occurs = months.values.some((month) => daysOfMonth.values.some((day) => day <= DAYS_IN_MONTH[month - 1]))+ if (!occurs) {+ return 'This schedule never matches a real date. Check the day and month.'+ }+ }+ if (minutes.kind === 'values' && hours.kind === 'values') {+ const slots = hours.values.flatMap((hour) => minutes.values.map((minute) => hour * 60 + minute))+ const gaps = slots.slice(1).map((slot, index) => slot - slots[index])+ // A schedule that runs every day also runs across midnight, so the last slot of one day and+ // the first of the next are one more gap. A day-restricted schedule can skip days, so how+ // far its wrap reaches is left to the backend.+ if (fields[2] === '*' && fields[4] === '*') {+ gaps.push(slots[0] + 1440 - slots[slots.length - 1])+ }+ if (gaps.some((gap) => gap < SCOUT_CRON_MIN_GAP_MINUTES)) {+ return `Runs must be at least ${SCOUT_CRON_MIN_GAP_MINUTES} minutes apart.`+ }+ }+ return null+}+/** Short form for row badges: "hourly", "every 3h". */export function formatRunIntervalShort(minutes: number): string {if (minutes === 60) {