Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(scheduled_action): add routine activation control (#7197)
Will Hutchinson12d6fd215d05
diff --git a/.sqlx/query-d33f587b2e81db6c6d6c6db12629590b62c522e229149217f4106ff7ba16b101.json b/.sqlx/query-640a0155a74ead75139874494dc1e5d02af88a1f6cb855e3fc47cf4c923f7ac6.jsonsimilarity index 57%rename from .sqlx/query-d33f587b2e81db6c6d6c6db12629590b62c522e229149217f4106ff7ba16b101.jsonrename to .sqlx/query-640a0155a74ead75139874494dc1e5d02af88a1f6cb855e3fc47cf4c923f7ac6.jsonindex f8f5535922..2f7e827b5f 100644--- a/.sqlx/query-d33f587b2e81db6c6d6c6db12629590b62c522e229149217f4106ff7ba16b101.json+++ b/.sqlx/query-640a0155a74ead75139874494dc1e5d02af88a1f6cb855e3fc47cf4c923f7ac6.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n UPDATE scheduled_action\n SET claimed = $1, claim_token = $4, updated_at = now()\n WHERE id = $2\n AND (claimed IS NULL OR claimed < $3)\n ",+ "query": "\n UPDATE scheduled_action\n SET claimed = $1, claim_token = $4, updated_at = now()\n WHERE id = $2\n AND configuration_revision = $5\n AND (claimed IS NULL OR claimed < $3)\n ","describe": {"columns": [],"parameters": {@@ -8,10 +8,11 @@"Timestamptz","Uuid","Timestamptz",- "Uuid"+ "Uuid",+ "Int8"]},"nullable": []},- "hash": "d33f587b2e81db6c6d6c6db12629590b62c522e229149217f4106ff7ba16b101"+ "hash": "640a0155a74ead75139874494dc1e5d02af88a1f6cb855e3fc47cf4c923f7ac6"}diff --git a/apps/web/src/features/block-automation/component/Automation.test.tsx b/apps/web/src/features/block-automation/component/Automation.test.tsxindex c9140a8488..4556c95c5d 100644--- a/apps/web/src/features/block-automation/component/Automation.test.tsx+++ b/apps/web/src/features/block-automation/component/Automation.test.tsx@@ -22,6 +22,8 @@ const mocks = vi.hoisted(() => ({update: vi.fn(),create: vi.fn(),run: vi.fn(),+ setEnabled: vi.fn(),+ activationPending: (): boolean => false,openWithSplit: vi.fn(),setDisplayName: vi.fn(),changePrompt: (_value: string): void => {},@@ -116,6 +118,21 @@ vi.mock('@ui', () => ({<button {...props} />),cn: (...classes: string[]) => classes.join(' '),+ ToggleSwitch: (props: {+ label: string;+ checked: boolean;+ disabled?: boolean;+ onChange: (checked: boolean) => void;+ }) => (+ <button+ type="button"+ role="switch"+ aria-label={props.label}+ aria-checked={props.checked}+ disabled={props.disabled}+ onClick={() => props.onChange(!props.checked)}+ />+ ),}));vi.mock('@queries/chat', () => ({useChatQuery: (id: () => string) => {@@ -177,6 +194,12 @@ vi.mock('@queries/agent-schedule/schedules', () => ({useUpdateScheduleMutation: () => ({ mutateAsync: mocks.update }),useCreateScheduleMutation: () => ({ mutate: mocks.create, isPending: false }),useRunScheduleNowMutation: () => ({ mutate: mocks.run, isPending: false }),+ useSetScheduleEnabledMutation: () => ({+ mutate: mocks.setEnabled,+ get isPending() {+ return mocks.activationPending();+ },+ }),invalidateSchedules: vi.fn(),}));@@ -208,12 +231,14 @@ const events: ScheduledAction = {};let setSchedules: Setter<ScheduledAction[]>;let setStatus: Setter<string>;+let setActivationPending: Setter<boolean>;beforeEach(() => {vi.clearAllMocks();mocks.update.mockReset().mockResolvedValue(cron);vi.useFakeTimers();[mocks.status, setStatus] = createSignal('success');[mocks.readSchedules, setSchedules] = createSignal([cron]);+ [mocks.activationPending, setActivationPending] = createSignal(false);mocks.metadataStatus = () => 'success';mocks.chatMetadata = () => ({ chat: { name: 'Run transcript' } });mocks.agentMetadata = () => ({ name: 'Agent transcript' });@@ -242,6 +267,10 @@ function runButton(): HTMLButtonElement {return screen.getByRole('button', { name: 'Run Now' });}+function activeSwitch(): HTMLButtonElement {+ return screen.getByRole('switch', { name: 'Active' });+}+function selectedTarget(): RoutineTarget {return JSON.parse(screen.getByLabelText('Execution target').textContent!);}@@ -375,35 +404,17 @@ describe('automation execution target autosave', () => {expect(runButton().disabled).toBe(true);});- it('pauses a running action with only its saved configuration, discarding queued changes', async () => {+ it('pauses a routine with an invalid draft without saving the draft', async () => {render(() => <Automation />);- mocks.changeTarget(agentTarget);- const running = {- ...cron,- claimed: new Date().toISOString(),- task: {- ...(cron.task as object),- prompt: 'Keep system prompt',- future: true,- },- };- setSchedules([running]);- mocks.changeTarget({ kind: 'model', model: 'ignored-while-running' });- fireEvent.click(screen.getByText('Pause'));- await vi.advanceTimersByTimeAsync(300);- expect(mocks.update).toHaveBeenCalledExactlyOnceWith({- scheduleId: cron.id,- body: {- name: cron.name,- kind: cron.kind,- trigger: cron.trigger,- task: running.task,- enabled: false,- },+ mocks.changePrompt('');+ expect(screen.getByText('Prompt is required.')).toBeTruthy();+ fireEvent.click(activeSwitch());+ expect(mocks.setEnabled).toHaveBeenCalledExactlyOnceWith({+ scheduleId: 'routine-id',+ enabled: false,});- expect(- screen.getByRole<HTMLButtonElement>('button', { name: 'Resume' }).disabled- ).toBe(true);+ await vi.advanceTimersByTimeAsync(300);+ expect(mocks.update).not.toHaveBeenCalled();});it('keeps a queued target through a cached-data refetch error', async () => {@@ -422,39 +433,42 @@ describe('automation execution target autosave', () => {});});- it('builds a queued pause from the configuration saved by an in-flight edit', async () => {- const first = deferredSave();- mocks.update.mockReturnValueOnce(first.promise);+ it('pauses a running routine but blocks resuming until the run ends', () => {+ vi.setSystemTime(new Date('2026-09-28T12:00:00Z'));+ const claimed = '2026-09-28T11:55:00Z';+ setSchedules([{ ...cron, claimed }]);render(() => <Automation />);- mocks.changeTarget(agentTarget);- await vi.advanceTimersByTimeAsync(300);- setSchedules([{ ...cron, claimed: new Date().toISOString() }]);- fireEvent.click(screen.getByText('Pause'));- await vi.advanceTimersByTimeAsync(300);- expect(mocks.update).toHaveBeenCalledTimes(1);- const saved = {- ...cron,- claimed: new Date().toISOString(),- task: {- ...(cron.task as object),- agent: { bot_id: agentTarget.agentId },- model: 'runtime-model',- },- };- setSchedules([saved]);- first.resolve(saved);- await vi.advanceTimersByTimeAsync(0);- expect(mocks.update).toHaveBeenLastCalledWith({- scheduleId: cron.id,- body: {- name: saved.name,- kind: saved.kind,- trigger: saved.trigger,- task: saved.task,- enabled: false,- },+ expect(screen.getByText('Running')).toBeTruthy();+ fireEvent.click(activeSwitch());+ expect(mocks.setEnabled).toHaveBeenCalledExactlyOnceWith({+ scheduleId: 'routine-id',+ enabled: false,});- expect(selectedTarget()).toEqual(agentTarget);+ setSchedules([{ ...cron, claimed, enabled: false }]);+ expect(activeSwitch().getAttribute('aria-checked')).toBe('false');+ expect(activeSwitch().disabled).toBe(true);+ setSchedules([{ ...cron, enabled: false }]);+ expect(activeSwitch().disabled).toBe(false);+ });++ it('shows a paused routine switched off and still runs it on demand', () => {+ render(() => <Automation />);+ expect(activeSwitch().getAttribute('aria-checked')).toBe('true');+ expect(screen.getByText('Next run 2026-09-28T09:00:00Z')).toBeTruthy();+ setSchedules([{ ...cron, enabled: false }]);+ expect(activeSwitch().getAttribute('aria-checked')).toBe('false');+ expect(screen.queryByText(/Next run/)).toBeNull();+ fireEvent.click(runButton());+ expect(mocks.run).toHaveBeenCalledExactlyOnceWith({+ scheduleId: 'routine-id',+ });+ });++ it('holds the switch while an activation request is pending', () => {+ render(() => <Automation />);+ expect(activeSwitch().disabled).toBe(false);+ setActivationPending(true);+ expect(activeSwitch().disabled).toBe(true);});it.each(['events', 'unmount'])(@@ -585,7 +599,6 @@ describe('automation editor trigger guards', () => {body: {name: 'Summary',kind: 'Agent',- enabled: true,trigger: cron.trigger,task: {model: 'claude-sonnet-4-6',diff --git a/apps/web/src/features/block-automation/component/Automation.tsx b/apps/web/src/features/block-automation/component/Automation.tsxindex e6d77dd212..ae673e3d1c 100644--- a/apps/web/src/features/block-automation/component/Automation.tsx+++ b/apps/web/src/features/block-automation/component/Automation.tsx@@ -23,12 +23,13 @@ import {useRunScheduleNowMutation,useScheduleHistoryQuery,useSchedulesQuery,+ useSetScheduleEnabledMutation,useUpdateScheduleMutation,} from '@queries/agent-schedule/schedules';import { getCronTrigger } from '@queries/agent-schedule/triggers';import { useAgentSessionQuery } from '@queries/agent-session/session';import { useChatQuery } from '@queries/chat';-import { Button, cn } from '@ui';+import { Button, cn, ToggleSwitch } from '@ui';import {type Accessor,createEffect,@@ -41,6 +42,7 @@ import {Show,Switch,} from 'solid-js';+import { match } from 'ts-pattern';import { createRoutineAutosave } from '../primitives/routine-autosave';import { RoutineExecutionPicker } from '../routine-execution-picker';import { type HistoryMetadata, RoutineHistory } from '../views/routine-history';@@ -61,10 +63,6 @@ import {} from './automationUtils';import type { ScheduleDraft } from './types';-type SaveIntent =- | { type: 'edit'; draft: ScheduleDraft }- | { type: 'pause'; draft: ScheduleDraft };-function createChatHistoryMetadata(id: string): Accessor<HistoryMetadata> {const query = useChatQuery(() => id);return () => {@@ -108,6 +106,9 @@ export function Automation() {const current = schedule();return current ? scheduleToEntity(current) : undefined;};+ const status = () => scheduleEntity()?.status;+ const isRunning = () => status()?.kind === 'running';+ const isActive = () => schedule()?.enabled ?? false;const [state, setRawState] = createSignal<ScheduleDraft | undefined>();@@ -135,26 +136,13 @@ export function Automation() {});const updateMutation = useUpdateScheduleMutation();- const autosave = createRoutineAutosave<SaveIntent>(async (intent) => {+ const autosave = createRoutineAutosave<ScheduleDraft>(async (draft) => {const previous = schedule();if (!previous || !getCronTrigger(previous)) {throw new Error('This routine is no longer editable.');}- const body =- intent.type === 'pause'- ? {- name: previous.name,- trigger: previous.trigger,- kind: previous.kind,- task: previous.task,- enabled: false,- }- : draftToUpdateBody(intent.draft, previous);+ const body = draftToUpdateBody(draft, previous);if (!body) throw new Error('Choose a valid execution target.');- if (intent.type === 'pause' && state() === intent.draft) {- // A preceding write may have changed the saved configuration while queued.- setRawState(draftFromSchedule({ ...previous, enabled: false }));- }await updateMutation.mutateAsync({ scheduleId, body });});@@ -166,22 +154,7 @@ export function Automation() {if (next.name !== current.name) {panel.handle.setDisplayName(next.name);}- autosave.queue(formError() ? undefined : { type: 'edit', draft: next });- }-- function toggleEnabled(): void {- const previous = schedule();- if (!previous || !cronTrigger()) return;- if (!isRunning()) {- setState((current) => ({ ...current, enabled: !current.enabled }));- return;- }- // A running action only accepts disabling with its exact saved configuration.- const saved = draftFromSchedule(previous);- if (!saved || !previous.enabled) return;- const paused = { ...saved, enabled: false };- setRawState(paused);- autosave.queue({ type: 'pause', draft: paused });+ autosave.queue(formError() ? undefined : next);}function runNow(): void {@@ -230,6 +203,13 @@ export function Automation() {toast.alert('Failed to start run', { subtext: getErrorMessage(error) }),});+ const setEnabledMutation = useSetScheduleEnabledMutation({+ onError: (error) =>+ toast.alert('Failed to update routine', {+ subtext: getErrorMessage(error),+ }),+ });+const duplicateMutation = useCreateScheduleMutation({onSuccess: (created) => {toast.success('Duplicated');@@ -270,18 +250,6 @@ export function Automation() {});};- // Treat an action as "running" when the server has a fresh claim on it.- // The backend's MAX_ACTION_TIME is 20 minutes — after that a claim is- // considered stale (e.g. executor crashed) and we stop showing the- // running indicator. The websocket sync patches `claimed` live; GETs seed- // it on page load.- const MAX_CLAIMED_MS = 20 * 60 * 1000;- const isRunning = createMemo(() => {- const claimed = schedule()?.claimed;- if (!claimed) return false;- return Date.now() - Date.parse(claimed) < MAX_CLAIMED_MS;- });-onMount(() => {void invalidateSchedules();});@@ -393,36 +361,38 @@ export function Automation() {>Run Now</Button>- <Button- variant="outline"- size="sm"- class="cursor-default"- disabled={isRunning() && !d().enabled}- onClick={toggleEnabled}- >- {d().enabled ? 'Pause' : 'Resume'}- </Button>+ <ToggleSwitch+ label="Active"+ labelClass="text-xs text-ink-muted"+ checked={isActive()}+ // Resuming conflicts with the claim until the run finishes.+ disabled={+ setEnabledMutation.isPending || (isRunning() && !isActive())+ }+ onChange={(active) =>+ setEnabledMutation.mutate({ scheduleId, enabled: active })+ }+ /><div class="ml-auto text-xs font-mono text-right uppercase font-light">- <Show- when={isRunning()}- fallback={+ {match(status())+ .with({ kind: 'running' }, () => (+ <span class="flex items-center justify-end gap-1.5 text-accent">+ <span class="size-1.5 animate-pulse rounded-full bg-accent" />+ Running+ </span>+ ))+ .with({ kind: 'scheduled' }, ({ nextRunAt }) => (<span class="text-ink-extra-muted">- <Show- when={d().enabled && schedule()?.next_run_at}- fallback={<>Paused</>}- >- {(nextRunAt) => (- <>Next run {formatDateAndTime(nextRunAt())}</>- )}- </Show>+ Next run {formatDateAndTime(nextRunAt)}</span>- }- >- <span class="flex items-center justify-end gap-1.5 text-accent">- <span class="size-1.5 animate-pulse rounded-full bg-accent" />- Running- </span>- </Show>+ ))+ .with(+ { kind: 'paused' },+ { kind: 'unscheduled' },+ undefined,+ () => undefined+ )+ .exhaustive()}</div></div>diff --git a/apps/web/src/features/block-automation/component/automationUtils.test.ts b/apps/web/src/features/block-automation/component/automationUtils.test.tsindex c4ee3b7ce0..dd111f2abf 100644--- a/apps/web/src/features/block-automation/component/automationUtils.test.ts+++ b/apps/web/src/features/block-automation/component/automationUtils.test.ts@@ -126,7 +126,7 @@ describe('routine execution payloads', () => {{ agent: { bot_id: agentId }, model: null },{ agent: { bot_id: agentId }, model: 'runtime/custom' },])(- 'preserves exact task and configuration for disable-only updates: %j',+ 'preserves exact task and configuration for unedited drafts: %j',(selection) => {const action = {...cron,@@ -144,16 +144,12 @@ describe('routine execution payloads', () => {},};const before = JSON.stringify(action.task);- const body = draftToUpdateBody(- { ...loadedDraft(action), enabled: false },- action- );+ const body = draftToUpdateBody(loadedDraft(action), action);expect(body).toEqual({name: action.name,trigger: action.trigger,kind: action.kind,task: action.task,- enabled: false,});expect(JSON.stringify(body?.task)).toBe(before);expect(body?.task).toBe(action.task);@@ -255,6 +251,7 @@ describe('cron automation payloads', () => {const body = draftToCreateBody(draft());expect(body).toMatchObject({name: 'Summary',+ enabled: true,trigger: { type: 'cron', schedule: '0 0 9 * * 2,3,4,5,6' },task: { user_prompt: 'Summarize updates' },});@@ -292,6 +289,16 @@ describe('cron automation payloads', () => {});+ it('keeps a paused routine paused when duplicating it', () => {+ expect(scheduleToDuplicateBody({ ...cron, enabled: false })).toEqual({+ name: 'Weekly summary copy',+ enabled: false,+ kind: 'Agent',+ task: cron.task,+ trigger: cron.trigger,+ });+ });+it('duplicates API-written cron expressions losslessly', () => {const trigger = {type: 'cron' as const,diff --git a/apps/web/src/features/block-automation/component/automationUtils.ts b/apps/web/src/features/block-automation/component/automationUtils.tsindex 0b42a1bf65..500d24655c 100644--- a/apps/web/src/features/block-automation/component/automationUtils.ts+++ b/apps/web/src/features/block-automation/component/automationUtils.ts@@ -101,7 +101,6 @@ export function createEmptyDraft(): ScheduleDraft {daysOfWeek: [...DEFAULT_WEEKDAYS],dayOfMonth: '1',target: { kind: 'model', model: DEFAULT_MODEL },- enabled: true,};}@@ -155,7 +154,6 @@ export function draftFromSchedule(daysOfWeek: parsed.daysOfWeek,dayOfMonth: parsed.dayOfMonth,target: targetFromTask(task),- enabled: schedule.enabled,};}@@ -192,7 +190,7 @@ export function draftToCreateBody(draft: ScheduleDraft): CreateScheduledAction {},kind: 'Agent',task: buildAgentTask(draft),- enabled: draft.enabled,+ enabled: true,};}@@ -219,7 +217,6 @@ export function draftToUpdateBody(}// Preserve API-written cron expressions and raw task data when not edited.- // The backend permits disabling a running action only if configuration matches.const parsed = parseCron(trigger.schedule);const scheduleChanged =draft.frequency !== parsed.frequency ||@@ -236,7 +233,6 @@ export function draftToUpdateBody(: trigger,kind: previous.kind,task,- enabled: draft.enabled,};}diff --git a/apps/web/src/features/block-automation/component/types.ts b/apps/web/src/features/block-automation/component/types.tsindex 0b15ff8b0a..2b0d82a924 100644--- a/apps/web/src/features/block-automation/component/types.ts+++ b/apps/web/src/features/block-automation/component/types.ts@@ -13,5 +13,4 @@ export type ScheduleDraft = {/** 1-31 day-of-month when frequency === "month". */dayOfMonth: string;target: RoutineTarget;- enabled: boolean;};diff --git a/apps/web/src/features/block-automation/util/automationComposerStorage.test.ts b/apps/web/src/features/block-automation/util/automationComposerStorage.test.tsindex 62df5f6ee8..0ad154cbba 100644--- a/apps/web/src/features/block-automation/util/automationComposerStorage.test.ts+++ b/apps/web/src/features/block-automation/util/automationComposerStorage.test.ts@@ -16,7 +16,6 @@ const draft: ScheduleDraft = {time: '09:00',daysOfWeek: [],dayOfMonth: '',- enabled: true,target: { kind: 'model', model: 'retired-model' },};@@ -53,10 +52,15 @@ describe('automation composer storage', () => {expect(loadAutomationComposerDraft()).toEqual(saved);});+ it('drops activation saved by older clients', () => {+ store({ draft: { ...draft, enabled: false }, timestamp: Date.now() });+ expect(loadAutomationComposerDraft()).toEqual(draft);+ });+it('migrates an unexpired legacy model without refreshing its expiry', () => {const { target: _target, ...fields } = draft;store({- draft: { ...fields, model: 'removed-from-catalog' },+ draft: { ...fields, model: 'removed-from-catalog', enabled: true },timestamp: Date.now(),});vi.advanceTimersByTime(expiry);diff --git a/apps/web/src/features/block-automation/util/automationComposerStorage.ts b/apps/web/src/features/block-automation/util/automationComposerStorage.tsindex 9fb099ce5b..9e2603bd0b 100644--- a/apps/web/src/features/block-automation/util/automationComposerStorage.ts+++ b/apps/web/src/features/block-automation/util/automationComposerStorage.ts@@ -17,18 +17,21 @@ const draftFields = {time: z.string(),daysOfWeek: z.array(z.string()),dayOfMonth: z.string(),- enabled: z.boolean(),+ // Older clients saved routine activation with the draft.+ enabled: z.boolean().optional(),};-const draftSchema = z.union([- z.strictObject({ ...draftFields, target: routineTargetSchema }),- z.strictObject({ ...draftFields, model: routineModelSchema }).transform(- ({ model, ...fields }): ScheduleDraft => ({- ...fields,- target: { kind: 'model', model },- })- ),-]);+const draftSchema = z+ .union([+ z.strictObject({ ...draftFields, target: routineTargetSchema }),+ z+ .strictObject({ ...draftFields, model: routineModelSchema })+ .transform(({ model, ...fields }) => ({+ ...fields,+ target: { kind: 'model' as const, model },+ })),+ ])+ .transform(({ enabled: _enabled, ...draft }): ScheduleDraft => draft);const storedDraftSchema = z.object({draft: draftSchema,diff --git a/apps/web/src/features/entity/composed/list-entity/automation.test.tsx b/apps/web/src/features/entity/composed/list-entity/automation.test.tsxnew file mode 100644index 0000000000..b35fdd3c56--- /dev/null+++ b/apps/web/src/features/entity/composed/list-entity/automation.test.tsx@@ -0,0 +1,63 @@+import { render, screen } from '@solidjs/testing-library';+import { describe, expect, it, vi } from 'vitest';+import type { AutomationEntity, RoutineStatus } from '../../types/entity';+import { AutomationWideContent } from './automation';++vi.mock('../../entity', () => ({+ Entity: {+ Title: (props: { entity: { name: string } }) => <>{props.entity.name}</>,+ },+}));+vi.mock('../../utils/timestamp', () => ({+ formatDateAndTime: (value: string) => value,+}));++function routine(name: string, status: RoutineStatus): AutomationEntity {+ return {+ id: name,+ type: 'automation',+ name,+ ownerId: 'macro|[email protected]',+ cron: '0 0 9 * * 2',+ status,+ };+}++describe('AutomationWideContent', () => {+ it.each<[RoutineStatus, string]>([+ [{ kind: 'running' }, 'SummaryRunning'],+ [{ kind: 'paused' }, 'SummaryPaused'],+ [+ { kind: 'scheduled', nextRunAt: '2026-09-29T09:00:00Z' },+ 'SummaryNext run 2026-09-29T09:00:00Z',+ ],+ [{ kind: 'unscheduled' }, 'Summary'],+ ])('labels a %j routine as %j', (status, text) => {+ const { container } = render(() => (+ <AutomationWideContent entity={routine('Summary', status)} />+ ));+ expect(container.textContent).toBe(text);+ });++ it('mutes the title of a paused routine only', () => {+ render(() => (+ <>+ <AutomationWideContent+ entity={routine('Paused routine', { kind: 'paused' })}+ />+ <AutomationWideContent+ entity={routine('Active routine', {+ kind: 'scheduled',+ nextRunAt: '2026-09-29T09:00:00Z',+ })}+ />+ </>+ ));+ expect(+ screen.getByText('Paused routine').classList.contains('text-ink-muted')+ ).toBe(true);+ expect(+ screen.getByText('Active routine').classList.contains('text-ink-muted')+ ).toBe(false);+ });+});diff --git a/apps/web/src/features/entity/composed/list-entity/automation.tsx b/apps/web/src/features/entity/composed/list-entity/automation.tsxindex d5549c5520..4a26d8132a 100644--- a/apps/web/src/features/entity/composed/list-entity/automation.tsx+++ b/apps/web/src/features/entity/composed/list-entity/automation.tsx@@ -1,29 +1,28 @@-import { Match, Switch } from 'solid-js';+import { match } from 'ts-pattern';import { Entity } from '../../entity';-import type { AutomationEntity } from '../../types/entity';+import type { AutomationEntity, RoutineStatus } from '../../types/entity';import { formatDateAndTime } from '../../utils/timestamp';-function AutomationSubtitle(props: { entity: AutomationEntity }) {+function AutomationSubtitle(props: { status: RoutineStatus }) {return (<div class="text-xs font-mono text-right uppercase font-light">- <Switch>- <Match when={props.entity.isRunning}>+ {match(props.status)+ .with({ kind: 'running' }, () => (<span class="flex items-center justify-end gap-1.5 text-accent"><span class="size-1.5 animate-pulse rounded-full bg-accent" />Running</span>- </Match>- <Match when={props.entity.enabled && props.entity.nextRunAt}>- {(nextRunAt) => (- <span class="text-ink-extra-muted">- Next run {formatDateAndTime(nextRunAt())}- </span>- )}- </Match>- <Match when={!props.entity.enabled}>+ ))+ .with({ kind: 'scheduled' }, ({ nextRunAt }) => (+ <span class="text-ink-extra-muted">+ Next run {formatDateAndTime(nextRunAt)}+ </span>+ ))+ .with({ kind: 'paused' }, () => (<span class="text-ink-extra-muted">Paused</span>- </Match>- </Switch>+ ))+ .with({ kind: 'unscheduled' }, () => undefined)+ .exhaustive()}</div>);}@@ -31,11 +30,14 @@ function AutomationSubtitle(props: { entity: AutomationEntity }) {export function AutomationWideContent(props: { entity: AutomationEntity }) {return (<>- <span class="w-(--title-width) shrink-0 truncate">+ <span+ class="w-(--title-width) shrink-0 truncate"+ classList={{ 'text-ink-muted': props.entity.status.kind === 'paused' }}+ ><Entity.Title entity={props.entity} /></span><span class="">- <AutomationSubtitle entity={props.entity} />+ <AutomationSubtitle status={props.entity.status} /></span></>);diff --git a/apps/web/src/features/entity/tests/buildEntityData.test.ts b/apps/web/src/features/entity/tests/buildEntityData.test.tsindex fb39ef79ea..1cb52c6347 100644--- a/apps/web/src/features/entity/tests/buildEntityData.test.ts+++ b/apps/web/src/features/entity/tests/buildEntityData.test.ts@@ -180,7 +180,7 @@ describe('buildEntityData', () => {...base,type: 'automation',cron: '* * * * *',- enabled: true,+ status: { kind: 'unscheduled' },});});});diff --git a/apps/web/src/features/entity/types/entity.ts b/apps/web/src/features/entity/types/entity.tsindex fec7ab0453..6a7a92f4d9 100644--- a/apps/web/src/features/entity/types/entity.ts+++ b/apps/web/src/features/entity/types/entity.ts@@ -321,20 +321,36 @@ export type CallEntity = EntityBase & {properties?: SoupProperty[];};+/**+ * What a routine is doing now. A run in progress outranks activation, and a+ * paused routine keeps its stale `next_run_at`, so pause outranks the schedule.+ */+export type RoutineStatus =+ | { kind: 'running' }+ | { kind: 'paused' }+ | { kind: 'scheduled'; nextRunAt: string }+ | { kind: 'unscheduled' };++export function routineStatus(facts: {+ enabled: boolean;+ isRunning: boolean;+ nextRunAt?: string | null;+}): RoutineStatus {+ if (facts.isRunning) return { kind: 'running' };+ if (!facts.enabled) return { kind: 'paused' };+ if (facts.nextRunAt) return { kind: 'scheduled', nextRunAt: facts.nextRunAt };+ return { kind: 'unscheduled' };+}+export type AutomationEntity = EntityBase & {type: 'automation';/** Cron expression controlling when the automation runs. */cron: string;- /** Whether the automation is currently enabled. */- enabled: boolean;- /** ISO timestamp of the next scheduled run, or null when paused / unscheduled. */- nextRunAt?: string | null;+ /** Running is derived from the server claim and the backend's stale-claim+ * window; claims update live via the connection-gateway websocket. */+ status: RoutineStatus;/** ISO timestamp of the last completed run. */lastRunAt?: string | null;- /** True when a run is actively claimed on the server. Derived from the- * scheduled action's `claimed` timestamp + the backend's stale-claim- * window; updated live via the connection-gateway websocket. */- isRunning?: boolean;};export type CrmCompanyDomain = {diff --git a/apps/web/src/features/entity/utils/buildEntityData.ts b/apps/web/src/features/entity/utils/buildEntityData.tsindex c4a6e53560..16409d7161 100644--- a/apps/web/src/features/entity/utils/buildEntityData.ts+++ b/apps/web/src/features/entity/utils/buildEntityData.ts@@ -1,17 +1,18 @@import type { BlockAlias, BlockName } from '@core/block';import { match } from 'ts-pattern';-import type {- AutomationEntity,- CallEntity,- ChannelEntity,- ChatEntity,- DocumentEntity,- EmailEntity,- EntityData,- ProjectEntity,- SkillEntity,- SnippetEntity,- TaskEntity,+import {+ type AutomationEntity,+ type CallEntity,+ type ChannelEntity,+ type ChatEntity,+ type DocumentEntity,+ type EmailEntity,+ type EntityData,+ type ProjectEntity,+ routineStatus,+ type SkillEntity,+ type SnippetEntity,+ type TaskEntity,} from '../types/entity';export type BuildEntityDataArgs = {@@ -161,7 +162,10 @@ export function buildEntityData(...base,type: 'automation',cron: args.cron,- enabled: args.enabled ?? false,+ status: routineStatus({+ enabled: args.enabled ?? false,+ isRunning: false,+ }),};}).with('call', (): CallEntity | undefined => {diff --git a/apps/web/src/lib/queries/agent-schedule/entities.test.ts b/apps/web/src/lib/queries/agent-schedule/entities.test.tsindex c618fc6ef0..850e4e68a5 100644--- a/apps/web/src/lib/queries/agent-schedule/entities.test.ts+++ b/apps/web/src/lib/queries/agent-schedule/entities.test.ts@@ -1,6 +1,7 @@+import type { RoutineStatus } from '@entity/types/entity';import type { ScheduledAction } from '@service-scheduled-action/generated/schemas';import { createRoot } from 'solid-js';-import { describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { scheduleToEntity, useAutomationEntities } from './entities';import { getCronTrigger } from './triggers';@@ -34,20 +35,62 @@ const events: ScheduledAction = {trigger: { type: 'events', filters: [{ events: ['document.updated'] }] },};+describe('routine status', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-09-28T12:00:00Z'));+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ it.each<{+ name: string;+ fields: Partial<ScheduledAction>;+ status: RoutineStatus;+ }>([+ {+ name: 'a fresh claim as running',+ fields: { claimed: '2026-09-28T11:55:00Z' },+ status: { kind: 'running' },+ },+ {+ name: 'a run that outlives its pause as running',+ fields: { claimed: '2026-09-28T11:55:00Z', enabled: false },+ status: { kind: 'running' },+ },+ {+ name: 'a stale claim as scheduled',+ fields: { claimed: '2026-09-28T11:35:00Z' },+ status: { kind: 'scheduled', nextRunAt: '2026-09-28T09:00:00Z' },+ },+ {+ name: 'a paused routine with a leftover next run as paused',+ fields: { enabled: false },+ status: { kind: 'paused' },+ },+ {+ name: 'an active routine without a next run as unscheduled',+ fields: { next_run_at: null },+ status: { kind: 'unscheduled' },+ },+ ])('reports $name', ({ fields, status }) => {+ expect(scheduleToEntity({ ...cron, ...fields })?.status).toEqual(status);+ });+});+describe('cron-only automation entities', () => {- it('converts canonical cron actions and preserves run state', () => {- expect(- scheduleToEntity({ ...cron, claimed: new Date().toISOString() })- ).toMatchObject({+ it('converts canonical cron actions', () => {+ expect(scheduleToEntity(cron)).toEqual({id: 'cron-id',type: 'automation',+ name: 'Summary',+ ownerId: 'macro|[email protected]',+ createdAt: '2026-09-22T12:00:00Z',+ updatedAt: '2026-09-22T12:00:00Z',cron: '0 0 9 * * 2',- nextRunAt: cron.next_run_at,- isRunning: true,+ status: { kind: 'scheduled', nextRunAt: '2026-09-28T09:00:00Z' },});- expect(- scheduleToEntity({ ...cron, claimed: '2020-01-01T00:00:00Z' })?.isRunning- ).toBe(false);});it('omits events and actions without an id', () => {diff --git a/apps/web/src/lib/queries/agent-schedule/entities.ts b/apps/web/src/lib/queries/agent-schedule/entities.tsindex 5bc4a54f74..562f1e373a 100644--- a/apps/web/src/lib/queries/agent-schedule/entities.ts+++ b/apps/web/src/lib/queries/agent-schedule/entities.ts@@ -1,4 +1,4 @@-import type { AutomationEntity } from '@entity';+import { type AutomationEntity, routineStatus } from '@entity/types/entity';import type { ScheduledAction } from '@service-scheduled-action/generated/schemas';import { createMemo } from 'solid-js';import { useSchedulesQuery } from './schedules';@@ -28,9 +28,11 @@ export function scheduleToEntity(createdAt: schedule.created_at,updatedAt: schedule.updated_at,cron: trigger.schedule,- enabled: schedule.enabled,- nextRunAt: schedule.next_run_at,- isRunning: isClaimActive(schedule.claimed),+ status: routineStatus({+ enabled: schedule.enabled,+ isRunning: isClaimActive(schedule.claimed),+ nextRunAt: schedule.next_run_at,+ }),};}diff --git a/apps/web/src/lib/queries/agent-schedule/schedules.test.tsx b/apps/web/src/lib/queries/agent-schedule/schedules.test.tsxnew file mode 100644index 0000000000..a449ddda07--- /dev/null+++ b/apps/web/src/lib/queries/agent-schedule/schedules.test.tsx@@ -0,0 +1,119 @@+import { queryClient } from '@queries/client';+import type { ScheduledAction } from '@service-scheduled-action/generated/schemas';+import { QueryClientProvider } from '@tanstack/solid-query';+import { err, ok } from 'neverthrow';+import { render } from 'solid-js/web';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { scheduledActionKeys } from './keys';+import { useSetScheduleEnabledMutation } from './schedules';++const setEnabled = vi.hoisted(() => vi.fn());+vi.mock('@service-scheduled-action/client', () => ({+ scheduledActionClient: { setEnabled },+}));+vi.mock('@queries/client', async () => {+ const { QueryClient } = await import('@tanstack/solid-query');+ return { queryClient: new QueryClient() };+});++const routine: ScheduledAction = {+ id: 'routine',+ owner: 'macro|[email protected]',+ name: 'Routine',+ kind: 'Agent',+ task: {},+ trigger: { type: 'cron', schedule: '0 0 9 * * *', timezone: 'UTC' },+ configuration_revision: 1,+ enabled: true,+ created_at: '2026-09-28T00:00:00Z',+ updated_at: '2026-09-28T00:00:00Z',+ next_run_at: '2026-09-29T09:00:00Z',+};+const other: ScheduledAction = { ...routine, id: 'other', name: 'Other' };++let dispose: (() => void) | undefined;++function mountMutation() {+ let mutation!: ReturnType<typeof useSetScheduleEnabledMutation>;+ function Probe() {+ mutation = useSetScheduleEnabledMutation();+ return null;+ }+ dispose = render(+ () => (+ <QueryClientProvider client={queryClient}>+ <Probe />+ </QueryClientProvider>+ ),+ document.createElement('div')+ );+ return mutation;+}++function respondLater(): (result: unknown) => void {+ let respond!: (result: unknown) => void;+ setEnabled.mockReturnValueOnce(+ new Promise((resolve) => {+ respond = resolve;+ })+ );+ return respond;+}++function schedules(): ScheduledAction[] | undefined {+ return queryClient.getQueryData(scheduledActionKeys.list.queryKey);+}++beforeEach(() => {+ setEnabled.mockReset();+ queryClient.setQueryData(scheduledActionKeys.list.queryKey, [routine, other]);+});++afterEach(() => {+ dispose?.();+ dispose = undefined;+ queryClient.clear();+});++describe('routine activation', () => {+ it('pauses only the target routine while saving, then keeps the saved row', async () => {+ const respond = respondLater();+ const pausing = mountMutation().mutateAsync({+ scheduleId: 'routine',+ enabled: false,+ });+ await vi.waitFor(() =>+ expect(schedules()).toEqual([{ ...routine, enabled: false }, other])+ );+ const saved = {+ ...routine,+ enabled: false,+ configuration_revision: 2,+ updated_at: '2026-09-28T12:00:00Z',+ };+ respond(ok(saved));+ await pausing;+ expect(setEnabled).toHaveBeenCalledExactlyOnceWith({+ scheduleId: 'routine',+ enabled: false,+ });+ expect(schedules()).toEqual([saved, other]);+ });++ it('restores only the activation it changed when saving fails', async () => {+ const respond = respondLater();+ const pausing = mountMutation().mutateAsync({+ scheduleId: 'routine',+ enabled: false,+ });+ await vi.waitFor(() => expect(schedules()?.[0].enabled).toBe(false));+ const claimed = '2026-09-28T12:00:00Z';+ queryClient.setQueryData(scheduledActionKeys.list.queryKey, [+ { ...routine, enabled: false, claimed },+ other,+ ]);+ respond(err([{ code: 'CONFLICT', message: 'Routine changed' }]));+ await expect(pausing).rejects.toThrow('Routine changed');+ expect(schedules()).toEqual([{ ...routine, claimed }, other]);+ });+});diff --git a/apps/web/src/lib/queries/agent-schedule/schedules.ts b/apps/web/src/lib/queries/agent-schedule/schedules.tsindex 72f367fb63..130d53ba6b 100644--- a/apps/web/src/lib/queries/agent-schedule/schedules.ts+++ b/apps/web/src/lib/queries/agent-schedule/schedules.ts@@ -42,6 +42,16 @@ function removeSchedule(scheduleId: string) {);}+function patchScheduleEnabled(scheduleId: string, enabled: boolean) {+ queryClient.setQueryData(+ scheduledActionKeys.list.queryKey,+ (current: ScheduledAction[] | undefined) =>+ current?.map((item) =>+ item.id === scheduleId ? { ...item, enabled } : item+ )+ );+}+export function useSchedulesQuery(enabled: Accessor<boolean>) {return useQuery(() => ({queryKey: scheduledActionKeys.list.queryKey,@@ -136,6 +146,54 @@ export function useUpdateScheduleMutation(}));}+type ScheduleActivation = { scheduleId: string; enabled: boolean };+type ScheduleActivationContext = { previousEnabled: boolean | undefined };++/**+ * Patches and rolls back only the row's `enabled` flag, so a failed toggle+ * cannot undo an autosave or claim update that reached the same row meanwhile.+ */+export function useSetScheduleEnabledMutation(+ callbacks?: MutationCallbacks<+ ScheduledAction,+ Error,+ ScheduleActivation,+ ScheduleActivationContext+ >+) {+ return useMutation(() => ({+ mutationFn: async (args: ScheduleActivation) =>+ throwOnErr(async () => await scheduledActionClient.setEnabled(args)),+ ...withCallbacks<+ ScheduledAction,+ Error,+ ScheduleActivation,+ ScheduleActivationContext+ >(+ {+ onMutate: async ({ scheduleId, enabled }) => {+ await queryClient.cancelQueries({+ queryKey: scheduledActionKeys.list.queryKey,+ });+ const previousEnabled = queryClient+ .getQueryData<ScheduledAction[]>(scheduledActionKeys.list.queryKey)+ ?.find((item) => item.id === scheduleId)?.enabled;+ patchScheduleEnabled(scheduleId, enabled);+ return { previousEnabled };+ },+ onError: (_error, { scheduleId }, context) => {+ if (context?.previousEnabled !== undefined) {+ patchScheduleEnabled(scheduleId, context.previousEnabled);+ }+ },+ onSuccess: (schedule) => upsertSchedule(schedule),+ onSettled: () => invalidateSchedules(),+ },+ callbacks+ ),+ }));+}+function _useDeleteScheduleMutation(callbacks?: MutationCallbacks<{ success: boolean },diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/client.ts b/apps/web/src/lib/service-clients/service-scheduled-action/client.tsindex d7bc610570..347959fe15 100644--- a/apps/web/src/lib/service-clients/service-scheduled-action/client.ts+++ b/apps/web/src/lib/service-clients/service-scheduled-action/client.ts@@ -11,6 +11,7 @@ import type {CreateScheduledAction,InProgressExecution,ScheduledAction,+ SetScheduledActionEnabled,UpdateScheduledAction,} from './generated/schemas';@@ -62,6 +63,17 @@ export const scheduledActionClient = {}),+ setEnabled: async (args: { scheduleId: string; enabled: boolean }) =>+ scheduledActionFetch<ScheduledAction>(+ `/scheduled-actions/${args.scheduleId}/enabled`,+ {+ method: 'PUT',+ body: JSON.stringify({+ enabled: args.enabled,+ } satisfies SetScheduledActionEnabled),+ }+ ),+deleteSchedule: async (args: { scheduleId: string }) => {const result = await scheduledActionFetch<{}>(`/scheduled-actions/${args.scheduleId}`,diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/client.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/client.tsindex a811f2f0d7..f2e598e215 100644--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/client.ts+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/client.ts@@ -12,6 +12,7 @@ import type {InProgressExecution,ListScheduledActionsParams,ScheduledActionResponse,+ SetScheduledActionEnabled,UpdateScheduledAction,} from './schemas';@@ -327,6 +328,82 @@ export const deleteScheduledAction = async (} as deleteScheduledActionResponse;};+export type setScheduledActionEnabledResponse200 = {+ data: ScheduledActionResponse;+ status: 200;+};++export type setScheduledActionEnabledResponse400 = {+ data: string;+ status: 400;+};++export type setScheduledActionEnabledResponse401 = {+ data: string;+ status: 401;+};++export type setScheduledActionEnabledResponse404 = {+ data: string;+ status: 404;+};++export type setScheduledActionEnabledResponse409 = {+ data: string;+ status: 409;+};++export type setScheduledActionEnabledResponse500 = {+ data: string;+ status: 500;+};++export type setScheduledActionEnabledResponseSuccess =+ setScheduledActionEnabledResponse200 & {+ headers: Headers;+ };+export type setScheduledActionEnabledResponseError = (+ | setScheduledActionEnabledResponse400+ | setScheduledActionEnabledResponse401+ | setScheduledActionEnabledResponse404+ | setScheduledActionEnabledResponse409+ | setScheduledActionEnabledResponse500+) & {+ headers: Headers;+};++export type setScheduledActionEnabledResponse =+ | setScheduledActionEnabledResponseSuccess+ | setScheduledActionEnabledResponseError;++export const getSetScheduledActionEnabledUrl = (id: string) => {+ return `/scheduled-actions/${id}/enabled`;+};++export const setScheduledActionEnabled = async (+ id: string,+ setScheduledActionEnabled: SetScheduledActionEnabled,+ options?: RequestInit+): Promise<setScheduledActionEnabledResponse> => {+ const res = await fetch(getSetScheduledActionEnabledUrl(id), {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(setScheduledActionEnabled),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: setScheduledActionEnabledResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as setScheduledActionEnabledResponse;+};+export type executeScheduledActionNowResponse200 = {data: InProgressExecution;status: 200;diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionConfigurationUpdate.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionConfigurationUpdate.tsnew file mode 100644index 0000000000..3b04e6d914--- /dev/null+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionConfigurationUpdate.ts@@ -0,0 +1,27 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * scheduled_action+ * API for managing scheduled actions+ * OpenAPI spec version: 0.1.0+ */+import type { ActionConfigurationUpdateEnabled } from './actionConfigurationUpdateEnabled';+import type { ActionConfigurationUpdateTask } from './actionConfigurationUpdateTask';+import type { ActionKind } from './actionKind';+import type { ActionTrigger } from './actionTrigger';++/**+ * Canonical configuration replacement. Activation has its own endpoint, so+omitting `enabled` keeps the stored value.+ */+export interface ActionConfigurationUpdate {+ /**+ * Still sent by clients deployed before the activation endpoint.+ * @deprecated+ */+ enabled?: ActionConfigurationUpdateEnabled;+ kind: ActionKind;+ name: string;+ task: ActionConfigurationUpdateTask;+ trigger: ActionTrigger;+}diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionConfigurationUpdateEnabled.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionConfigurationUpdateEnabled.tsnew file mode 100644index 0000000000..615f36c085--- /dev/null+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionConfigurationUpdateEnabled.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * scheduled_action+ * API for managing scheduled actions+ * OpenAPI spec version: 0.1.0+ */++/**+ * Still sent by clients deployed before the activation endpoint.+ * @deprecated+ */+export type ActionConfigurationUpdateEnabled = boolean | null;diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionConfigurationUpdateTask.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionConfigurationUpdateTask.tsnew file mode 100644index 0000000000..15d82b0e63--- /dev/null+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionConfigurationUpdateTask.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * scheduled_action+ * API for managing scheduled actions+ * OpenAPI spec version: 0.1.0+ */++export type ActionConfigurationUpdateTask = { [key: string]: unknown };diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.tsindex 021fcbd6ca..1d23ae7230 100644--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.ts@@ -8,6 +8,9 @@export * from './actionConfiguration';export * from './actionConfigurationTask';+export * from './actionConfigurationUpdate';+export * from './actionConfigurationUpdateEnabled';+export * from './actionConfigurationUpdateTask';export * from './actionExecutionRecord';export * from './actionExecutionRecordId';export * from './actionExecutionRecordResourceId';@@ -60,4 +63,5 @@ export * from './scheduledActionUpdateOneOfFiveResource';export * from './scheduledActionUpdateOneOfFiveType';export * from './scheduledActionUpdateOneOfResource';export * from './scheduledActionUpdateOneOfType';+export * from './setScheduledActionEnabled';export * from './updateScheduledAction';diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/setScheduledActionEnabled.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/setScheduledActionEnabled.tsnew file mode 100644index 0000000000..d553f9afdd--- /dev/null+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/setScheduledActionEnabled.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * scheduled_action+ * API for managing scheduled actions+ * OpenAPI spec version: 0.1.0+ */++export interface SetScheduledActionEnabled {+ enabled: boolean;+}diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/updateScheduledAction.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/updateScheduledAction.tsindex 578a3417b2..ff8803fbc9 100644--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/updateScheduledAction.ts+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/updateScheduledAction.ts@@ -5,12 +5,12 @@* API for managing scheduled actions* OpenAPI spec version: 0.1.0*/-import type { ActionConfiguration } from './actionConfiguration';+import type { ActionConfigurationUpdate } from './actionConfigurationUpdate';import type { LegacyActionConfiguration } from './legacyActionConfiguration';/*** Full replacement of client configuration, not of server-owned action state.*/export type UpdateScheduledAction =- | ActionConfiguration+ | ActionConfigurationUpdate| LegacyActionConfiguration;diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json b/apps/web/src/lib/service-clients/service-scheduled-action/openapi.jsonindex 4683de643d..b6a14e699e 100644--- a/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json+++ b/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json@@ -286,6 +286,95 @@}}},+ "/scheduled-actions/{id}/enabled": {+ "put": {+ "tags": ["scheduled actions"],+ "operationId": "set_scheduled_action_enabled",+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "description": "ID of the scheduled action",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SetScheduledActionEnabled"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ScheduledActionResponse"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "409": {+ "description": "Configuration changed or execution is active",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ },"/scheduled-actions/{id}/execute": {"post": {"tags": ["scheduled actions"],@@ -453,6 +542,31 @@},"additionalProperties": false},+ "ActionConfigurationUpdate": {+ "type": "object",+ "description": "Canonical configuration replacement. Activation has its own endpoint, so\nomitting `enabled` keeps the stored value.",+ "required": ["name", "trigger", "kind", "task"],+ "properties": {+ "enabled": {+ "type": ["boolean", "null"],+ "description": "Still sent by clients deployed before the activation endpoint.",+ "deprecated": true+ },+ "kind": {+ "$ref": "#/components/schemas/ActionKind"+ },+ "name": {+ "type": "string"+ },+ "task": {+ "type": "object"+ },+ "trigger": {+ "$ref": "#/components/schemas/ActionTrigger"+ }+ },+ "additionalProperties": false+ },"ActionExecutionRecord": {"type": "object","required": [@@ -891,10 +1005,20 @@],"description": "Live status update for a scheduled-action run, broadcast via the connection\ngateway to the owner. Clients use the typed resource to navigate to the run\ntranscript and the variant tag to toggle the running indicator. `chat_id`\nremains populated only for chat runs, for older clients.\n\nSerialized with a `type` tag (`started`/`stopped`) and delivered over the\nsingle `scheduled_action_update` message type on the gateway."},+ "SetScheduledActionEnabled": {+ "type": "object",+ "required": ["enabled"],+ "properties": {+ "enabled": {+ "type": "boolean"+ }+ },+ "additionalProperties": false+ },"UpdateScheduledAction": {"oneOf": [{- "$ref": "#/components/schemas/ActionConfiguration"+ "$ref": "#/components/schemas/ActionConfigurationUpdate"},{"$ref": "#/components/schemas/LegacyActionConfiguration"diff --git a/docs/AGENT_GUIDE/navigation.md b/docs/AGENT_GUIDE/navigation.mdindex 61089a51c8..38b1ee84dc 100644--- a/docs/AGENT_GUIDE/navigation.md+++ b/docs/AGENT_GUIDE/navigation.md@@ -436,14 +436,19 @@ the static highlight.## Routines (automations)-Create → Automation creates a cron-scheduled routine. Cron routines support+Create → Automation creates an active cron-scheduled routine. Cron routines supportediting instructions, schedule, and the **Execution target** model/agent picker,-Rename, Pause/Resume, Duplicate, Run Now, and History links to run chats.-Edits autosave in order. **Run Now** stays disabled until the latest valid edit-saves successfully; it also works while paused. A failed save keeps the selection-visible with **Changes not saved** and **Retry save**. While running, configuration-cannot be changed, but **Pause** still disables the saved routine. Duplicate-retains the saved execution configuration, not unsaved edits.+Rename, the **Active** switch, Duplicate, Run Now, and History links to run chats.+The **Active** switch next to **Run Now** pauses or resumes the routine at once,+separately from autosave and even while the draft is invalid. A paused routine+shows no next run in its editor; routine lists mute its title and label it+**Paused**. Edits autosave in order and never change whether the routine is+active. **Run Now** stays disabled until the latest valid edit saves successfully;+it also works while paused. A failed save keeps the selection visible with+**Changes not saved** and **Retry save**. While running, configuration cannot be+changed, and the switch can pause the routine but cannot resume it until the run+ends. Duplicate retains the saved execution configuration and active state, not+unsaved edits.If a background refresh fails, cached cron routines stay listed and their editorand queued autosave remain available. An initial load failure without cached datashows **Unable to load automation** instead. Cached event routines remaindiff --git a/packages/sdk/generated/scheduled-action/index.ts b/packages/sdk/generated/scheduled-action/index.tsindex 7fcbb5b5f9..d4151dc70c 100644--- a/packages/sdk/generated/scheduled-action/index.ts+++ b/packages/sdk/generated/scheduled-action/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { ActionConfiguration, ActionExecutionRecord, ActionKind, ActionTrigger, AgentTask, AgentTaskAgent, ClientOptions, CreateScheduledAction, CreateScheduledActionData, CreateScheduledActionError, CreateScheduledActionErrors, CreateScheduledActionResponse, CreateScheduledActionResponses, DeleteScheduledActionData, DeleteScheduledActionError, DeleteScheduledActionErrors, DeleteScheduledActionResponse, DeleteScheduledActionResponses, EmptyResponse, EventFilter, EventFilters, EventName, ExecuteScheduledActionNowData, ExecuteScheduledActionNowError, ExecuteScheduledActionNowErrors, ExecuteScheduledActionNowResponse, ExecuteScheduledActionNowResponses, ExecutionResource, ExecutionResourceType, ExecutionResult, InProgressExecution, LegacyActionConfiguration, ListScheduledActionHistoryData, ListScheduledActionHistoryError, ListScheduledActionHistoryErrors, ListScheduledActionHistoryResponse, ListScheduledActionHistoryResponses, ListScheduledActionsData, ListScheduledActionsError, ListScheduledActionsErrors, ListScheduledActionsResponse, ListScheduledActionsResponses, RoutineModelId, Schedule, ScheduledAction, ScheduledActionHealthData, ScheduledActionHealthResponse, ScheduledActionHealthResponses, ScheduledActionResponse, ScheduledActionUpdate, UpdateScheduledAction, UpdateScheduledActionData, UpdateScheduledActionError, UpdateScheduledActionErrors, UpdateScheduledActionResponse, UpdateScheduledActionResponses } from './types.gen';+export type { ActionConfiguration, ActionConfigurationUpdate, ActionExecutionRecord, ActionKind, ActionTrigger, AgentTask, AgentTaskAgent, ClientOptions, CreateScheduledAction, CreateScheduledActionData, CreateScheduledActionError, CreateScheduledActionErrors, CreateScheduledActionResponse, CreateScheduledActionResponses, DeleteScheduledActionData, DeleteScheduledActionError, DeleteScheduledActionErrors, DeleteScheduledActionResponse, DeleteScheduledActionResponses, EmptyResponse, EventFilter, EventFilters, EventName, ExecuteScheduledActionNowData, ExecuteScheduledActionNowError, ExecuteScheduledActionNowErrors, ExecuteScheduledActionNowResponse, ExecuteScheduledActionNowResponses, ExecutionResource, ExecutionResourceType, ExecutionResult, InProgressExecution, LegacyActionConfiguration, ListScheduledActionHistoryData, ListScheduledActionHistoryError, ListScheduledActionHistoryErrors, ListScheduledActionHistoryResponse, ListScheduledActionHistoryResponses, ListScheduledActionsData, ListScheduledActionsError, ListScheduledActionsErrors, ListScheduledActionsResponse, ListScheduledActionsResponses, RoutineModelId, Schedule, ScheduledAction, ScheduledActionHealthData, ScheduledActionHealthResponse, ScheduledActionHealthResponses, ScheduledActionResponse, ScheduledActionUpdate, SetScheduledActionEnabled, SetScheduledActionEnabledData, SetScheduledActionEnabledError, SetScheduledActionEnabledErrors, SetScheduledActionEnabledResponse, SetScheduledActionEnabledResponses, UpdateScheduledAction, UpdateScheduledActionData, UpdateScheduledActionError, UpdateScheduledActionErrors, UpdateScheduledActionResponse, UpdateScheduledActionResponses } from './types.gen';diff --git a/packages/sdk/generated/scheduled-action/sdk.gen.ts b/packages/sdk/generated/scheduled-action/sdk.gen.tsindex 515e91df09..b03eebb939 100644--- a/packages/sdk/generated/scheduled-action/sdk.gen.ts+++ b/packages/sdk/generated/scheduled-action/sdk.gen.ts@@ -2,7 +2,7 @@import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';import { client } from './client.gen';-import type { CreateScheduledActionData, CreateScheduledActionErrors, CreateScheduledActionResponses, DeleteScheduledActionData, DeleteScheduledActionErrors, DeleteScheduledActionResponses, ExecuteScheduledActionNowData, ExecuteScheduledActionNowErrors, ExecuteScheduledActionNowResponses, ListScheduledActionHistoryData, ListScheduledActionHistoryErrors, ListScheduledActionHistoryResponses, ListScheduledActionsData, ListScheduledActionsErrors, ListScheduledActionsResponses, ScheduledActionHealthData, ScheduledActionHealthResponses, UpdateScheduledActionData, UpdateScheduledActionErrors, UpdateScheduledActionResponses } from './types.gen';+import type { CreateScheduledActionData, CreateScheduledActionErrors, CreateScheduledActionResponses, DeleteScheduledActionData, DeleteScheduledActionErrors, DeleteScheduledActionResponses, ExecuteScheduledActionNowData, ExecuteScheduledActionNowErrors, ExecuteScheduledActionNowResponses, ListScheduledActionHistoryData, ListScheduledActionHistoryErrors, ListScheduledActionHistoryResponses, ListScheduledActionsData, ListScheduledActionsErrors, ListScheduledActionsResponses, ScheduledActionHealthData, ScheduledActionHealthResponses, SetScheduledActionEnabledData, SetScheduledActionEnabledErrors, SetScheduledActionEnabledResponses, UpdateScheduledActionData, UpdateScheduledActionErrors, UpdateScheduledActionResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -91,6 +91,17 @@ export class Sdk extends HeyApiClient {});}+ public setScheduledActionEnabled<ThrowOnError extends boolean = false>(options: Options<SetScheduledActionEnabledData, ThrowOnError>): RequestResult<SetScheduledActionEnabledResponses, SetScheduledActionEnabledErrors, ThrowOnError> {+ return (options.client ?? this.client).put<SetScheduledActionEnabledResponses, SetScheduledActionEnabledErrors, ThrowOnError>({+ url: '/scheduled-actions/{id}/enabled',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }+public executeScheduledActionNow<ThrowOnError extends boolean = false>(options: Options<ExecuteScheduledActionNowData, ThrowOnError>): RequestResult<ExecuteScheduledActionNowResponses, ExecuteScheduledActionNowErrors, ThrowOnError> {return (options.client ?? this.client).post<ExecuteScheduledActionNowResponses, ExecuteScheduledActionNowErrors, ThrowOnError>({ url: '/scheduled-actions/{id}/execute', ...options });}diff --git a/packages/sdk/generated/scheduled-action/types.gen.ts b/packages/sdk/generated/scheduled-action/types.gen.tsindex 9e3cf93e9c..abc9cfc1e2 100644--- a/packages/sdk/generated/scheduled-action/types.gen.ts+++ b/packages/sdk/generated/scheduled-action/types.gen.ts@@ -17,6 +17,25 @@ export type ActionConfiguration = {trigger: ActionTrigger;};+/**+ * Canonical configuration replacement. Activation has its own endpoint, so+ * omitting `enabled` keeps the stored value.+ */+export type ActionConfigurationUpdate = {+ /**+ * Still sent by clients deployed before the activation endpoint.+ *+ * @deprecated+ */+ enabled?: boolean | null;+ kind: ActionKind;+ name: string;+ task: {+ [key: string]: unknown;+ };+ trigger: ActionTrigger;+};+export type ActionExecutionRecord = {action_id: string;created_at: string;@@ -223,10 +242,14 @@ export type ScheduledActionUpdate = {type: 'stopped';};+export type SetScheduledActionEnabled = {+ enabled: boolean;+};+/*** Full replacement of client configuration, not of server-owned action state.*/-export type UpdateScheduledAction = ActionConfiguration | LegacyActionConfiguration;+export type UpdateScheduledAction = ActionConfigurationUpdate | LegacyActionConfiguration;export type ScheduledActionHealthData = {body?: never;@@ -348,6 +371,37 @@ export type UpdateScheduledActionResponses = {export type UpdateScheduledActionResponse = UpdateScheduledActionResponses[keyof UpdateScheduledActionResponses];+export type SetScheduledActionEnabledData = {+ body: SetScheduledActionEnabled;+ path: {+ /**+ * ID of the scheduled action+ */+ id: string;+ };+ query?: never;+ url: '/scheduled-actions/{id}/enabled';+};++export type SetScheduledActionEnabledErrors = {+ 400: string;+ 401: string;+ 404: string;+ /**+ * Configuration changed or execution is active+ */+ 409: string;+ 500: string;+};++export type SetScheduledActionEnabledError = SetScheduledActionEnabledErrors[keyof SetScheduledActionEnabledErrors];++export type SetScheduledActionEnabledResponses = {+ 200: ScheduledActionResponse;+};++export type SetScheduledActionEnabledResponse = SetScheduledActionEnabledResponses[keyof SetScheduledActionEnabledResponses];+export type ExecuteScheduledActionNowData = {body?: never;path: {diff --git a/packages/sdk/specs/scheduled-action.json b/packages/sdk/specs/scheduled-action.jsonindex 4683de643d..b6a14e699e 100644--- a/packages/sdk/specs/scheduled-action.json+++ b/packages/sdk/specs/scheduled-action.json@@ -286,6 +286,95 @@}}},+ "/scheduled-actions/{id}/enabled": {+ "put": {+ "tags": ["scheduled actions"],+ "operationId": "set_scheduled_action_enabled",+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "description": "ID of the scheduled action",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SetScheduledActionEnabled"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ScheduledActionResponse"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "409": {+ "description": "Configuration changed or execution is active",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ },"/scheduled-actions/{id}/execute": {"post": {"tags": ["scheduled actions"],@@ -453,6 +542,31 @@},"additionalProperties": false},+ "ActionConfigurationUpdate": {+ "type": "object",+ "description": "Canonical configuration replacement. Activation has its own endpoint, so\nomitting `enabled` keeps the stored value.",+ "required": ["name", "trigger", "kind", "task"],+ "properties": {+ "enabled": {+ "type": ["boolean", "null"],+ "description": "Still sent by clients deployed before the activation endpoint.",+ "deprecated": true+ },+ "kind": {+ "$ref": "#/components/schemas/ActionKind"+ },+ "name": {+ "type": "string"+ },+ "task": {+ "type": "object"+ },+ "trigger": {+ "$ref": "#/components/schemas/ActionTrigger"+ }+ },+ "additionalProperties": false+ },"ActionExecutionRecord": {"type": "object","required": [@@ -891,10 +1005,20 @@],"description": "Live status update for a scheduled-action run, broadcast via the connection\ngateway to the owner. Clients use the typed resource to navigate to the run\ntranscript and the variant tag to toggle the running indicator. `chat_id`\nremains populated only for chat runs, for older clients.\n\nSerialized with a `type` tag (`started`/`stopped`) and delivered over the\nsingle `scheduled_action_update` message type on the gateway."},+ "SetScheduledActionEnabled": {+ "type": "object",+ "required": ["enabled"],+ "properties": {+ "enabled": {+ "type": "boolean"+ }+ },+ "additionalProperties": false+ },"UpdateScheduledAction": {"oneOf": [{- "$ref": "#/components/schemas/ActionConfiguration"+ "$ref": "#/components/schemas/ActionConfigurationUpdate"},{"$ref": "#/components/schemas/LegacyActionConfiguration"diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.tsindex d085ad7372..e65e0a38a7 100644--- a/packages/sdk/src/coverage/skipped.ts+++ b/packages/sdk/src/coverage/skipped.ts@@ -264,6 +264,7 @@ export const scheduledActionBacklog = ['executeScheduledActionNow','listScheduledActionHistory','listScheduledActions',+ 'setScheduledActionEnabled','updateScheduledAction',] as const satisfies readonly (keyof ScheduledActionSdk)[];diff --git a/services/scheduled_action/src/domain/execution.rs b/services/scheduled_action/src/domain/execution.rsindex ed14586e58..fc63618fd3 100644--- a/services/scheduled_action/src/domain/execution.rs+++ b/services/scheduled_action/src/domain/execution.rs@@ -210,7 +210,9 @@ wherelet claim = bounded(deadline,executor.cancellation.cancelled(),- executor.repo.claim_action(&id),+ executor+ .repo+ .claim_action(&id, action.configuration_revision),).await;let token = match claim {diff --git a/services/scheduled_action/src/domain/execution/test.rs b/services/scheduled_action/src/domain/execution/test.rsindex 5c6596f46d..71fd9c4b77 100644--- a/services/scheduled_action/src/domain/execution/test.rs+++ b/services/scheduled_action/src/domain/execution/test.rs@@ -21,6 +21,7 @@ const USER: &str = "macro|[email protected]";struct Repo {claim: Mutex<Option<ClaimToken>>,claims: AtomicUsize,+ claimed_revisions: Mutex<Vec<i64>>,releases: AtomicUsize,records: Mutex<Vec<ActionExecutionRecord>>,fail_persistence: bool,@@ -28,8 +29,9 @@ struct Repo {}impl ScheduledActionRepo for Repo {- async fn claim_action(&self, _: &Uuid) -> Result<ClaimToken> {+ async fn claim_action(&self, _: &Uuid, revision: ConfigurationRevision) -> Result<ClaimToken> {self.claims.fetch_add(1, Ordering::SeqCst);+ self.claimed_revisions.lock().unwrap().push(revision.get());let mut claim = self.claim.lock().unwrap();anyhow::ensure!(claim.is_none(), "already running");let token = ClaimToken::generate();@@ -280,6 +282,17 @@ async fn manual_event_action_does_not_fabricate_event_context() {assert_eq!(executor.repo.claims.load(Ordering::SeqCst), 1);}+#[tokio::test]+async fn claim_is_fenced_to_the_snapshot_revision() {+ let executor = executor(Repo::default(), Runner::default());+ let mut action = action();+ action.configuration_revision = ConfigurationRevision::try_from(7).unwrap();+ executor.runner.finish.cancel();+ executor.execute_action(action).await.unwrap();+ drain(&executor).await;+ assert_eq!(*executor.repo.claimed_revisions.lock().unwrap(), [7]);+}+#[tokio::test]async fn manual_claim_failure_never_prepares_or_runs() {let executor = executor(Repo::default(), Runner::default());diff --git a/services/scheduled_action/src/domain/models.rs b/services/scheduled_action/src/domain/models.rsindex 7cf34c9a28..050698650a 100644--- a/services/scheduled_action/src/domain/models.rs+++ b/services/scheduled_action/src/domain/models.rs@@ -187,28 +187,50 @@ pub enum CreateScheduledAction {Legacy(LegacyActionConfiguration),}+/// Canonical configuration replacement. Activation has its own endpoint, so+/// omitting `enabled` keeps the stored value.+#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]+#[serde(deny_unknown_fields)]+pub struct ActionConfigurationUpdate {+ pub name: String,+ pub trigger: ActionTrigger,+ pub kind: ActionKind,+ #[schema(value_type = Object)]+ pub task: Value,+ /// Still sent by clients deployed before the activation endpoint.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schema(deprecated)]+ pub enabled: Option<bool>,+}+/// Full replacement of client configuration, not of server-owned action state.#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]#[serde(untagged)]pub enum UpdateScheduledAction {- Canonical(ActionConfiguration),+ Canonical(ActionConfigurationUpdate),Legacy(LegacyActionConfiguration),}-impl From<CreateScheduledAction> for ActionConfiguration {- fn from(input: CreateScheduledAction) -> Self {- match input {- CreateScheduledAction::Canonical(input) => input,- CreateScheduledAction::Legacy(input) => input.into(),+impl UpdateScheduledAction {+ pub fn into_configuration(self, stored_enabled: bool) -> ActionConfiguration {+ match self {+ Self::Canonical(input) => ActionConfiguration {+ name: input.name,+ trigger: input.trigger,+ kind: input.kind,+ task: input.task,+ enabled: input.enabled.unwrap_or(stored_enabled),+ },+ Self::Legacy(input) => input.into(),}}}-impl From<UpdateScheduledAction> for ActionConfiguration {- fn from(input: UpdateScheduledAction) -> Self {+impl From<CreateScheduledAction> for ActionConfiguration {+ fn from(input: CreateScheduledAction) -> Self {match input {- UpdateScheduledAction::Canonical(input) => input,- UpdateScheduledAction::Legacy(input) => input.into(),+ CreateScheduledAction::Canonical(input) => input,+ CreateScheduledAction::Legacy(input) => input.into(),}}}@@ -414,9 +436,9 @@ impl ScheduledActionUpdate {pub const SCHEDULED_ACTION_UPDATE_MESSAGE_TYPE: &str = "scheduled_action_update";/// Returned by the executor when a run cannot start because the action is-/// already claimed by another in-flight execution. Callers at the HTTP-/// boundary map this to 409 Conflict; the polling dispatcher treats it as a-/// benign "another worker got there first" signal.+/// already claimed by another in-flight execution, or its configuration changed+/// after the caller read it. Callers at the HTTP boundary map this to 409+/// Conflict; the polling dispatcher treats it as benign and polls again.#[derive(Debug)]pub struct AlreadyRunningError {pub action_id: Uuid,diff --git a/services/scheduled_action/src/domain/models/test.rs b/services/scheduled_action/src/domain/models/test.rsindex 9a42cdee43..79c0294542 100644--- a/services/scheduled_action/src/domain/models/test.rs+++ b/services/scheduled_action/src/domain/models/test.rs@@ -20,12 +20,23 @@ fn both_request_representations_normalize_to_the_same_configuration() {let create: CreateScheduledAction = serde_json::from_value(input.clone()).unwrap();let update: UpdateScheduledAction = serde_json::from_value(input).unwrap();let create = serde_json::to_value(ActionConfiguration::from(create)).unwrap();- let update = serde_json::to_value(ActionConfiguration::from(update)).unwrap();+ let update = serde_json::to_value(update.into_configuration(false)).unwrap();assert_eq!(create, update);assert_eq!(create["trigger"]["type"], "cron");}}+#[test]+fn updates_may_omit_activation_but_creates_may_not() {+ let input = json!({"name":"routine", "kind":"Agent", "task":{},+ "trigger":{"type":"cron", "schedule":"0 0 9 * * *", "timezone":"UTC"}});+ for stored in [false, true] {+ let update: UpdateScheduledAction = serde_json::from_value(input.clone()).unwrap();+ assert_eq!(update.into_configuration(stored).enabled, stored);+ }+ assert!(serde_json::from_value::<CreateScheduledAction>(input).is_err());+}+#[test]fn mixed_representations_are_rejected_even_when_the_values_agree() {let input = json!({"name":"routine", "kind":"Agent", "task":{}, "enabled":true,diff --git a/services/scheduled_action/src/domain/ports.rs b/services/scheduled_action/src/domain/ports.rsindex f387e27217..9414534a49 100644--- a/services/scheduled_action/src/domain/ports.rs+++ b/services/scheduled_action/src/domain/ports.rs@@ -1,4 +1,4 @@-use super::event_runs::ClaimToken;+use super::event_runs::{ClaimToken, ConfigurationRevision};use super::event_trigger::EventReference;use super::execution::ExecutionHandle;use super::models::{@@ -61,7 +61,13 @@ pub trait ScheduledActionRepo: Send + Sync + 'static {macro_user_id: MacroUserIdStr<'static>,) -> impl Future<Output = Result<()>> + Send;- fn claim_action(&self, id: &Uuid) -> impl Future<Output = Result<ClaimToken>> + Send;+ /// Claim only while the stored configuration is still `revision`, so a+ /// snapshot read before a pause or update can never start a run.+ fn claim_action(+ &self,+ id: &Uuid,+ revision: ConfigurationRevision,+ ) -> impl Future<Output = Result<ClaimToken>> + Send;/// Release only this execution's claim; stale tokens must not mutate a newer run.fn release_action(@@ -119,6 +125,15 @@ pub trait ScheduledActionService: Send + Sync + 'static {macro_user_id: MacroUserIdStr<'static>,) -> impl Future<Output = Result<ScheduledAction>> + Send;+ /// Change activation without touching configuration. Requesting the+ /// current state returns the stored action unchanged.+ fn set_enabled(+ &self,+ id: &Uuid,+ enabled: bool,+ macro_user_id: MacroUserIdStr<'static>,+ ) -> impl Future<Output = Result<ScheduledAction>> + Send;+fn delete_action(&self,id: &Uuid,diff --git a/services/scheduled_action/src/domain/service.rs b/services/scheduled_action/src/domain/service.rsindex 06ec5ca9d7..d56cb4ec57 100644--- a/services/scheduled_action/src/domain/service.rs+++ b/services/scheduled_action/src/domain/service.rs@@ -78,6 +78,65 @@ impl<Rpo: ScheduledActionRepo, Exe, Targets> ScheduledActionServiceImpl<Rpo, Exe}Ok(())}++ async fn replace_configuration(+ &self,+ mut action: ScheduledAction,+ input: ActionConfiguration,+ caller: &MacroUserIdStr<'static>,+ ) -> Result<ScheduledAction>+ where+ Targets: TaskTargetValidator,+ {+ require_explicit_agent(&action.task, &input.task)?;+ let trigger_changed = !same_trigger(&action.trigger, &input.trigger);+ let configuration_changed = trigger_changed+ || action.name != input.name+ || action.kind != input.kind+ || action.task != input.task;+ let disable_only = !input.enabled && !configuration_changed;+ // A rollout gate must not prevent an owner from stopping an existing+ // event action. Deletion, history and explicit manual runs also remain available.+ if !disable_only {+ self.check_event_management(&action.trigger)?;+ self.check_event_management(&input.trigger)?;+ }+ let now = Utc::now();+ if action+ .claimed+ .is_some_and(|claimed| claimed >= now - MAX_ACTION_TIME)+ && !disable_only+ {+ return Err(ActionPolicyError::UpdateConflict.into());+ }+ if !disable_only {+ self.targets.validate_task(&input.task, caller).await?;+ action.next_run_at = next_run(&input.trigger)?;+ }+ action.event_activated_at = match &input.trigger {+ ActionTrigger::Cron { .. } => None,+ ActionTrigger::Events { .. }+ if trigger_changed || (!action.enabled && input.enabled) =>+ {+ Some(now)+ }+ ActionTrigger::Events { .. } => action.event_activated_at,+ };+ action.configuration_revision = action.configuration_revision.next()?;+ action.name = input.name;+ action.trigger = input.trigger;+ action.kind = input.kind;+ action.task = input.task;+ action.enabled = input.enabled;+ action.updated_at = now;++ let updated = self.repo.update_action(action).await?;+ self.dispatcher_tx+ .send(DispatchEvent::Update(updated.clone()))+ .await+ .map_err(|e| anyhow::anyhow!("failed to dispatch update event: {e}"))?;+ Ok(updated)+ }}fn next_run(trigger: &ActionTrigger) -> Result<Option<DateTime<Utc>>> {@@ -194,58 +253,31 @@ whereinput: UpdateScheduledAction,macro_user_id: MacroUserIdStr<'static>,) -> Result<ScheduledAction> {- let mut action = self.owned_action(id, ¯o_user_id).await?;- let input = ActionConfiguration::from(input);- require_explicit_agent(&action.task, &input.task)?;- let trigger_changed = !same_trigger(&action.trigger, &input.trigger);- let configuration_changed = trigger_changed- || action.name != input.name- || action.kind != input.kind- || action.task != input.task;- let disable_only = !input.enabled && !configuration_changed;- // A rollout gate must not prevent an owner from stopping an existing- // event action. Deletion, history and explicit manual runs also remain available.- if !disable_only {- self.check_event_management(&action.trigger)?;- self.check_event_management(&input.trigger)?;- }- let now = Utc::now();- if action- .claimed- .is_some_and(|claimed| claimed >= now - MAX_ACTION_TIME)- && !disable_only- {- return Err(ActionPolicyError::UpdateConflict.into());- }- if !disable_only {- self.targets- .validate_task(&input.task, ¯o_user_id)- .await?;- action.next_run_at = next_run(&input.trigger)?;+ let action = self.owned_action(id, ¯o_user_id).await?;+ let input = input.into_configuration(action.enabled);+ self.replace_configuration(action, input, ¯o_user_id)+ .await+ }++ async fn set_enabled(+ &self,+ id: &Uuid,+ enabled: bool,+ macro_user_id: MacroUserIdStr<'static>,+ ) -> Result<ScheduledAction> {+ let action = self.owned_action(id, ¯o_user_id).await?;+ if action.enabled == enabled {+ return Ok(action);}- action.event_activated_at = match &input.trigger {- ActionTrigger::Cron { .. } => None,- ActionTrigger::Events { .. }- if trigger_changed || (!action.enabled && input.enabled) =>- {- Some(now)- }- ActionTrigger::Events { .. } => action.event_activated_at,+ let input = ActionConfiguration {+ name: action.name.clone(),+ trigger: action.trigger.clone(),+ kind: action.kind.clone(),+ task: action.task.clone(),+ enabled,};- action.configuration_revision = action.configuration_revision.next()?;- action.name = input.name;- action.trigger = input.trigger;- action.kind = input.kind;- action.task = input.task;- action.enabled = input.enabled;- action.updated_at = now;-- let updated = self.repo.update_action(action).await?;- self.dispatcher_tx- .send(DispatchEvent::Update(updated.clone()))+ self.replace_configuration(action, input, ¯o_user_id).await- .map_err(|e| anyhow::anyhow!("failed to dispatch update event: {e}"))?;- Ok(updated)}async fn delete_action(&self, id: &Uuid, macro_user_id: MacroUserIdStr<'static>) -> Result<()> {diff --git a/services/scheduled_action/src/domain/service/test.rs b/services/scheduled_action/src/domain/service/test.rsindex 210110df8c..a98acb461c 100644--- a/services/scheduled_action/src/domain/service/test.rs+++ b/services/scheduled_action/src/domain/service/test.rs@@ -2,7 +2,9 @@ mod user_cleanup;use super::*;use crate::domain::event_runs::ClaimToken;-use crate::domain::models::{ActionKind, ExecutionResource, ExecutionResourceType};+use crate::domain::models::{+ ActionConfigurationUpdate, ActionKind, ExecutionResource, ExecutionResourceType,+};use crate::domain::{event_trigger::EventReference,execution::ExecutionHandle,@@ -74,7 +76,11 @@ impl ScheduledActionRepo for FakeRepo {async fn get_next_unclaimed_actions(&self, _limit: i64) -> Result<Vec<ScheduledAction>> {unimplemented!()}- async fn claim_action(&self, _id: &Uuid) -> Result<ClaimToken> {+ async fn claim_action(+ &self,+ _id: &Uuid,+ _revision: ConfigurationRevision,+ ) -> Result<ClaimToken> {unimplemented!()}async fn release_action(&self, _id: &Uuid, _token: ClaimToken) -> Result<()> {@@ -145,6 +151,17 @@ pub(crate) fn configuration(events: bool) -> ActionConfiguration {}}+/// Clients deployed before the activation endpoint send `enabled` with every update.+fn update(config: ActionConfiguration) -> UpdateScheduledAction {+ UpdateScheduledAction::Canonical(ActionConfigurationUpdate {+ name: config.name,+ trigger: config.trigger,+ kind: config.kind,+ task: config.task,+ enabled: Some(config.enabled),+ })+}+#[tokio::test]async fn validates_before_persistence_and_rejects_cross_owner_selection() {let base = service(false);@@ -185,11 +202,7 @@ async fn validates_before_persistence_and_rejects_cross_owner_selection() {*sessions.error.lock().unwrap() = Some(RoutineSessionError::Forbidden);config.task["user_prompt"] = json!("replacement");let error = svc- .update_action(- &created.id.unwrap(),- UpdateScheduledAction::Canonical(config),- user(),- )+ .update_action(&created.id.unwrap(), update(config), user()).await.unwrap_err();assert_eq!(error.downcast_ref(), Some(&RoutineSessionError::Forbidden));@@ -226,7 +239,7 @@ async fn gated_acceptance_allows_models_and_explicit_switch_but_rejects_old_clie.unwrap();let id = created.id.unwrap();let error = base- .update_action(&id, UpdateScheduledAction::Canonical(config), user())+ .update_action(&id, update(config), user()).await.unwrap_err();assert_eq!(@@ -239,7 +252,7 @@ async fn gated_acceptance_allows_models_and_explicit_switch_but_rejects_old_cliefor enabled in [false, true] {model.enabled = enabled;let error = base- .update_action(&id, UpdateScheduledAction::Canonical(model.clone()), user())+ .update_action(&id, update(model.clone()), user()).await.unwrap_err();assert_eq!(@@ -250,7 +263,7 @@ async fn gated_acceptance_allows_models_and_explicit_switch_but_rejects_old_clie}model.task["agent"] = json!(null);let switched = base- .update_action(&id, UpdateScheduledAction::Canonical(model.clone()), user())+ .update_action(&id, update(model.clone()), user()).await.unwrap();assert_eq!(switched.task, model.task);@@ -283,11 +296,7 @@ async fn unavailable_agents_can_be_paused_deleted_and_have_history_read_without_*sessions.error.lock().unwrap() = Some(RoutineSessionError::RuntimeUnavailable);if !claimed {let error = svc- .update_action(- &id,- UpdateScheduledAction::Canonical(config.clone()),- user(),- )+ .update_action(&id, update(config.clone()), user()).await.unwrap_err();assert_eq!(@@ -298,18 +307,14 @@ async fn unavailable_agents_can_be_paused_deleted_and_have_history_read_without_let validations = sessions.validations.lock().unwrap().len();config.enabled = false;let paused = svc- .update_action(- &id,- UpdateScheduledAction::Canonical(config.clone()),- user(),- )+ .update_action(&id, update(config.clone()), user()).await.unwrap();assert!(!paused.enabled);assert_eq!(paused.task, created.task);assert_eq!(paused.claimed.is_some(), claimed);// Disabling still works if acceptance has since been turned off.- base.update_action(&id, UpdateScheduledAction::Canonical(config), user())+ base.update_action(&id, update(config), user()).await.unwrap();svc.get_execution_records(&id, user()).await.unwrap();@@ -440,12 +445,8 @@ async fn default_gate_rejects_event_creation_and_transition_but_allows_cron() {.await.unwrap();assert_policy(- svc.update_action(- &cron.id.unwrap(),- UpdateScheduledAction::Canonical(configuration(true)),- user(),- )- .await,+ svc.update_action(&cron.id.unwrap(), update(configuration(true)), user())+ .await,ActionPolicyError::EventManagementDisabled,);}@@ -468,11 +469,7 @@ async fn gate_off_rejects_enabling_an_existing_event_action() {config.enabled = true;assert_policy(disabled- .update_action(- &action.id.unwrap(),- UpdateScheduledAction::Canonical(config),- user(),- )+ .update_action(&action.id.unwrap(), update(config), user()).await,ActionPolicyError::EventManagementDisabled,);@@ -539,12 +536,12 @@ async fn foreign_and_non_user_owners_cannot_be_managed_or_executed() {let id = created.id.unwrap();svc.repo.actions.lock().unwrap().last_mut().unwrap().owner = owner;assert_policy(- svc.update_action(- &id,- UpdateScheduledAction::Canonical(configuration(true)),- user(),- )- .await,+ svc.update_action(&id, update(configuration(true)), user())+ .await,+ ActionPolicyError::NotFound,+ );+ assert_policy(+ svc.set_enabled(&id, false, user()).await,ActionPolicyError::NotFound,);assert_policy(@@ -561,6 +558,15 @@ async fn foreign_and_non_user_owners_cannot_be_managed_or_executed() {);}assert!(svc.get_actions(user(), true).await.unwrap().is_empty());+ let enabled: Vec<bool> = svc+ .repo+ .actions+ .lock()+ .unwrap()+ .iter()+ .map(|a| a.enabled)+ .collect();+ assert_eq!(enabled, [true, true, true]);assert!(svc.executor.calls.lock().unwrap().is_empty());assert_policy(svc.execute_action_now(&generate_uuid_v7(), user()).await,@@ -606,11 +612,7 @@ async fn updates_advance_revision_and_only_trigger_changes_or_enabling_reset_actsvc.repo.actions.lock().unwrap()[0].event_activated_at = Some(past);config.task["prompt"] = json!("changed");let updated = svc- .update_action(- &id,- UpdateScheduledAction::Canonical(config.clone()),- user(),- )+ .update_action(&id, update(config.clone()), user()).await.unwrap();assert_eq!(updated.configuration_revision.get(), 2);@@ -618,22 +620,14 @@ async fn updates_advance_revision_and_only_trigger_changes_or_enabling_reset_actassert_eq!(updated.event_activated_at, Some(past));config.enabled = false;let disabled = svc- .update_action(- &id,- UpdateScheduledAction::Canonical(config.clone()),- user(),- )+ .update_action(&id, update(config.clone()), user()).await.unwrap();assert_eq!(disabled.configuration_revision.get(), 3);assert_eq!(disabled.event_activated_at, Some(past));config.enabled = true;let enabled = svc- .update_action(- &id,- UpdateScheduledAction::Canonical(config.clone()),- user(),- )+ .update_action(&id, update(config.clone()), user()).await.unwrap();assert_eq!(enabled.configuration_revision.get(), 4);@@ -644,16 +638,12 @@ async fn updates_advance_revision_and_only_trigger_changes_or_enabling_reset_act).unwrap();let changed = svc- .update_action(&id, UpdateScheduledAction::Canonical(config), user())+ .update_action(&id, update(config), user()).await.unwrap();assert!(changed.event_activated_at.unwrap() > past);let cron = svc- .update_action(- &id,- UpdateScheduledAction::Canonical(configuration(false)),- user(),- )+ .update_action(&id, update(configuration(false)), user()).await.unwrap();assert!(cron.event_activated_at.is_none());@@ -674,7 +664,7 @@ async fn active_execution_blocks_replacement_but_allows_disabling_even_with_gatereplacement.name = "new name".into();assert_policy(enabled- .update_action(&id, UpdateScheduledAction::Canonical(replacement), user())+ .update_action(&id, update(replacement), user()).await,ActionPolicyError::UpdateConflict,);@@ -684,20 +674,187 @@ async fn active_execution_blocks_replacement_but_allows_disabling_even_with_gateenabled.dispatcher_tx.clone(),);assert_policy(- svc.update_action(- &id,- UpdateScheduledAction::Canonical(config.clone()),- user(),- )- .await,+ svc.update_action(&id, update(config.clone()), user()).await,ActionPolicyError::EventManagementDisabled,);config.enabled = false;let disabled = svc- .update_action(&id, UpdateScheduledAction::Canonical(config), user())+ .update_action(&id, update(config), user()).await.unwrap();assert!(!disabled.enabled);assert!(disabled.claimed.is_some());assert_eq!(disabled.event_activated_at, action.event_activated_at);}++#[tokio::test]+async fn activation_changes_are_idempotent_and_keep_configuration() {+ let (tx, mut rx) = tokio::sync::mpsc::channel(8);+ let svc = TestService::new(+ Arc::new(FakeRepo::default()),+ Arc::new(FakeExecutor::default()),+ tx,+ );+ let created = svc+ .create_action(+ CreateScheduledAction::Canonical(configuration(false)),+ user(),+ )+ .await+ .unwrap();+ let id = created.id.unwrap();+ assert!(matches!(rx.try_recv(), Ok(DispatchEvent::Create(_))));++ let unchanged = svc.set_enabled(&id, true, user()).await.unwrap();+ assert_eq!(unchanged.configuration_revision.get(), 1);+ assert_eq!(unchanged.updated_at, created.updated_at);+ assert!(rx.try_recv().is_err());++ let paused = svc.set_enabled(&id, false, user()).await.unwrap();+ let repeated = svc.set_enabled(&id, false, user()).await.unwrap();+ assert!(!repeated.enabled);+ assert_eq!(repeated.configuration_revision.get(), 2);+ assert_eq!(repeated.updated_at, paused.updated_at);+ assert!(matches!(rx.try_recv(), Ok(DispatchEvent::Update(a)) if !a.enabled));+ assert!(rx.try_recv().is_err());++ svc.repo.actions.lock().unwrap()[0].next_run_at = Some(Utc::now() - chrono::Duration::days(1));+ let resumed = svc.set_enabled(&id, true, user()).await.unwrap();+ assert!(resumed.enabled);+ assert_eq!(resumed.configuration_revision.get(), 3);+ assert!(+ resumed.next_run_at.unwrap() > Utc::now(),+ "a firing missed while paused must not run on resume"+ );+ assert!(matches!(rx.try_recv(), Ok(DispatchEvent::Update(a)) if a.enabled));++ for action in [paused, resumed] {+ assert_eq!(action.name, "routine");+ assert_eq!(+ serde_json::to_value(&action.trigger).unwrap(),+ json!({"type": "cron", "schedule": "0 0 9 * * *", "timezone": "UTC"})+ );+ assert_eq!(+ action.task,+ json!({"model": "model", "prompt": "summarize", "user_prompt": "task"})+ );+ }+}++#[tokio::test]+async fn gate_off_allows_pausing_an_event_action_but_not_resuming_it() {+ let enabled = service(true);+ let action = enabled+ .create_action(+ CreateScheduledAction::Canonical(configuration(true)),+ user(),+ )+ .await+ .unwrap();+ let id = action.id.unwrap();+ let gated = TestService::new(+ enabled.repo.clone(),+ enabled.executor.clone(),+ enabled.dispatcher_tx.clone(),+ );+ let paused = gated.set_enabled(&id, false, user()).await.unwrap();+ assert!(!paused.enabled);+ assert_eq!(paused.event_activated_at, action.event_activated_at);+ assert_policy(+ gated.set_enabled(&id, true, user()).await,+ ActionPolicyError::EventManagementDisabled,+ );+ assert!(!enabled.repo.actions.lock().unwrap()[0].enabled);++ let past = Utc::now() - chrono::Duration::days(1);+ enabled.repo.actions.lock().unwrap()[0].event_activated_at = Some(past);+ let resumed = enabled.set_enabled(&id, true, user()).await.unwrap();+ assert!(+ resumed.event_activated_at.unwrap() > past,+ "events published while paused must not be replayed"+ );+}++#[tokio::test]+async fn running_actions_can_be_paused_but_not_resumed() {+ let svc = service(true);+ let created = svc+ .create_action(+ CreateScheduledAction::Canonical(configuration(false)),+ user(),+ )+ .await+ .unwrap();+ let id = created.id.unwrap();+ svc.repo.actions.lock().unwrap()[0].claimed = Some(Utc::now());+ let paused = svc.set_enabled(&id, false, user()).await.unwrap();+ assert!(!paused.enabled);+ assert!(paused.claimed.is_some());+ assert_policy(+ svc.set_enabled(&id, true, user()).await,+ ActionPolicyError::UpdateConflict,+ );+ assert!(!svc.repo.actions.lock().unwrap()[0].enabled);+}++#[tokio::test]+async fn resuming_revalidates_the_stored_agent_but_pausing_does_not() {+ let base = service(false);+ let sessions = Arc::new(Sessions::default());+ let svc = TestService::new(+ base.repo.clone(),+ base.executor.clone(),+ base.dispatcher_tx.clone(),+ )+ .with_target_validation(TargetValidation::new(sessions.clone(), true));+ let mut config = configuration(false);+ config.task = agent_task();+ let created = svc+ .create_action(CreateScheduledAction::Canonical(config), user())+ .await+ .unwrap();+ let id = created.id.unwrap();+ *sessions.error.lock().unwrap() = Some(RoutineSessionError::RuntimeUnavailable);+ let validations = sessions.validations.lock().unwrap().len();+ let paused = svc.set_enabled(&id, false, user()).await.unwrap();+ assert_eq!(paused.task, created.task);+ assert_eq!(sessions.validations.lock().unwrap().len(), validations);++ let error = svc.set_enabled(&id, true, user()).await.unwrap_err();+ assert_eq!(+ error.downcast_ref(),+ Some(&RoutineSessionError::RuntimeUnavailable)+ );+ assert!(!base.repo.actions.lock().unwrap()[0].enabled);+ *sessions.error.lock().unwrap() = None;+ let resumed = svc.set_enabled(&id, true, user()).await.unwrap();+ assert!(resumed.enabled);+ assert_eq!(resumed.task, created.task);+}++#[tokio::test]+async fn configuration_updates_that_omit_activation_keep_it() {+ let svc = service(true);+ let id = svc+ .create_action(+ CreateScheduledAction::Canonical(configuration(false)),+ user(),+ )+ .await+ .unwrap()+ .id+ .unwrap();+ for enabled in [false, true] {+ svc.set_enabled(&id, enabled, user()).await.unwrap();+ let input = serde_json::from_value(json!({+ "name": format!("renamed while enabled={enabled}"),+ "kind": "Agent",+ "trigger": {"type": "cron", "schedule": "0 0 18 * * *", "timezone": "UTC"},+ "task": {"model": "model", "prompt": "summarize", "user_prompt": "task"},+ }))+ .unwrap();+ let updated = svc.update_action(&id, input, user()).await.unwrap();+ assert_eq!(updated.enabled, enabled);+ assert_eq!(updated.name, format!("renamed while enabled={enabled}"));+ }+}diff --git a/services/scheduled_action/src/domain/service/test/user_cleanup.rs b/services/scheduled_action/src/domain/service/test/user_cleanup.rsindex b6096a45bd..3b40892399 100644--- a/services/scheduled_action/src/domain/service/test/user_cleanup.rs+++ b/services/scheduled_action/src/domain/service/test/user_cleanup.rs@@ -43,7 +43,7 @@ impl ScheduledActionRepo for FakeRepo {async fn update_action(&self, _: ScheduledAction) -> Result<ScheduledAction> {unreachable!()}- async fn claim_action(&self, _: &Uuid) -> Result<ClaimToken> {+ async fn claim_action(&self, _: &Uuid, _: ConfigurationRevision) -> Result<ClaimToken> {unreachable!()}async fn release_action(&self, _: &Uuid, _: ClaimToken) -> Result<()> {diff --git a/services/scheduled_action/src/domain/target_runner/test.rs b/services/scheduled_action/src/domain/target_runner/test.rsindex 9081764691..3446f73870 100644--- a/services/scheduled_action/src/domain/target_runner/test.rs+++ b/services/scheduled_action/src/domain/target_runner/test.rs@@ -492,7 +492,7 @@ impl ScheduledActionRepo for UnusedRepo {async fn delete_action(&self, _: &Uuid, _: MacroUserIdStr<'static>) -> Result<()> {unimplemented!()}- async fn claim_action(&self, _: &Uuid) -> Result<ClaimToken> {+ async fn claim_action(&self, _: &Uuid, _: ConfigurationRevision) -> Result<ClaimToken> {unimplemented!()}async fn release_action(&self, _: &Uuid, _: ClaimToken) -> Result<()> {diff --git a/services/scheduled_action/src/inbound/axum_router.rs b/services/scheduled_action/src/inbound/axum_router.rsindex ac8252cfe7..b1632db42a 100644--- a/services/scheduled_action/src/inbound/axum_router.rs+++ b/services/scheduled_action/src/inbound/axum_router.rs@@ -60,6 +60,12 @@ impl From<ScheduledAction> for ScheduledActionResponse {}}+#[derive(Debug, Deserialize, ToSchema)]+#[serde(deny_unknown_fields)]+pub struct SetScheduledActionEnabled {+ pub enabled: bool,+}+#[derive(Debug, Default, Deserialize, IntoParams)]pub struct ListActionsQuery {/// Backend clients must opt in to event actions; defaults to false (cron-only).@@ -108,6 +114,10 @@ where"/scheduled-actions/{id}",put(update_action::<S, Auth>).delete(delete_action::<S, Auth>),)+ .route(+ "/scheduled-actions/{id}/enabled",+ put(set_action_enabled::<S, Auth>),+ ).route("/scheduled-actions/{id}/execute",post(execute_action::<S, Auth>),@@ -242,6 +252,43 @@ pub async fn update_action<Ok(Json(ScheduledActionResponse::from(updated)))}+#[utoipa::path(+ put,+ path = "/scheduled-actions/{id}/enabled",+ tag = "scheduled actions",+ operation_id = "set_scheduled_action_enabled",+ params(("id" = String, Path, description = "ID of the scheduled action")),+ request_body = SetScheduledActionEnabled,+ responses(+ (status = 200, body = ScheduledActionResponse),+ (status = 400, body = String),+ (status = 409, body = String, description = "Configuration changed or execution is active"),+ (status = 401, body = String),+ (status = 404, body = String),+ (status = 500, body = String),+ )+)]+pub async fn set_action_enabled<+ S: ScheduledActionService + Send + Sync + 'static,+ Auth: MacroAuthorizationService,+>(+ State(state): State<ScheduledActionRouterState<S, Auth>>,+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ Path(id): Path<Uuid>,+ body: Result<Json<SetScheduledActionEnabled>, JsonRejection>,+) -> Result<impl IntoResponse, ScheduledActionApiError> {+ let Json(req) = body.map_err(ScheduledActionApiError::InvalidRequest)?;+ let action = state+ .service+ .set_enabled(+ &id,+ req.enabled,+ user.authorization.user.macro_user_id.clone(),+ )+ .await?;+ Ok(Json(ScheduledActionResponse::from(action)))+}+#[utoipa::path(delete,path = "/scheduled-actions/{id}",diff --git a/services/scheduled_action/src/inbound/axum_router/test.rs b/services/scheduled_action/src/inbound/axum_router/test.rsindex 23a7451382..e429e33312 100644--- a/services/scheduled_action/src/inbound/axum_router/test.rs+++ b/services/scheduled_action/src/inbound/axum_router/test.rs@@ -198,6 +198,7 @@ async fn foreign_owner_operations_return_not_found_and_list_is_empty() {let url = format!("/scheduled-actions/{}", action["id"].as_str().unwrap());for (method, path, body) in [("PUT", url.clone(), legacy()),+ ("PUT", format!("{url}/enabled"), json!({"enabled": false})),("DELETE", url.clone(), Value::Null),("POST", format!("{url}/execute"), Value::Null),("GET", format!("{url}/history"), Value::Null),@@ -221,6 +222,38 @@ async fn foreign_owner_operations_return_not_found_and_list_is_empty() {);}+#[tokio::test]+async fn activation_endpoint_is_idempotent_and_accepts_only_enabled() {+ let app = router(false);+ let (_, created) = request(&app, "POST", "/scheduled-actions", "owner", legacy()).await;+ let url = format!(+ "/scheduled-actions/{}/enabled",+ created["id"].as_str().unwrap()+ );+ for _ in 0..2 {+ let (status, paused) = request(&app, "PUT", &url, "owner", json!({"enabled": false})).await;+ assert_eq!(status, StatusCode::OK);+ assert_eq!(paused["enabled"], false);+ assert_eq!(paused["configuration_revision"], 2);+ assert_eq!(paused["name"], "legacy");+ assert_eq!(paused["schedule"], "0 0 9 * * *");+ }+ for invalid in [+ json!({}),+ json!({"enabled": "false"}),+ json!({"enabled": true, "name": "renamed"}),+ ] {+ assert_eq!(+ request(&app, "PUT", &url, "owner", invalid).await.0,+ StatusCode::BAD_REQUEST+ );+ }+ let (status, resumed) = request(&app, "PUT", &url, "owner", json!({"enabled": true})).await;+ assert_eq!(status, StatusCode::OK);+ assert_eq!(resumed["enabled"], true);+ assert_eq!(resumed["configuration_revision"], 3);+}+#[tokio::test]async fn event_management_off_and_expired_cron_are_bad_requests() {let app = router(false);@@ -456,6 +489,7 @@ fn openapi_documents_canonical_legacy_and_event_opt_in_contracts() {let schemas = &spec["components"]["schemas"];for name in ["ActionConfiguration",+ "ActionConfigurationUpdate","LegacyActionConfiguration","ActionTrigger","EventFilters",@@ -463,9 +497,24 @@ fn openapi_documents_canonical_legacy_and_event_opt_in_contracts() {"ScheduledActionResponse","CreateScheduledAction","UpdateScheduledAction",+ "SetScheduledActionEnabled",] {assert!(!schemas[name].is_null(), "missing {name}");}+ let update = &schemas["ActionConfigurationUpdate"];+ assert_eq!(+ update["required"],+ json!(["name", "trigger", "kind", "task"])+ );+ assert_eq!(update["properties"]["enabled"]["deprecated"], true);+ assert_eq!(+ schemas["SetScheduledActionEnabled"]["additionalProperties"],+ false+ );+ assert_eq!(+ spec["paths"]["/scheduled-actions/{id}/enabled"]["put"]["operationId"],+ "set_scheduled_action_enabled"+ );let legacy_properties = &schemas["ScheduledActionResponse"]["allOf"][1]["properties"];assert_eq!(legacy_properties["schedule"]["deprecated"], true);assert_eq!(legacy_properties["timezone"]["deprecated"], true);diff --git a/services/scheduled_action/src/outbound/pg_polling_dispatcher/test.rs b/services/scheduled_action/src/outbound/pg_polling_dispatcher/test.rsindex 4af30dfd24..0c28729adf 100644--- a/services/scheduled_action/src/outbound/pg_polling_dispatcher/test.rs+++ b/services/scheduled_action/src/outbound/pg_polling_dispatcher/test.rs@@ -94,7 +94,11 @@ impl ScheduledActionRepo for FakeRepository {Ok(())}- async fn claim_action(&self, _id: &Uuid) -> Result<crate::domain::event_runs::ClaimToken> {+ async fn claim_action(+ &self,+ _id: &Uuid,+ _revision: ConfigurationRevision,+ ) -> Result<crate::domain::event_runs::ClaimToken> {Ok(crate::domain::event_runs::ClaimToken::generate())}diff --git a/services/scheduled_action/src/outbound/pg_scheduled_action_repo.rs b/services/scheduled_action/src/outbound/pg_scheduled_action_repo.rsindex e3836820bd..df925c3f34 100644--- a/services/scheduled_action/src/outbound/pg_scheduled_action_repo.rs+++ b/services/scheduled_action/src/outbound/pg_scheduled_action_repo.rs@@ -332,7 +332,7 @@ impl ScheduledActionRepo for PgScheduledActionRepo {Ok(())}- async fn claim_action(&self, id: &Uuid) -> Result<ClaimToken> {+ async fn claim_action(&self, id: &Uuid, revision: ConfigurationRevision) -> Result<ClaimToken> {let token = ClaimToken::generate();let now = Utc::now();let stale_threshold = now - MAX_ACTION_TIME;@@ -342,12 +342,14 @@ impl ScheduledActionRepo for PgScheduledActionRepo {UPDATE scheduled_actionSET claimed = $1, claim_token = $4, updated_at = now()WHERE id = $2+ AND configuration_revision = $5AND (claimed IS NULL OR claimed < $3)"#,now,*id,stale_threshold,token.as_uuid(),+ revision.get(),).execute(&self.pool).await?;diff --git a/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test.rs b/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test.rsindex f9fb98c23f..d1013c33e6 100644--- a/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test.rs+++ b/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test.rs@@ -183,7 +183,10 @@ async fn replacement_is_fenced_against_claims_and_stale_revisions(pool: PgPool)replacement.name = "replacement".into();// Claim after management read, before its write.- let token = repo.claim_action(&id).await.unwrap();+ let token = repo+ .claim_action(&id, action.configuration_revision)+ .await+ .unwrap();let error = repo.update_action(replacement.clone()).await.unwrap_err();assert!(matches!(error.downcast_ref(),@@ -225,16 +228,63 @@ async fn second_claim_returns_already_running(pool: PgPool) {.expect("create should succeed");let id = created.id.expect("create returns Some(id)");- repo.claim_action(&id)+ repo.claim_action(&id, created.configuration_revision).await.expect("first claim should succeed");let error = repo- .claim_action(&id)+ .claim_action(&id, created.configuration_revision).await.expect_err("second claim should fail");assert!(error.downcast_ref::<AlreadyRunningError>().is_some());}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn claims_from_snapshots_older_than_a_pause_or_update_fail(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgScheduledActionRepo::new(pool);+ let polled = repo+ .create_action(sample_action(user_owner(USER_A), "standup"))+ .await+ .unwrap();+ let id = polled.id.unwrap();+ let paused = repo+ .update_action(ScheduledAction {+ enabled: false,+ configuration_revision: polled.configuration_revision.next().unwrap(),+ ..polled.clone()+ })+ .await+ .unwrap();+ let error = repo+ .claim_action(&id, polled.configuration_revision)+ .await+ .expect_err("a snapshot from before the pause must not claim");+ assert!(error.downcast_ref::<AlreadyRunningError>().is_some());+ let manual = repo+ .claim_action(&id, paused.configuration_revision)+ .await+ .expect("a manual run of the paused action claims");+ repo.release_action(&id, manual).await.unwrap();++ let renamed = repo+ .update_action(ScheduledAction {+ name: "renamed".into(),+ enabled: true,+ configuration_revision: paused.configuration_revision.next().unwrap(),+ ..paused.clone()+ })+ .await+ .unwrap();+ assert!(+ repo.claim_action(&id, paused.configuration_revision)+ .await+ .is_err()+ );+ repo.claim_action(&id, renamed.configuration_revision)+ .await+ .expect("the current snapshot claims");+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn release_is_fenced_to_its_own_execution(pool: PgPool) {insert_user(&pool, USER_A).await;@@ -244,18 +294,19 @@ async fn release_is_fenced_to_its_own_execution(pool: PgPool) {.await.unwrap();let id = action.id.unwrap();- let old = repo.claim_action(&id).await.unwrap();+ let revision = action.configuration_revision;+ let old = repo.claim_action(&id, revision).await.unwrap();repo.release_action(&id, crate::domain::event_runs::ClaimToken::generate()).await.unwrap();- assert!(repo.claim_action(&id).await.is_err());+ assert!(repo.claim_action(&id, revision).await.is_err());repo.release_action(&id, old).await.unwrap();- let current = repo.claim_action(&id).await.unwrap();+ let current = repo.claim_action(&id, revision).await.unwrap();assert_ne!(old, current);repo.release_action(&id, old).await.unwrap();- assert!(repo.claim_action(&id).await.is_err());+ assert!(repo.claim_action(&id, revision).await.is_err());repo.release_action(&id, current).await.unwrap();- assert!(repo.claim_action(&id).await.is_ok());+ assert!(repo.claim_action(&id, revision).await.is_ok());}#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]@@ -382,7 +433,10 @@ async fn event_round_trip_and_bookkeeping_does_not_advance_configuration(pool: Plet after = repo.get_action(&id, user(USER_A)).await.unwrap().unwrap();assert_eq!(after.updated_at, before.updated_at);assert_eq!(after.next_run_at, None);- let token = repo.claim_action(&id).await.unwrap();+ let token = repo+ .claim_action(&id, before.configuration_revision)+ .await+ .unwrap();repo.release_action(&id, token).await.unwrap();repo.update_last_executed(&id, Utc::now()).await.unwrap();let after = repo.get_action(&id, user(USER_A)).await.unwrap().unwrap();@@ -511,7 +565,9 @@ async fn polling_returns_only_enabled_unclaimed_cron_rows(pool: PgPool) {.create_action(sample_action(user_owner(USER_A), "claimed")).await.unwrap();- repo.claim_action(&claimed.id.unwrap()).await.unwrap();+ repo.claim_action(&claimed.id.unwrap(), claimed.configuration_revision)+ .await+ .unwrap();let cron = repo.create_action(sample_action(user_owner(USER_A), "cron")).awaitdiff --git a/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test/user_cleanup.rs b/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test/user_cleanup.rsindex dc222c34af..ea109cf7ef 100644--- a/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test/user_cleanup.rs+++ b/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test/user_cleanup.rs@@ -28,7 +28,9 @@ async fn deletes_user_actions_without_cascade_and_preserves_other_users(pool: Pg}).await.unwrap();- repo.claim_action(&enabled.id.unwrap()).await.unwrap();+ repo.claim_action(&enabled.id.unwrap(), enabled.configuration_revision)+ .await+ .unwrap();let event = repo.create_action(event_action()).await.unwrap();let other = repo.create_action(sample_action(user_owner(USER_B), "other"))diff --git a/services/scheduled_action/src/swagger.rs b/services/scheduled_action/src/swagger.rsindex e058edcec9..cc7c5c57c7 100644--- a/services/scheduled_action/src/swagger.rs+++ b/services/scheduled_action/src/swagger.rs@@ -6,15 +6,16 @@ use utoipa::OpenApi;)]use crate::inbound::axum_router::{__path_create_action, __path_delete_action, __path_execute_action, __path_health,- __path_list_actions, __path_list_history, __path_update_action, ScheduledActionResponse,+ __path_list_actions, __path_list_history, __path_set_action_enabled, __path_update_action,+ ScheduledActionResponse, SetScheduledActionEnabled,};use crate::domain::event_trigger::{ActionTrigger, EventFilter, EventFilters, EventName};use crate::domain::models::{- ActionConfiguration, ActionExecutionRecord, ActionKind, AgentTask, AgentTaskAgent,- CreateScheduledAction, ExecutionResource, ExecutionResourceType, ExecutionResult,- InProgressExecution, LegacyActionConfiguration, RoutineModelId, Schedule, ScheduledAction,- ScheduledActionUpdate, UpdateScheduledAction,+ ActionConfiguration, ActionConfigurationUpdate, ActionExecutionRecord, ActionKind, AgentTask,+ AgentTaskAgent, CreateScheduledAction, ExecutionResource, ExecutionResourceType,+ ExecutionResult, InProgressExecution, LegacyActionConfiguration, RoutineModelId, Schedule,+ ScheduledAction, ScheduledActionUpdate, UpdateScheduledAction,};use model::response::EmptyResponse;@@ -30,6 +31,7 @@ use model::response::EmptyResponse;crate::inbound::axum_router::list_actions,crate::inbound::axum_router::create_action,crate::inbound::axum_router::update_action,+ crate::inbound::axum_router::set_action_enabled,crate::inbound::axum_router::delete_action,crate::inbound::axum_router::execute_action,crate::inbound::axum_router::list_history,@@ -39,6 +41,7 @@ use model::response::EmptyResponse;ScheduledAction,ScheduledActionResponse,ActionConfiguration,+ ActionConfigurationUpdate,LegacyActionConfiguration,ActionTrigger,EventFilter,@@ -46,6 +49,7 @@ use model::response::EmptyResponse;EventName,CreateScheduledAction,UpdateScheduledAction,+ SetScheduledActionEnabled,Schedule,ActionKind,AgentTask,