Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(routines): add once routines that run at an exact time (#9336)

Wolf Mermelstein52b434e7a260
diff --git a/.sqlx/query-339fd0e2a1902209e20dae1b5191a8b9ba61686541cc8e4f9dd8b10de39e4aa5.json b/.sqlx/query-51226a0e37d6100612f402ede03812962c1517feab837d3469ffeb1cf93330b8.json
similarity index 91%
rename from .sqlx/query-339fd0e2a1902209e20dae1b5191a8b9ba61686541cc8e4f9dd8b10de39e4aa5.json
rename to .sqlx/query-51226a0e37d6100612f402ede03812962c1517feab837d3469ffeb1cf93330b8.json
index f634941e82..ef5360878c 100644
--- a/.sqlx/query-339fd0e2a1902209e20dae1b5191a8b9ba61686541cc8e4f9dd8b10de39e4aa5.json
+++ b/.sqlx/query-51226a0e37d6100612f402ede03812962c1517feab837d3469ffeb1cf93330b8.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters,\n configuration_revision, event_activated_at, trigger_config, run_visibility, template_id\n FROM scheduled_action\n WHERE enabled AND trigger_type IN ('cron', 'multiple') AND next_run_at IS NOT NULL\n AND (claimed IS NULL OR claimed < $1)\n ORDER BY next_run_at ASC, id ASC\n LIMIT $2\n ",
+ "query": "\n SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters,\n configuration_revision, event_activated_at, trigger_config, run_visibility, template_id\n FROM scheduled_action\n WHERE enabled AND trigger_type IN ('cron', 'once', 'multiple') AND next_run_at IS NOT NULL\n AND (claimed IS NULL OR claimed < $1)\n ORDER BY next_run_at ASC, id ASC\n LIMIT $2\n ",
"describe": {
"columns": [
{
@@ -127,5 +127,5 @@
true
]
},
- "hash": "339fd0e2a1902209e20dae1b5191a8b9ba61686541cc8e4f9dd8b10de39e4aa5"
+ "hash": "51226a0e37d6100612f402ede03812962c1517feab837d3469ffeb1cf93330b8"
}
diff --git a/.sqlx/query-8d484fc6738f586d946f9b99af4c33c1f0d331db120ce796a8d13170b8b0b542.json b/.sqlx/query-ca33bc73ece363d8217839bd0d728c836d6c1400571399c1591c699954d2939c.json
similarity index 63%
rename from .sqlx/query-8d484fc6738f586d946f9b99af4c33c1f0d331db120ce796a8d13170b8b0b542.json
rename to .sqlx/query-ca33bc73ece363d8217839bd0d728c836d6c1400571399c1591c699954d2939c.json
index 73de6aa0c9..420818705a 100644
--- a/.sqlx/query-8d484fc6738f586d946f9b99af4c33c1f0d331db120ce796a8d13170b8b0b542.json
+++ b/.sqlx/query-ca33bc73ece363d8217839bd0d728c836d6c1400571399c1591c699954d2939c.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n UPDATE scheduled_action\n SET next_run_at = $1, updated_at = now()\n WHERE id = $2 AND trigger_type IN ('cron', 'multiple')\n ",
+ "query": "\n UPDATE scheduled_action\n SET next_run_at = $1, updated_at = now()\n WHERE id = $2 AND trigger_type IN ('cron', 'once', 'multiple')\n ",
"describe": {
"columns": [],
"parameters": {
@@ -11,5 +11,5 @@
},
"nullable": []
},
- "hash": "8d484fc6738f586d946f9b99af4c33c1f0d331db120ce796a8d13170b8b0b542"
+ "hash": "ca33bc73ece363d8217839bd0d728c836d6c1400571399c1591c699954d2939c"
}
diff --git a/apps/web/src/features/routines/components/routine-triggers.tsx b/apps/web/src/features/routines/components/routine-triggers.tsx
index f2ff059f02..58ca3f389f 100644
--- a/apps/web/src/features/routines/components/routine-triggers.tsx
+++ b/apps/web/src/features/routines/components/routine-triggers.tsx
@@ -25,6 +25,7 @@ import {
Switch,
} from 'solid-js';
import {
+ describeTrigger,
type EventTriggerDraft,
eventScopeKind,
eventTriggerDescription,
@@ -69,12 +70,7 @@ type EventSlots = {
function scheduleSummary(trigger: ScheduleTriggerDraft) {
const label = scheduleTriggerLabel(trigger);
- if (trigger.frequency === 'once') {
- const date = new Date(trigger.onceAt);
- return Number.isFinite(date.getTime())
- ? format(date, 'MMM d, h:mm a')
- : 'Run once';
- }
+ if (trigger.frequency === 'once') return describeTrigger(trigger);
if (trigger.frequency === 'hour' || trigger.frequency === 'custom')
return label;
const date = new Date(`2000-01-01T${trigger.time}`);
diff --git a/apps/web/src/features/routines/core/routine-triggers.ts b/apps/web/src/features/routines/core/routine-triggers.ts
index fa9c8bb3cc..60c8da836f 100644
--- a/apps/web/src/features/routines/core/routine-triggers.ts
+++ b/apps/web/src/features/routines/core/routine-triggers.ts
@@ -4,6 +4,7 @@ import {
getDefaultTimezone,
} from '@core/util/cron';
import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';
+import { format } from 'date-fns';
import { match } from 'ts-pattern';
import { z } from 'zod';
@@ -711,7 +712,11 @@ export function describeTrigger(trigger: RoutineTriggerDraft): string {
})
.with('day', () => `Every day at ${formatTimeLabel(trigger.time)}`)
.with('hour', () => 'Every hour')
- .with('once', () => 'Once')
+ .with('once', () => {
+ const at = new Date(trigger.onceAt);
+ if (!Number.isFinite(at.getTime())) return 'Run once';
+ return `Once at ${format(at, at.getSeconds() ? 'MMM d, h:mm:ss a' : 'MMM d, h:mm a')}`;
+ })
.with('custom', () => `Custom schedule (${trigger.cron})`)
.exhaustive();
}
diff --git a/apps/web/src/features/routines/core/template.ts b/apps/web/src/features/routines/core/template.ts
index 533fef324d..c251a020c1 100644
--- a/apps/web/src/features/routines/core/template.ts
+++ b/apps/web/src/features/routines/core/template.ts
@@ -199,6 +199,7 @@ export function fillTemplateTrigger(args: {
.returnType<ActionTrigger>()
.with({ type: 'cron' }, (cron) => ({ ...cron, timezone }))
.with({ type: 'events' }, (events) => events)
+ .with({ type: 'once' }, (once) => once)
.with({ type: 'multiple' }, (multiple) => ({
...multiple,
triggers: multiple.triggers.map((item) =>
diff --git a/apps/web/src/features/routines/queries/routine-draft.test.ts b/apps/web/src/features/routines/queries/routine-draft.test.ts
index c130aa36f2..2942beb3b6 100644
--- a/apps/web/src/features/routines/queries/routine-draft.test.ts
+++ b/apps/web/src/features/routines/queries/routine-draft.test.ts
@@ -392,11 +392,7 @@ describe('one-off routines', () => {
const created = draftToCreateBody(draft);
expect(
created && 'trigger' in created ? created.trigger : undefined
- ).toEqual({
- type: 'cron',
- schedule: '12 0 13 3 10 * 2030',
- timezone: 'UTC',
- });
+ ).toEqual({ type: 'once', at: '2030-10-03T13:00:12.000Z' });
});
it('rejects past one-off creation but permits editing a completed routine', () => {
const once = {
diff --git a/apps/web/src/features/routines/queries/routine-draft.ts b/apps/web/src/features/routines/queries/routine-draft.ts
index b2e91bbf41..3bde059cb6 100644
--- a/apps/web/src/features/routines/queries/routine-draft.ts
+++ b/apps/web/src/features/routines/queries/routine-draft.ts
@@ -5,6 +5,7 @@ import {
} from '../core/routine-draft';
import {
onceFromCron,
+ onceTrigger,
parseRoutineTriggers,
serializeTriggers,
} from './routine-trigger-mapping';
@@ -234,16 +235,7 @@ function triggerFromDraft(
timezone = getDefaultTimezone()
) {
if (draft.triggers) return serializeTriggers(draft.triggers);
- if (draft.frequency === 'once') {
- const date = new Date(draft.onceAt ?? '');
- if (Number.isNaN(date.getTime()))
- throw new Error('Choose a valid date and time.');
- return {
- type: 'cron' as const,
- timezone: 'UTC',
- schedule: `${date.getUTCSeconds()} ${date.getUTCMinutes()} ${date.getUTCHours()} ${date.getUTCDate()} ${date.getUTCMonth() + 1} * ${date.getUTCFullYear()}`,
- };
- }
+ if (draft.frequency === 'once') return onceTrigger(draft.onceAt ?? '');
return {
type: 'cron' as const,
timezone: draft.timezone ?? timezone,
diff --git a/apps/web/src/features/routines/queries/routine-trigger-mapping.test.ts b/apps/web/src/features/routines/queries/routine-trigger-mapping.test.ts
index 3e484556dc..3d06e42a3b 100644
--- a/apps/web/src/features/routines/queries/routine-trigger-mapping.test.ts
+++ b/apps/web/src/features/routines/queries/routine-trigger-mapping.test.ts
@@ -82,14 +82,17 @@ describe('routine trigger mapping', () => {
expect(serializeTriggers(triggers)).toEqual(config);
});
it('restores a one-off instant as an editable local date', () => {
- const config = {
- type: 'cron' as const,
- schedule: '30 15 9 12 11 * 2040',
- timezone: 'UTC',
- };
+ const config = { type: 'once' as const, at: '2040-11-12T09:15:30.000Z' };
const triggers = parseRoutineTriggers(config)!;
expect(triggers[0]).toMatchObject({ frequency: 'once' });
expect(serializeTriggers(triggers)).toEqual(config);
+ // One-offs saved before the once trigger existed keep their instant.
+ const legacy = parseRoutineTriggers({
+ type: 'cron',
+ schedule: '30 15 9 12 11 * 2040',
+ timezone: 'UTC',
+ })!;
+ expect(serializeTriggers(legacy)).toEqual(config);
});
it('preserves the full backend event-filter capacity and empty selectors', () => {
diff --git a/apps/web/src/features/routines/queries/routine-trigger-mapping.ts b/apps/web/src/features/routines/queries/routine-trigger-mapping.ts
index 4188849f78..cc6edc3ffb 100644
--- a/apps/web/src/features/routines/queries/routine-trigger-mapping.ts
+++ b/apps/web/src/features/routines/queries/routine-trigger-mapping.ts
@@ -77,16 +77,7 @@ export function serializeTrigger(trigger: RoutineTriggerDraft) {
filters: [serializeFilter(trigger)],
};
const [hour, minute] = trigger.time.split(':').map(Number);
- if (trigger.frequency === 'once') {
- const date = new Date(trigger.onceAt);
- if (!Number.isFinite(date.getTime()))
- throw new Error('Choose a date and time.');
- return {
- type: 'cron' as const,
- timezone: 'UTC',
- schedule: `${date.getUTCSeconds()} ${date.getUTCMinutes()} ${date.getUTCHours()} ${date.getUTCDate()} ${date.getUTCMonth() + 1} * ${date.getUTCFullYear()}`,
- };
- }
+ if (trigger.frequency === 'once') return onceTrigger(trigger.onceAt);
const schedule = match(trigger.frequency)
.with('hour', () => '0 0 * * * *')
.with('day', () => `0 ${minute} ${hour} * * *`)
@@ -122,10 +113,22 @@ export function parseRoutineTriggers(
): RoutineTriggerDraft[] | undefined {
const values = trigger.type === 'multiple' ? trigger.triggers : [trigger];
if (
- !values.every((value) => value.type === 'cron' || value.type === 'events')
+ !values.every(
+ (value) =>
+ value.type === 'cron' ||
+ value.type === 'once' ||
+ value.type === 'events'
+ )
)
return undefined;
return values.flatMap((value): RoutineTriggerDraft[] => {
+ if (value.type === 'once')
+ return [
+ {
+ ...newScheduleTrigger('once'),
+ onceAt: localDateTime(new Date(value.at)),
+ },
+ ];
if (value.type === 'events')
return value.filters.map((filter) => ({
id: crypto.randomUUID(),
@@ -183,9 +186,21 @@ export function onceFromCron(
const [second, minute, hour, day, month, , year] = parts.map(Number);
const date = new TZDate(year, month - 1, day, hour, minute, second, timezone);
if (Number.isNaN(date.getTime())) return;
- const instant = new Date(date.getTime());
+ return { frequency: 'once', onceAt: localDateTime(new Date(date.getTime())) };
+}
+
+/** An instant as the `datetime-local` value the once picker edits. */
+function localDateTime(instant: Date): string {
const local = new Date(
instant.getTime() - instant.getTimezoneOffset() * 60000
);
- return { frequency: 'once', onceAt: local.toISOString().slice(0, 19) };
+ return local.toISOString().slice(0, 19);
+}
+
+/** A single run at the picked local date and time. */
+export function onceTrigger(onceAt: string) {
+ const date = new Date(onceAt);
+ if (!Number.isFinite(date.getTime()))
+ throw new Error('Choose a date and time.');
+ return { type: 'once' as const, at: date.toISOString() };
}
diff --git a/apps/web/src/features/routines/routine-creator.test.tsx b/apps/web/src/features/routines/routine-creator.test.tsx
index 6af5fed660..af2615b637 100644
--- a/apps/web/src/features/routines/routine-creator.test.tsx
+++ b/apps/web/src/features/routines/routine-creator.test.tsx
@@ -16,7 +16,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { buildAgentRoster } from '../agents-view/core/roster';
import { getDefaultTimezone } from './core/routine-draft';
import { loadRoutineComposerDraft } from './draft-storage';
-import { onceFromCron } from './queries/routine-trigger-mapping';
import { RoutineCreator } from './routine-creator';
const host = vi.hoisted(() => ({
@@ -712,11 +711,8 @@ describe('routine composer execution selection', () => {
const body = host.create.mock.calls[0][0];
if (!('trigger' in body)) throw new Error('Expected a tagged trigger');
const trigger = body.trigger;
- expect(trigger.type).toBe('cron');
- if (trigger.type !== 'cron') throw new Error('Expected one-off cron');
- const at = onceFromCron(trigger.schedule, trigger.timezone)?.onceAt;
- expect(at).toBeDefined();
- const scheduled = new Date(at!).getTime();
+ if (trigger.type !== 'once') throw new Error('Expected a once trigger');
+ const scheduled = new Date(trigger.at).getTime();
expect(scheduled).toBeGreaterThanOrEqual(
before + 2 * 60 * 60 * 1000 - 1000
);
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
index 666adf266f..cf264bfed0 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
@@ -16455,7 +16455,7 @@ export interface CodeGuide {
*
* Prefer ExecuteCode for supported Macro work, including a single precise call. Entity indexes in context list each method with its signature. Before writing a program, read the symbols it needs with ReadCodeDocs for their parameters, options and return types, all together in one call, unless their reference is already in context; do not guess option names. Use DescribeCodeTools for the index of an entity not in context or for workflow guides, requesting entities together (e.g. documents, email, ai, core).
*
- * For editable email/calendar drafts, persist them with execution.reviews.create({kind, title, drafts}), then return reviews: [await review.reference()]. This does not send emails or create calendar events. Creation immediately presents a completed PresentReview ACP tool call, even while main continues. "Presented to the user" means saved in the conversation, not approved or sent. The saved cards remain usable after this execution and chat continues. User decisions arrive as typed system events referring to the same review ID. Use GetReview to read final drafts and confirmed outcomes; notifications never authorize repeating an action. To show the user what the program made, changed or found, present a view with await execution.views.present(view). It is checked and drawn at once, while main continues; nothing is saved and nothing comes back. When to present a view, and its format, are in the PresentView schema at the end of this description. Edit markdown documents and tasks with the SDK document edit(instructions) method. Direct human-interactive tools, subagents and unsupported SDK operations remain available.
+ * For editable email/calendar drafts, persist them with execution.reviews.create({kind, title, drafts}), then return reviews: [await review.reference()]. This does not send emails or create calendar events. Creation immediately presents a completed PresentReview ACP tool call, even while main continues. "Presented to the user" means saved in the conversation, not approved or sent. The saved cards remain usable after this execution and chat continues. User decisions arrive as typed system events referring to the same review ID. Use GetReview to read final drafts and confirmed outcomes; notifications never authorize repeating an action. To show the user what the program made, changed or found, present a view with await execution.views.present(view). It is checked and drawn at once, while main continues; nothing is saved and nothing comes back. When to present a view, and its format, are in the PresentView schema at the end of this description. Edit markdown documents and tasks with the SDK document edit(instructions) method. Direct human-interactive tools, subagents and unsupported SDK operations remain available. Never sleep, call setTimeout or poll inside ExecuteCode to wait for something. To check back later, create a routine with a once trigger due shortly, macro.routines.create({trigger: {type: "once", at}, ...}), whose prompt says what to check and where to report, then finish; it runs within about a second of at.
*
* Do the whole job in as few executions as possible, ideally one: every execution costs a model turn. Put control flow in the program instead of checking in one execution and acting in the next, e.g. if macro.tasks.findSimilar finds no likely duplicate, create the task and return it, else return the matches without creating. Use nested SDK entities, e.g. macro.documents.search(query) is an async iterator and document.content() is a promise. Use for await...of, break, conditions and ordinary JavaScript freely. Batch useful independent work with Promise.all or Promise.allSettled; inspect partial failures and await every started operation. Use bounded concurrency for large inputs. Preserve user source scope on every search and retry: macro.documents.search searches documents; macro.email.search searches emails. Read names in batches: macro.initiatives.summaries() and macro.tasks.summaries(tasks) each take one request, while name() on every handle loads each entity separately. Create a task with its initiative, assignees and dueDate in one macro.tasks.create call. Return compact evidence with source IDs, URLs, explicit failures and coverage limits, enough to answer without a follow-up execution; for each item you create or point the user to, return its webUrl() as the URL rather than building one; do not return SDK objects, raw large batches, or claim a stopped iterator is exhaustive.
*
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionTrigger.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionTrigger.ts
index f8566a1f9c..7012b49097 100644
--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionTrigger.ts
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionTrigger.ts
@@ -7,6 +7,7 @@
*/
import type { ActionTriggerOneOf } from './actionTriggerOneOf';
import type { ActionTriggerOneOfFive } from './actionTriggerOneOfFive';
+import type { ActionTriggerOneOfSeven } from './actionTriggerOneOfSeven';
import type { ActionTriggerOneOfThree } from './actionTriggerOneOfThree';
/**
@@ -15,4 +16,5 @@ import type { ActionTriggerOneOfThree } from './actionTriggerOneOfThree';
export type ActionTrigger =
| ActionTriggerOneOf
| ActionTriggerOneOfThree
- | ActionTriggerOneOfFive;
+ | ActionTriggerOneOfFive
+ | ActionTriggerOneOfSeven;
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionTriggerOneOfFive.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionTriggerOneOfFive.ts
index c2cba6cb20..5b06eac770 100644
--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionTriggerOneOfFive.ts
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionTriggerOneOfFive.ts
@@ -5,11 +5,12 @@
* API for managing scheduled actions
* OpenAPI spec version: 0.1.0
*/
-
import type { ActionTriggerOneOfFiveType } from './actionTriggerOneOfFiveType';
-import type { RoutineTriggers } from './routineTriggers';
+/**
+ * Fires once at `at`, or as soon as it is saved when `at` has passed.
+ */
export type ActionTriggerOneOfFive = {
- triggers: RoutineTriggers;
+ at: string;
type: ActionTriggerOneOfFiveType;
};
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionTriggerOneOfFiveType.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionTriggerOneOfFiveType.ts
index d38fb100b7..75b5479222 100644
--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionTriggerOneOfFiveType.ts
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionTriggerOneOfFiveType.ts
@@ -11,5 +11,5 @@ export type ActionTriggerOneOfFiveType =
// eslint-disable-next-line @typescript-eslint/no-redeclare
export const ActionTriggerOneOfFiveType = {
- multiple: 'multiple',
+ once: 'once',
} as const;
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionTriggerOneOfSeven.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionTriggerOneOfSeven.ts
new file mode 100644
index 0000000000..dec89261a3
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionTriggerOneOfSeven.ts
@@ -0,0 +1,15 @@
+/**
+ * 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 { ActionTriggerOneOfSevenType } from './actionTriggerOneOfSevenType';
+import type { RoutineTriggers } from './routineTriggers';
+
+export type ActionTriggerOneOfSeven = {
+ triggers: RoutineTriggers;
+ type: ActionTriggerOneOfSevenType;
+};
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionTriggerOneOfSevenType.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionTriggerOneOfSevenType.ts
new file mode 100644
index 0000000000..23e54b4987
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionTriggerOneOfSevenType.ts
@@ -0,0 +1,15 @@
+/**
+ * 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 ActionTriggerOneOfSevenType =
+ (typeof ActionTriggerOneOfSevenType)[keyof typeof ActionTriggerOneOfSevenType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const ActionTriggerOneOfSevenType = {
+ multiple: 'multiple',
+} as const;
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.ts
index 2de86d8b7a..cade6a77c3 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
@@ -21,6 +21,8 @@ export * from './actionTrigger';
export * from './actionTriggerOneOf';
export * from './actionTriggerOneOfFive';
export * from './actionTriggerOneOfFiveType';
+export * from './actionTriggerOneOfSeven';
+export * from './actionTriggerOneOfSevenType';
export * from './actionTriggerOneOfThree';
export * from './actionTriggerOneOfThreeType';
export * from './actionTriggerOneOfType';
@@ -69,6 +71,8 @@ export * from './routineTemplate';
export * from './routineTemplateTask';
export * from './routineTrigger';
export * from './routineTriggerOneOf';
+export * from './routineTriggerOneOfFive';
+export * from './routineTriggerOneOfFiveType';
export * from './routineTriggerOneOfThree';
export * from './routineTriggerOneOfThreeType';
export * from './routineTriggerOneOfType';
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTrigger.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTrigger.ts
index b51721dba2..c6aa1ebf70 100644
--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTrigger.ts
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTrigger.ts
@@ -6,9 +6,13 @@
* OpenAPI spec version: 0.1.0
*/
import type { RoutineTriggerOneOf } from './routineTriggerOneOf';
+import type { RoutineTriggerOneOfFive } from './routineTriggerOneOfFive';
import type { RoutineTriggerOneOfThree } from './routineTriggerOneOfThree';
/**
* An individual trigger in a routine's trigger list.
*/
-export type RoutineTrigger = RoutineTriggerOneOf | RoutineTriggerOneOfThree;
+export type RoutineTrigger =
+ | RoutineTriggerOneOf
+ | RoutineTriggerOneOfThree
+ | RoutineTriggerOneOfFive;
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTriggerOneOfFive.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTriggerOneOfFive.ts
new file mode 100644
index 0000000000..1e79aa28b1
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTriggerOneOfFive.ts
@@ -0,0 +1,16 @@
+/**
+ * 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 { RoutineTriggerOneOfFiveType } from './routineTriggerOneOfFiveType';
+
+/**
+ * Fires once at `at`, or as soon as it is saved when `at` has passed.
+ */
+export type RoutineTriggerOneOfFive = {
+ at: string;
+ type: RoutineTriggerOneOfFiveType;
+};
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTriggerOneOfFiveType.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTriggerOneOfFiveType.ts
new file mode 100644
index 0000000000..dc257cbe17
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTriggerOneOfFiveType.ts
@@ -0,0 +1,15 @@
+/**
+ * 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 RoutineTriggerOneOfFiveType =
+ (typeof RoutineTriggerOneOfFiveType)[keyof typeof RoutineTriggerOneOfFiveType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const RoutineTriggerOneOfFiveType = {
+ once: 'once',
+} as const;
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.json
index b04a46fa95..fc827002a0 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
@@ -1021,6 +1021,21 @@
}
}
},
+ {
+ "type": "object",
+ "description": "Fires once at `at`, or as soon as it is saved when `at` has passed.",
+ "required": ["at", "type"],
+ "properties": {
+ "at": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "type": {
+ "type": "string",
+ "enum": ["once"]
+ }
+ }
+ },
{
"type": "object",
"required": ["triggers", "type"],
@@ -1540,6 +1555,21 @@
"enum": ["events"]
}
}
+ },
+ {
+ "type": "object",
+ "description": "Fires once at `at`, or as soon as it is saved when `at` has passed.",
+ "required": ["at", "type"],
+ "properties": {
+ "at": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "type": {
+ "type": "string",
+ "enum": ["once"]
+ }
+ }
}
],
"description": "An individual trigger in a routine's trigger list."
diff --git a/crates/agent_code_mode/src/inbound/toolset/session/execute_code.md b/crates/agent_code_mode/src/inbound/toolset/session/execute_code.md
index 95e5eef9d8..f301a28c41 100644
--- a/crates/agent_code_mode/src/inbound/toolset/session/execute_code.md
+++ b/crates/agent_code_mode/src/inbound/toolset/session/execute_code.md
@@ -2,4 +2,4 @@ Copy turn_id from the current prompt’s hidden invocation context; never substi
Prefer ExecuteCode for supported Macro work, including a single precise call. Entity indexes in context list each method with its signature. Before writing a program, read the symbols it needs with ReadCodeDocs for their parameters, options and return types, all together in one call, unless their reference is already in context; do not guess option names. Use DescribeCodeTools for the index of an entity not in context or for workflow guides, requesting entities together (e.g. documents, email, ai, core).
-For editable email/calendar drafts, persist them with execution.reviews.create({kind, title, drafts}), then return reviews: [await review.reference()]. This does not send emails or create calendar events. Creation immediately presents a completed PresentReview ACP tool call, even while main continues. "Presented to the user" means saved in the conversation, not approved or sent. The saved cards remain usable after this execution and chat continues. User decisions arrive as typed system events referring to the same review ID. Use GetReview to read final drafts and confirmed outcomes; notifications never authorize repeating an action. To show the user what the program made, changed or found, present a view with await execution.views.present(view). It is checked and drawn at once, while main continues; nothing is saved and nothing comes back. When to present a view, and its format, are in the PresentView schema at the end of this description. Edit markdown documents and tasks with the SDK document edit(instructions) method. Direct human-interactive tools, subagents and unsupported SDK operations remain available.
+For editable email/calendar drafts, persist them with execution.reviews.create({kind, title, drafts}), then return reviews: [await review.reference()]. This does not send emails or create calendar events. Creation immediately presents a completed PresentReview ACP tool call, even while main continues. "Presented to the user" means saved in the conversation, not approved or sent. The saved cards remain usable after this execution and chat continues. User decisions arrive as typed system events referring to the same review ID. Use GetReview to read final drafts and confirmed outcomes; notifications never authorize repeating an action. To show the user what the program made, changed or found, present a view with await execution.views.present(view). It is checked and drawn at once, while main continues; nothing is saved and nothing comes back. When to present a view, and its format, are in the PresentView schema at the end of this description. Edit markdown documents and tasks with the SDK document edit(instructions) method. Direct human-interactive tools, subagents and unsupported SDK operations remain available. Never sleep, call setTimeout or poll inside ExecuteCode to wait for something. To check back later, create a routine with a once trigger due shortly, macro.routines.create({trigger: {type: "once", at}, ...}), whose prompt says what to check and where to report, then finish; it runs within about a second of at.
diff --git a/crates/agent_code_mode/src/inbound/toolset/user/execute_code.md b/crates/agent_code_mode/src/inbound/toolset/user/execute_code.md
index f9a7958517..cf62690346 100644
--- a/crates/agent_code_mode/src/inbound/toolset/user/execute_code.md
+++ b/crates/agent_code_mode/src/inbound/toolset/user/execute_code.md
@@ -1,3 +1,3 @@
Run a JavaScript ES module in Deno against the real Macro SDK, as the signed-in user. Export async function main({macro}); return {data: <JSON>}. macro is an authenticated Macro SDK client. Optional imports: import {Macro} from "@macro-inc/sdk"; import Handlebars from "handlebars". main also receives token and hosts for explicit SDK construction. Never print, return or persist the token. No TypeScript syntax or package installation.
-Prefer ExecuteCode for Macro work that would otherwise take several tool calls. Before writing a program, call DescribeCodeTools with task set to what the program must do, unless the entity indexes it needs are already in this conversation, then read the symbols the program uses with ReadCodeDocs, all together in one call. The SDK is large; do not guess method names or options. If a program fails with an SDK error, read the symbol involved with ReadCodeDocs and fix the program.
+Prefer ExecuteCode for Macro work that would otherwise take several tool calls. Before writing a program, call DescribeCodeTools with task set to what the program must do, unless the entity indexes it needs are already in this conversation, then read the symbols the program uses with ReadCodeDocs, all together in one call. The SDK is large; do not guess method names or options. If a program fails with an SDK error, read the symbol involved with ReadCodeDocs and fix the program. Never sleep, call setTimeout or poll inside ExecuteCode to wait for something. To check back later, create a routine with a once trigger due shortly, macro.routines.create({trigger: {type: "once", at}, ...}), whose prompt says what to check and where to report, then finish; it runs within about a second of at.
diff --git a/crates/complete_graph/src/sdl_test.rs b/crates/complete_graph/src/sdl_test.rs
index 3c700afbec..1320b9fa11 100644
--- a/crates/complete_graph/src/sdl_test.rs
+++ b/crates/complete_graph/src/sdl_test.rs
@@ -646,7 +646,7 @@ fn scheduled_actions_hang_off_the_authenticated_user() {
assert_sdl_line(&sdl, "scheduledActions: [GraphqlScheduledAction!]!");
assert_sdl_line(
&sdl,
- "union GraphqlScheduledActionTrigger = GraphqlScheduledActionCronTrigger | GraphqlScheduledActionEventsTrigger | GraphqlScheduledActionMultipleTrigger",
+ "union GraphqlScheduledActionTrigger = GraphqlScheduledActionCronTrigger | GraphqlScheduledActionEventsTrigger | GraphqlScheduledActionOnceTrigger | GraphqlScheduledActionMultipleTrigger",
);
assert!(sdl.contains("AI routines the authenticated user can access."));
for value in [
diff --git a/crates/graphql_scheduled_action/Cargo.toml b/crates/graphql_scheduled_action/Cargo.toml
index 300af92171..a14b64cf70 100644
--- a/crates/graphql_scheduled_action/Cargo.toml
+++ b/crates/graphql_scheduled_action/Cargo.toml
@@ -6,6 +6,7 @@ publish = false
[dependencies]
async-graphql = { workspace = true }
+chrono = { workspace = true }
macro_user_id = { path = "../macro_user_id" }
rootcause = { workspace = true }
scheduled_action = { path = "../scheduled_action" }
@@ -14,7 +15,6 @@ tracing = { workspace = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
-chrono = { workspace = true }
macro_uuid = { path = "../macro_uuid" }
model_owner = { path = "../model_owner" }
tokio = { workspace = true, features = ["macros", "rt"] }
diff --git a/crates/graphql_scheduled_action/src/objects.rs b/crates/graphql_scheduled_action/src/objects.rs
index 33facb08bd..3b525ea10d 100644
--- a/crates/graphql_scheduled_action/src/objects.rs
+++ b/crates/graphql_scheduled_action/src/objects.rs
@@ -1,4 +1,5 @@
use async_graphql::{Enum, ID, SimpleObject, Union};
+use chrono::{DateTime, Utc};
use rootcause::Report;
use scheduled_action::domain::{
event_trigger::{ActionTrigger, EventName, RoutineTrigger},
@@ -33,9 +34,19 @@ pub struct GraphqlScheduledAction {
pub(crate) enum GraphqlScheduledActionTrigger {
Cron(GraphqlScheduledActionCronTrigger),
Events(GraphqlScheduledActionEventsTrigger),
+ Once(GraphqlScheduledActionOnceTrigger),
Multiple(GraphqlScheduledActionMultipleTrigger),
}
+/// A routine that runs a single time.
+#[derive(SimpleObject)]
+pub(crate) struct GraphqlScheduledActionOnceTrigger {
+ /// When the routine runs, as RFC 3339.
+ at: String,
+ /// Whether that run is still ahead. False once it has run.
+ pending: bool,
+}
+
/// A routine that runs on a cron schedule.
#[derive(SimpleObject)]
pub(crate) struct GraphqlScheduledActionCronTrigger {
@@ -52,6 +63,8 @@ pub(crate) struct GraphqlScheduledActionCronTrigger {
pub(crate) struct GraphqlScheduledActionMultipleTrigger {
/// Each schedule retains its own timezone and next firing.
schedules: Vec<GraphqlScheduledActionCronTrigger>,
+ /// Single runs at exact times.
+ once: Vec<GraphqlScheduledActionOnceTrigger>,
/// Events that can also trigger this routine.
events: Option<GraphqlScheduledActionEventsTrigger>,
}
@@ -239,7 +252,15 @@ fn trigger(action: &ScheduledAction) -> GraphqlScheduledActionTrigger {
.flatten(),
})
}
- RoutineTrigger::Events { .. } => None,
+ RoutineTrigger::Once { .. } | RoutineTrigger::Events { .. } => None,
+ })
+ .collect(),
+ once: triggers
+ .as_slice()
+ .iter()
+ .filter_map(|trigger| match trigger {
+ RoutineTrigger::Once { at } => Some(once_trigger(action, *at)),
+ RoutineTrigger::Cron { .. } | RoutineTrigger::Events { .. } => None,
})
.collect(),
events: action.trigger.event_filters().map(event_filters),
@@ -248,6 +269,18 @@ fn trigger(action: &ScheduledAction) -> GraphqlScheduledActionTrigger {
ActionTrigger::Events { filters } => {
GraphqlScheduledActionTrigger::Events(event_filters(filters))
}
+ ActionTrigger::Once { at } => {
+ GraphqlScheduledActionTrigger::Once(once_trigger(action, *at))
+ }
+ }
+}
+
+/// Pending firings never come after `next_run_at`, so a once time at or after
+/// it has yet to run.
+fn once_trigger(action: &ScheduledAction, at: DateTime<Utc>) -> GraphqlScheduledActionOnceTrigger {
+ GraphqlScheduledActionOnceTrigger {
+ at: at.to_rfc3339(),
+ pending: action.next_run_at.is_some_and(|next| next <= at),
}
}
diff --git a/crates/macro_db_client/migrations/20261102030508_scheduled_action_once_trigger.sql b/crates/macro_db_client/migrations/20261102030508_scheduled_action_once_trigger.sql
new file mode 100644
index 0000000000..44db8e218b
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261102030508_scheduled_action_once_trigger.sql
@@ -0,0 +1,62 @@
+-- Routines can fire once at an exact time, alone or among other triggers.
+-- A once routine keeps its configuration in trigger_config, like `multiple`.
+ALTER TABLE scheduled_action DROP CONSTRAINT scheduled_action_trigger_shape_check;
+ALTER TABLE scheduled_action
+ADD CONSTRAINT scheduled_action_trigger_shape_check CHECK (
+ (
+ (trigger_type = 'cron'
+ AND schedule IS NOT NULL
+ AND timezone IS NOT NULL
+ AND event_filters IS NULL
+ AND event_activated_at IS NULL)
+ OR
+ (trigger_type = 'events'
+ AND schedule IS NULL
+ AND timezone IS NULL
+ AND next_run_at IS NULL
+ AND event_filters IS NOT NULL
+ AND CASE WHEN jsonb_typeof(event_filters) = 'array'
+ THEN jsonb_array_length(event_filters) BETWEEN 1 AND 32
+ ELSE FALSE END
+ AND event_activated_at IS NOT NULL)
+ OR
+ (trigger_type = 'once'
+ AND schedule IS NULL
+ AND timezone IS NULL
+ AND event_filters IS NULL
+ AND event_activated_at IS NULL
+ AND trigger_config IS NOT NULL
+ AND trigger_config->>'type' = 'once'
+ AND trigger_config->>'at' IS NOT NULL)
+ OR
+ (trigger_type = 'multiple'
+ AND schedule IS NULL
+ AND timezone IS NULL
+ AND trigger_config IS NOT NULL
+ AND trigger_config->>'type' = 'multiple'
+ AND (
+ (event_filters IS NULL AND event_activated_at IS NULL)
+ OR
+ (event_filters IS NOT NULL AND event_activated_at IS NOT NULL
+ AND CASE WHEN jsonb_typeof(event_filters) = 'array'
+ THEN jsonb_array_length(event_filters) BETWEEN 1 AND 32
+ ELSE FALSE END)
+ ))
+ ) IS TRUE
+);
+
+-- A routine contains between one and sixteen schedule, once and event triggers.
+ALTER TABLE scheduled_action DROP CONSTRAINT scheduled_action_supported_triggers_check;
+ALTER TABLE scheduled_action
+ADD CONSTRAINT scheduled_action_supported_triggers_check CHECK (
+ (trigger_type IN ('cron', 'events', 'once') OR (
+ trigger_type = 'multiple'
+ AND CASE WHEN jsonb_typeof(trigger_config->'triggers') = 'array'
+ THEN jsonb_array_length(trigger_config->'triggers') BETWEEN 1 AND 16
+ AND jsonb_array_length(jsonb_path_query_array(
+ trigger_config,
+ '$.triggers[*] ? (@.type == "cron" || @.type == "events" || @.type == "once")'
+ )) = jsonb_array_length(trigger_config->'triggers')
+ ELSE FALSE END
+ )) IS TRUE
+);
diff --git a/crates/prompt/src/code_mode.rs b/crates/prompt/src/code_mode.rs
index bb6a53a9b9..b266585c52 100644
--- a/crates/prompt/src/code_mode.rs
+++ b/crates/prompt/src/code_mode.rs
@@ -9,7 +9,7 @@ static INSTRUCTIONS: &str = r##"- Prefer `ExecuteCode` for Macro work, including
- Discover before writing: entity indexes in context list each method's signature. Read the symbols a program uses with `ReadCodeDocs`, all in one call, unless their reference is already in context, and call `DescribeCodeTools` only for an entity index not in context. Do not guess methods or options.
- Do one job in one program. Put conditions, loops and dependent reads and writes inside it instead of checking in one execution and acting in the next, and run independent work in parallel.
- Return compact evidence: the ids and `webUrl()` of what you found or changed, outcomes, failures and coverage limits, not SDK objects or raw batches.
-- Never sleep, set timers or poll to wait for something. To check back later, create a routine with `macro.routines.create` that says what to check and where to report, then end the turn.
+- Never sleep, set timers or poll to wait for something. To check back later, create a routine with a once trigger due shortly (`macro.routines.create({ trigger: { type: 'once', at }, ... })`) that says what to check and where to report, then end the turn; it runs within about a second of `at`.
- When a turn made, changed or sent something the user will want to open, or the answer is a set of workspace items, present them with `execution.views.present` without being asked, and keep your reply to a one-line lead-in.
"##;
diff --git a/crates/scheduled_action/AGENTS.md b/crates/scheduled_action/AGENTS.md
index d90cb612ad..565f82346e 100644
--- a/crates/scheduled_action/AGENTS.md
+++ b/crates/scheduled_action/AGENTS.md
@@ -103,6 +103,16 @@ that listener is ready. Cancellation can stop the gate before startup finishes.
(both reject unknown fields, and older clients omit it), plus every query in
`pg_scheduled_action_repo.rs` and the event-run claim in `pg_event_run_repo.rs`,
which builds its own `ScheduledAction`.
+- A `once` trigger (stored as `trigger_type = 'once'`, or inside `multiple`)
+ runs a single time at `at`, kept to whole seconds. A past `at` is due as soon
+ as it is saved, unless the stored routine already consumed it (its
+ `next_run_at` moved past `at`), so edits and re-enabling never re-run it.
+ After the run `next_run_at` is NULL and the routine stays, shown as completed.
+- `PgPollingDispatcher` polls every 30 seconds but wakes earlier for the first
+ not-yet-due row a poll saw and for the `next_run_at` of enabled creates and
+ updates sent on its in-process `DispatchEvent` channel. Every harness instance
+ runs a dispatcher beside the API, so the instance that saved a near-term
+ routine runs it within about a second; the claim stays fenced to `next_run_at`.
- Create and update bodies are `ActionConfiguration` and
`ActionConfigurationUpdate`, with `trigger` required; the cron-only body with a
top-level `schedule` is gone. Rejections return serde's message, which names
diff --git a/crates/scheduled_action/src/domain/event_trigger.rs b/crates/scheduled_action/src/domain/event_trigger.rs
index 3dde266781..8804bb8356 100644
--- a/crates/scheduled_action/src/domain/event_trigger.rs
+++ b/crates/scheduled_action/src/domain/event_trigger.rs
@@ -9,7 +9,7 @@
use activity::Actor;
use call::domain::events::CallTopicEvent;
use channels::domain::broker_events::ChannelTopicEvent;
-use chrono::{DateTime, Utc};
+use chrono::{DateTime, SubsecRound, Utc};
use chrono_tz::Tz;
use document_sub_type::DocumentSubType;
use documents::domain::events::DocumentTopicEvent;
@@ -66,6 +66,11 @@ pub enum ActionTrigger {
Events {
filters: EventFilters,
},
+ /// Fires once at `at`, or as soon as it is saved when `at` has passed.
+ Once {
+ #[serde(deserialize_with = "whole_seconds")]
+ at: DateTime<Utc>,
+ },
Multiple {
triggers: RoutineTriggers,
},
@@ -83,6 +88,19 @@ pub enum RoutineTrigger {
Events {
filters: EventFilters,
},
+ /// Fires once at `at`, or as soon as it is saved when `at` has passed.
+ Once {
+ #[serde(deserialize_with = "whole_seconds")]
+ at: DateTime<Utc>,
+ },
+}
+
+/// Once times keep whole seconds: dispatch is precise to about a second, and
+/// clients that edit a routine send its times back at that precision.
+fn whole_seconds<'de, D: serde::Deserializer<'de>>(
+ deserializer: D,
+) -> Result<DateTime<Utc>, D::Error> {
+ Ok(DateTime::<Utc>::deserialize(deserializer)?.trunc_subsecs(0))
}
/// Bounded schedules and one combined set of event filters.
@@ -135,16 +153,33 @@ impl ActionTrigger {
pub fn has_schedule(&self) -> bool {
match self {
- Self::Cron { .. } => true,
+ Self::Cron { .. } | Self::Once { .. } => true,
+ Self::Multiple { triggers } => triggers
+ .0
+ .iter()
+ .any(|t| matches!(t, RoutineTrigger::Cron { .. } | RoutineTrigger::Once { .. })),
+ Self::Events { .. } => false,
+ }
+ }
+
+ /// Every time a once trigger names.
+ pub fn once_times(&self) -> Vec<DateTime<Utc>> {
+ match self {
+ Self::Once { at } => vec![*at],
Self::Multiple { triggers } => triggers
.0
.iter()
- .any(|t| matches!(t, RoutineTrigger::Cron { .. })),
- _ => false,
+ .filter_map(|trigger| match trigger {
+ RoutineTrigger::Once { at } => Some(*at),
+ _ => None,
+ })
+ .collect(),
+ Self::Cron { .. } | Self::Events { .. } => Vec::new(),
}
}
- /// The first upcoming firing across all schedules. Simultaneous firings run once.
+ /// The first upcoming firing across all schedules. Simultaneous firings
+ /// run once. A once trigger counts only while its time is still ahead.
pub fn next_run_after(&self, after: DateTime<Utc>) -> Option<DateTime<Utc>> {
let next = |schedule: &Schedule, timezone: Tz| {
schedule
@@ -153,19 +188,37 @@ impl ActionTrigger {
.next()
.map(|time| time.with_timezone(&Utc))
};
+ let once = |at: DateTime<Utc>| (at > after).then_some(at);
match self {
Self::Cron { schedule, timezone } => next(schedule, *timezone),
+ Self::Once { at } => once(*at),
Self::Multiple { triggers } => triggers
.0
.iter()
.filter_map(|trigger| match trigger {
RoutineTrigger::Cron { schedule, timezone } => next(schedule, *timezone),
+ RoutineTrigger::Once { at } => once(*at),
RoutineTrigger::Events { .. } => None,
})
.min(),
- _ => None,
+ Self::Events { .. } => None,
}
}
+
+ /// The first firing of this trigger as saved at `now`. A once time that
+ /// has already passed is due at once, unless `fired` says it already ran.
+ pub fn first_run_at(
+ &self,
+ now: DateTime<Utc>,
+ fired: impl Fn(DateTime<Utc>) -> bool,
+ ) -> Option<DateTime<Utc>> {
+ let overdue = self
+ .once_times()
+ .into_iter()
+ .filter(|at| *at <= now && !fired(*at))
+ .min();
+ overdue.or_else(|| self.next_run_after(now))
+ }
}
/// Closed allowlist: unknown names, deletions and ambiguous attribution are not
diff --git a/crates/scheduled_action/src/domain/event_trigger/test.rs b/crates/scheduled_action/src/domain/event_trigger/test.rs
index 5874a811a0..528c5f0710 100644
--- a/crates/scheduled_action/src/domain/event_trigger/test.rs
+++ b/crates/scheduled_action/src/domain/event_trigger/test.rs
@@ -797,6 +797,59 @@ fn github_deliveries_normalize_with_their_payload_and_reject_odd_names() {
);
}
+#[test]
+fn once_fires_at_its_time_and_never_after() {
+ let trigger: ActionTrigger =
+ serde_json::from_value(json!({"type": "once", "at": "2040-01-01T10:00:02Z"})).unwrap();
+ assert_eq!(
+ serde_json::to_value(&trigger).unwrap(),
+ json!({"type": "once", "at": "2040-01-01T10:00:02Z"})
+ );
+ let at = "2040-01-01T10:00:02Z".parse::<DateTime<Utc>>().unwrap();
+ let before = "2040-01-01T10:00:00Z".parse::<DateTime<Utc>>().unwrap();
+ let after = "2040-01-01T10:00:03Z".parse::<DateTime<Utc>>().unwrap();
+ assert!(trigger.has_schedule());
+ assert_eq!(trigger.next_run_after(before), Some(at));
+ assert_eq!(trigger.next_run_after(at), None);
+ assert_eq!(trigger.next_run_after(after), None);
+ assert_eq!(trigger.first_run_at(before, |_| false), Some(at));
+ // A time that has already passed when saved is due now, unless it ran.
+ assert_eq!(trigger.first_run_at(after, |_| false), Some(at));
+ assert_eq!(trigger.first_run_at(after, |_| true), None);
+ assert!(
+ serde_json::from_value::<ActionTrigger>(json!({"type": "once", "at": "tomorrow"})).is_err()
+ );
+ assert!(serde_json::from_value::<ActionTrigger>(json!({"type": "once"})).is_err());
+}
+
+#[test]
+fn once_inside_multiple_runs_before_later_schedules_and_then_yields_to_them() {
+ let trigger: ActionTrigger = serde_json::from_value(json!({
+ "type": "multiple",
+ "triggers": [
+ {"type": "cron", "schedule": "0 0 17 * * *", "timezone": "UTC"},
+ {"type": "once", "at": "2040-01-01T10:00:02Z"},
+ {"type": "events", "filters": [{"events": ["document.created"]}]}
+ ]
+ }))
+ .unwrap();
+ let before = "2040-01-01T10:00:00Z".parse::<DateTime<Utc>>().unwrap();
+ let after = "2040-01-01T10:00:03Z".parse::<DateTime<Utc>>().unwrap();
+ assert_eq!(
+ trigger.next_run_after(before).unwrap().to_rfc3339(),
+ "2040-01-01T10:00:02+00:00"
+ );
+ assert_eq!(
+ trigger.next_run_after(after).unwrap().to_rfc3339(),
+ "2040-01-01T17:00:00+00:00"
+ );
+ assert_eq!(
+ trigger.first_run_at(after, |_| false).unwrap().to_rfc3339(),
+ "2040-01-01T10:00:02+00:00"
+ );
+ assert!(trigger.event_filters().is_some());
+}
+
const COMPLETED: &str = "00000001-0000-0000-0002-000000000004";
const IN_PROGRESS: &str = "00000001-0000-0000-0002-000000000002";
diff --git a/crates/scheduled_action/src/domain/service.rs b/crates/scheduled_action/src/domain/service.rs
index 0fca923311..d94e3b8429 100644
--- a/crates/scheduled_action/src/domain/service.rs
+++ b/crates/scheduled_action/src/domain/service.rs
@@ -189,7 +189,7 @@ impl<Rpo: ScheduledActionRepo, Exe, Grants, Targets, Github>
self.check_github(&input.trigger, owner_user).await?;
}
let now = Utc::now();
- let next_run_at = next_run(&input.trigger)?;
+ let next_run_at = next_run(&input.trigger, now, |_| false)?;
let event_activated_at = input.trigger.event_filters().is_some().then_some(now);
let created = self
.repo
@@ -270,7 +270,8 @@ impl<Rpo: ScheduledActionRepo, Exe, Grants, Targets, Github>
.await?;
}
if trigger_changed || (!action.enabled && input.enabled) {
- action.next_run_at = next_run(&input.trigger)?;
+ action.next_run_at =
+ next_run(&input.trigger, now, |at| once_already_fired(&action, at))?;
}
}
action.event_activated_at = if input.trigger.event_filters().is_some() {
@@ -323,8 +324,12 @@ pub(crate) async fn granted_action<R: ScheduledActionRepo, T: RequiredPermission
}
}
-fn next_run(trigger: &ActionTrigger) -> Result<Option<DateTime<Utc>>> {
- let next = trigger.next_run_after(Utc::now());
+fn next_run(
+ trigger: &ActionTrigger,
+ now: DateTime<Utc>,
+ fired: impl Fn(DateTime<Utc>) -> bool,
+) -> Result<Option<DateTime<Utc>>> {
+ let next = trigger.first_run_at(now, fired);
if trigger.has_schedule() && next.is_none() && trigger.event_filters().is_none() {
return Err(ActionPolicyError::NoFutureFirings.into());
}
@@ -357,6 +362,13 @@ where
Ok(actions)
}
+/// Whether the stored routine already ran its once trigger at `at`. Pending
+/// firings never come after `next_run_at`, so a stored once time before it (or
+/// with nothing left to run) has been consumed.
+fn once_already_fired(stored: &ScheduledAction, at: DateTime<Utc>) -> bool {
+ stored.trigger.once_times().contains(&at) && stored.next_run_at.is_none_or(|next| next > at)
+}
+
fn claim_blocks_replacement(action: &ScheduledAction, now: DateTime<Utc>) -> bool {
action
.claim_expires_at()
diff --git a/crates/scheduled_action/src/domain/service/test.rs b/crates/scheduled_action/src/domain/service/test.rs
index b425d79d7c..845f9944d5 100644
--- a/crates/scheduled_action/src/domain/service/test.rs
+++ b/crates/scheduled_action/src/domain/service/test.rs
@@ -1242,6 +1242,43 @@ async fn editing_an_overdue_one_off_keeps_its_unconsumed_firing() {
assert_eq!(updated.next_run_at, None);
}
+#[tokio::test]
+async fn a_past_once_time_is_due_on_save_but_never_rearmed_after_it_ran() {
+ use chrono::SubsecRound;
+ let svc = service(false);
+ let at = (Utc::now() - chrono::Duration::minutes(1)).trunc_subsecs(0);
+ let mut config = configuration(false);
+ config.trigger = ActionTrigger::Once { at };
+ let created = svc
+ .create_action(&user_principal(), config.clone())
+ .await
+ .unwrap();
+ assert_eq!(created.next_run_at, Some(at));
+ let id = created.id.unwrap();
+
+ // The dispatcher ran it: nothing is left to run.
+ svc.repo.actions.lock().unwrap()[0].next_run_at = None;
+ let paused = svc.set_enabled(edit_receipt(id), false).await.unwrap();
+ assert_eq!(paused.next_run_at, None);
+ assert_policy(
+ svc.set_enabled(edit_receipt(id), true).await,
+ ActionPolicyError::NoFutureFirings,
+ );
+
+ // An edit keeps the spent time spent; a newly added past time is due now.
+ let later = (Utc::now() - chrono::Duration::seconds(5)).trunc_subsecs(0);
+ config.trigger = serde_json::from_value(json!({"type": "multiple", "triggers": [
+ {"type": "once", "at": at},
+ {"type": "once", "at": later},
+ ]}))
+ .unwrap();
+ let updated = svc
+ .update_action(edit_receipt(id), update(config))
+ .await
+ .unwrap();
+ assert_eq!(updated.next_run_at, Some(later));
+}
+
fn conditional_configuration() -> ActionConfiguration {
ActionConfiguration {
trigger: serde_json::from_value(json!({
diff --git a/crates/scheduled_action/src/domain/service/test/user_cleanup.rs b/crates/scheduled_action/src/domain/service/test/user_cleanup.rs
index 48d2aae2b4..5fd690896c 100644
--- a/crates/scheduled_action/src/domain/service/test/user_cleanup.rs
+++ b/crates/scheduled_action/src/domain/service/test/user_cleanup.rs
@@ -104,7 +104,7 @@ pub(super) fn action(owner: Owner, events: bool) -> ScheduledAction {
id: Some(macro_uuid::generate_uuid_v7()),
owner,
name: config.name,
- next_run_at: next_run(&config.trigger).unwrap(),
+ next_run_at: next_run(&config.trigger, now, |_| false).unwrap(),
trigger: config.trigger,
kind: config.kind,
created_at: now,
diff --git a/crates/scheduled_action/src/domain/target_runner.rs b/crates/scheduled_action/src/domain/target_runner.rs
index 3eb70f4bea..0e42c1e399 100644
--- a/crates/scheduled_action/src/domain/target_runner.rs
+++ b/crates/scheduled_action/src/domain/target_runner.rs
@@ -12,6 +12,7 @@ use agent_session::domain::{
};
use anyhow::{Context, Result};
use bot_id::BotId;
+use chrono::{DateTime, Utc};
use chrono_tz::Tz;
use macro_user_id::user_id::MacroUserIdStr;
use trigger_context::{
@@ -254,13 +255,16 @@ fn retain_resource(handle: &mut ExecutionHandle) {
fn schedule(trigger: &ActionTrigger) -> String {
let cron =
|schedule: &Schedule, timezone: &Tz| format!("cron `{}` in {timezone}", schedule.as_str());
+ let once = |at: &DateTime<Utc>| format!("once at {}", at.to_rfc3339());
match trigger {
ActionTrigger::Cron { schedule, timezone } => cron(schedule, timezone),
+ ActionTrigger::Once { at } => once(at),
ActionTrigger::Multiple { triggers } => triggers
.as_slice()
.iter()
.filter_map(|trigger| match trigger {
RoutineTrigger::Cron { schedule, timezone } => Some(cron(schedule, timezone)),
+ RoutineTrigger::Once { at } => Some(once(at)),
RoutineTrigger::Events { .. } => None,
})
.collect::<Vec<_>>()
@@ -269,8 +273,8 @@ fn schedule(trigger: &ActionTrigger) -> String {
}
}
-/// The routine's triggers as the agent reads them: one entry per schedule and
-/// per event filter.
+/// The routine's triggers as the agent reads them: one entry per schedule,
+/// once time and event filter.
fn triggers(trigger: &ActionTrigger) -> Vec<ContextTrigger> {
let schedule = |schedule: &Schedule, timezone: &Tz| ContextTrigger::Schedule {
cron: schedule.as_str().to_owned(),
@@ -281,6 +285,7 @@ fn triggers(trigger: &ActionTrigger) -> Vec<ContextTrigger> {
schedule: cron,
timezone,
} => vec![schedule(cron, timezone)],
+ ActionTrigger::Once { at } => vec![ContextTrigger::Once { at: *at }],
ActionTrigger::Multiple { triggers } => triggers
.as_slice()
.iter()
@@ -289,6 +294,7 @@ fn triggers(trigger: &ActionTrigger) -> Vec<ContextTrigger> {
schedule: cron,
timezone,
} => Some(schedule(cron, timezone)),
+ RoutineTrigger::Once { at } => Some(ContextTrigger::Once { at: *at }),
RoutineTrigger::Events { .. } => None,
})
.collect(),
diff --git a/crates/scheduled_action/src/outbound/pg_polling_dispatcher.rs b/crates/scheduled_action/src/outbound/pg_polling_dispatcher.rs
index ac176b40c6..15c574e9aa 100644
--- a/crates/scheduled_action/src/outbound/pg_polling_dispatcher.rs
+++ b/crates/scheduled_action/src/outbound/pg_polling_dispatcher.rs
@@ -1,7 +1,7 @@
use std::sync::Arc;
use std::time::{Duration, Instant};
-use chrono::Utc;
+use chrono::{DateTime, Utc};
use tokio::sync::mpsc::{Receiver, Sender};
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
@@ -26,18 +26,20 @@ const BATCH_MIN_DURATION: Duration = Duration::from_secs(30);
/// A [`ScheduledActionDispatcher`] that polls Postgres for due actions rather
/// than holding an in-memory cron schedule. Safe to run in multiple instances:
/// coordination is done via [`ScheduledActionRepo::claim_action`], which is an
-/// atomic conditional UPDATE. The first instance to claim an action wins; peers
-/// see the stale-or-unclaimed filter exclude it on subsequent polls.
+/// atomic conditional UPDATE fenced to `next_run_at`. The first instance to
+/// claim an action wins; peers see the stale-or-unclaimed filter exclude it on
+/// subsequent polls.
///
/// Polling cadence: each batch of up to [`BATCH_SIZE`] actions is processed,
/// then the loop sleeps until [`BATCH_MIN_DURATION`] has elapsed from the batch
-/// start. This gives other dispatcher instances a chance to pick up work, and
-/// bounds DB load when there is nothing to do.
+/// start, or until an earlier firing comes due. This gives other dispatcher
+/// instances a chance to pick up work, and bounds DB load when there is nothing
+/// to do.
///
-/// [`DispatchEvent`]s on the returned [`Sender`] are drained and dropped —
-/// polling reads state directly from the DB each tick, so create/update/delete
-/// events are redundant. The sender is only accepted to satisfy the trait
-/// contract shared with the in-memory dispatcher.
+/// An earlier firing is the first not-yet-due action the poll returned, or the
+/// `next_run_at` of an enabled action created or updated through the returned
+/// [`Sender`]. Either wakes the loop when it comes due, so a routine due in two
+/// seconds runs in about two seconds rather than at the next batch.
pub struct PgPollingDispatcher<Rpo: ScheduledActionRepo, Exe: ScheduledActionExecutor> {
repo: Arc<Rpo>,
executor: Exe,
@@ -118,21 +120,32 @@ where
} = self;
let cancellation_token = lifecycle.cancellation_token;
- // Drain dispatch events — the polling loop pulls fresh state from the
- // DB each tick, so create/update/delete notifications are not needed.
- // We still must drain so service-side sends don't block on a full
- // channel.
+ // The earliest firing a create or update asked for. The poll loop
+ // clears it when it polls, since that poll reads the saved row.
+ let (wake_tx, mut wake_rx) = tokio::sync::watch::channel(None::<DateTime<Utc>>);
+ let wake_tx = Arc::new(wake_tx);
+ let poll_wake_tx = Arc::clone(&wake_tx);
+
+ // Always drain so service-side sends never block on a full channel.
let drain_cancellation_token = cancellation_token.clone();
lifecycle.task_tracker.spawn(async move {
loop {
- tokio::select! {
+ let event = tokio::select! {
biased;
_ = drain_cancellation_token.cancelled() => break,
- event = rx.recv() => {
- if event.is_none() {
- break;
+ event = rx.recv() => event,
+ };
+ let Some(event) = event else {
+ break;
+ };
+ if let Some(at) = requested_wake(&event) {
+ wake_tx.send_if_modified(|earliest| {
+ let earlier = earliest.is_none_or(|earliest| at < earliest);
+ if earlier {
+ *earliest = Some(at);
}
- }
+ earlier
+ });
}
}
});
@@ -147,12 +160,15 @@ where
}
let batch_start = Instant::now();
+ poll_wake_tx.send_replace(None);
+ wake_rx.mark_unchanged();
let poll_result = tokio::select! {
biased;
_ = cancellation_token.cancelled() => return,
result = repo.get_next_unclaimed_actions(BATCH_SIZE) => result,
};
+ let mut next_due = None;
match poll_result {
Ok(candidates) => {
let now = Utc::now();
@@ -167,6 +183,7 @@ where
// The first non-due one ends the batch — anything
// after it is also not yet due.
if next_run_at > now {
+ next_due = Some(next_run_at);
break;
}
@@ -200,12 +217,19 @@ where
}
}
- let elapsed = batch_start.elapsed();
- if elapsed < BATCH_MIN_DURATION {
+ let batch_end = batch_start + BATCH_MIN_DURATION;
+ loop {
+ let requested = *wake_rx.borrow_and_update();
+ let wake_at = [next_due, requested]
+ .into_iter()
+ .flatten()
+ .map(instant_at)
+ .fold(batch_end, Instant::min);
tokio::select! {
biased;
_ = cancellation_token.cancelled() => return,
- _ = tokio::time::sleep(BATCH_MIN_DURATION - elapsed) => {}
+ _ = tokio::time::sleep_until(wake_at.into()) => break,
+ _ = wake_rx.changed() => {}
}
}
}
@@ -215,6 +239,22 @@ where
}
}
+/// When a saved action next needs the dispatcher, if it is enabled to run.
+fn requested_wake(event: &DispatchEvent) -> Option<DateTime<Utc>> {
+ match event {
+ DispatchEvent::Create(action) | DispatchEvent::Update(action) if action.enabled => {
+ action.next_run_at
+ }
+ DispatchEvent::Create(_) | DispatchEvent::Update(_) | DispatchEvent::Delete(_) => None,
+ }
+}
+
+/// The monotonic instant of a wall-clock time; past times are now.
+fn instant_at(at: DateTime<Utc>) -> Instant {
+ let wait = (at - Utc::now()).to_std().unwrap_or_default();
+ Instant::now() + wait
+}
+
async fn wait_until_ready(
ready: Option<tokio::sync::watch::Receiver<bool>>,
cancellation: &CancellationToken,
diff --git a/crates/scheduled_action/src/outbound/pg_polling_dispatcher/test.rs b/crates/scheduled_action/src/outbound/pg_polling_dispatcher/test.rs
index b55b62e196..90fcd95c28 100644
--- a/crates/scheduled_action/src/outbound/pg_polling_dispatcher/test.rs
+++ b/crates/scheduled_action/src/outbound/pg_polling_dispatcher/test.rs
@@ -24,7 +24,7 @@ use crate::domain::ports::{
};
struct FakeRepository {
- candidates: Vec<ScheduledAction>,
+ candidates: std::sync::Mutex<Vec<ScheduledAction>>,
cancellation_token: Option<CancellationToken>,
poll_started: Semaphore,
}
@@ -32,7 +32,7 @@ struct FakeRepository {
impl FakeRepository {
fn returning(candidates: Vec<ScheduledAction>) -> Self {
Self {
- candidates,
+ candidates: std::sync::Mutex::new(candidates),
cancellation_token: None,
poll_started: Semaphore::new(0),
}
@@ -43,7 +43,7 @@ impl FakeRepository {
cancellation_token: CancellationToken,
) -> Self {
Self {
- candidates,
+ candidates: std::sync::Mutex::new(candidates),
cancellation_token: Some(cancellation_token),
poll_started: Semaphore::new(0),
}
@@ -83,7 +83,7 @@ impl ScheduledActionRepo for FakeRepository {
if let Some(cancellation_token) = &self.cancellation_token {
cancellation_token.cancel();
}
- Ok(self.candidates.clone())
+ Ok(self.candidates.lock().unwrap().clone())
}
async fn update_action(&self, action: ScheduledAction) -> Result<ScheduledAction> {
@@ -340,6 +340,69 @@ async fn only_enabled_due_schedules_including_mixed_triggers_reach_executor() {
assert_eq!(execution_count.load(Ordering::SeqCst), 1);
}
+fn once_action(at: DateTime<Utc>) -> ScheduledAction {
+ let mut action = due_action();
+ action.trigger = ActionTrigger::Once { at };
+ action.next_run_at = Some(at);
+ action
+}
+
+/// Both cases run well inside the 30-second batch the loop would otherwise wait out.
+const NEAR_TERM_DEADLINE: Duration = Duration::from_secs(5);
+
+#[tokio::test]
+async fn a_saved_near_term_routine_wakes_the_idle_loop() {
+ let repository = Arc::new(FakeRepository::returning(Vec::new()));
+ let executor = RecordingExecutor {
+ execution_count: Arc::new(AtomicUsize::new(0)),
+ };
+ let (cancellation_token, tracker, lifecycle) = lifecycle();
+ let dispatcher =
+ PgPollingDispatcher::new(Arc::clone(&repository), executor).with_lifecycle(lifecycle);
+ let (dispatch_tx, mut execution_rx) = dispatcher.begin_dispatch_loop();
+ repository.wait_for_poll().await;
+
+ let action = once_action(Utc::now() + ChronoDuration::milliseconds(200));
+ let id = action.id.unwrap();
+ *repository.candidates.lock().unwrap() = vec![action.clone()];
+ dispatch_tx
+ .send(crate::domain::models::DispatchEvent::Create(action))
+ .await
+ .unwrap();
+
+ let execution = tokio::time::timeout(NEAR_TERM_DEADLINE, execution_rx.recv())
+ .await
+ .expect("the routine should run when due, not at the next batch")
+ .unwrap();
+ assert_eq!(execution.action_id, id);
+ cancellation_token.cancel();
+ tracker.close();
+ wait_for_tracker(&tracker).await;
+}
+
+#[tokio::test]
+async fn a_polled_routine_due_before_the_next_batch_runs_when_due() {
+ let action = once_action(Utc::now() + ChronoDuration::milliseconds(200));
+ let id = action.id.unwrap();
+ let repository = Arc::new(FakeRepository::returning(vec![action]));
+ let execution_count = Arc::new(AtomicUsize::new(0));
+ let executor = RecordingExecutor {
+ execution_count: Arc::clone(&execution_count),
+ };
+ let (cancellation_token, tracker, lifecycle) = lifecycle();
+ let dispatcher = PgPollingDispatcher::new(repository, executor).with_lifecycle(lifecycle);
+ let (_dispatch_tx, mut execution_rx) = dispatcher.begin_dispatch_loop();
+
+ let execution = tokio::time::timeout(NEAR_TERM_DEADLINE, execution_rx.recv())
+ .await
+ .expect("the routine should run when due, not at the next batch")
+ .unwrap();
+ assert_eq!(execution.action_id, id);
+ cancellation_token.cancel();
+ tracker.close();
+ wait_for_tracker(&tracker).await;
+}
+
#[tokio::test]
async fn startup_gate_waits_for_http_and_can_be_cancelled_before_it_listens() {
let (listening, ready) = tokio::sync::watch::channel(false);
diff --git a/crates/scheduled_action/src/outbound/pg_scheduled_action_repo.rs b/crates/scheduled_action/src/outbound/pg_scheduled_action_repo.rs
index 13a44d8694..5b07246ba1 100644
--- a/crates/scheduled_action/src/outbound/pg_scheduled_action_repo.rs
+++ b/crates/scheduled_action/src/outbound/pg_scheduled_action_repo.rs
@@ -97,7 +97,7 @@ impl TryFrom<ActionRow> for ScheduledAction {
row.event_filters.context("event filters missing")?,
)?,
},
- "multiple" => {
+ "multiple" | "once" => {
serde_json::from_value(row.trigger_config.context("routine triggers missing")?)?
}
other => bail!("unknown action trigger: {other}"),
@@ -154,6 +154,13 @@ impl TryFrom<&ActionTrigger> for TriggerColumns {
event_filters: Some(serde_json::to_value(filters)?),
trigger_config: None,
}),
+ ActionTrigger::Once { .. } => Ok(Self {
+ trigger_type: "once",
+ schedule: None,
+ timezone: None,
+ event_filters: None,
+ trigger_config: Some(serde_json::to_value(trigger)?),
+ }),
ActionTrigger::Multiple { .. } => Ok(Self {
trigger_type: "multiple",
schedule: None,
@@ -294,7 +301,7 @@ impl<B: BotFacts + 'static> ScheduledActionRepo for PgScheduledActionRepo<B> {
updated_at, next_run_at, enabled, trigger_type, event_filters,
configuration_revision, event_activated_at, trigger_config, run_visibility, template_id
FROM scheduled_action
- WHERE enabled AND trigger_type IN ('cron', 'multiple') AND next_run_at IS NOT NULL
+ WHERE enabled AND trigger_type IN ('cron', 'once', 'multiple') AND next_run_at IS NOT NULL
AND (claimed IS NULL OR claimed < $1)
ORDER BY next_run_at ASC, id ASC
LIMIT $2
@@ -535,7 +542,7 @@ impl<B: BotFacts + 'static> ScheduledActionRepo for PgScheduledActionRepo<B> {
.fetch_one(&mut *tx)
.await?;
- if row.trigger_type == "cron" || row.trigger_type == "multiple" {
+ if matches!(row.trigger_type.as_str(), "cron" | "once" | "multiple") {
let trigger = if row.trigger_type == "cron" {
ActionTrigger::Cron {
schedule: Schedule::from_cron(row.schedule.context("cron schedule missing")?)?,
@@ -549,7 +556,7 @@ impl<B: BotFacts + 'static> ScheduledActionRepo for PgScheduledActionRepo<B> {
r#"
UPDATE scheduled_action
SET next_run_at = $1, updated_at = now()
- WHERE id = $2 AND trigger_type IN ('cron', 'multiple')
+ WHERE id = $2 AND trigger_type IN ('cron', 'once', 'multiple')
"#,
next_run_at,
*id,
diff --git a/crates/scheduled_action/src/outbound/pg_scheduled_action_repo/test.rs b/crates/scheduled_action/src/outbound/pg_scheduled_action_repo/test.rs
index be9cbcc8b6..f6875f03dc 100644
--- a/crates/scheduled_action/src/outbound/pg_scheduled_action_repo/test.rs
+++ b/crates/scheduled_action/src/outbound/pg_scheduled_action_repo/test.rs
@@ -1,6 +1,6 @@
mod user_cleanup;
-use chrono::Utc;
+use chrono::{SubsecRound, Utc};
use entity_registry::{BotFacts, EntityRegistryResult, OwnerGrantPolicy};
use entity_registry_db_utils::OwnedEntityRegistrar;
use macro_db_migrator::MACRO_DB_MIGRATIONS;
@@ -993,6 +993,101 @@ async fn exhausted_one_off_clears_firing_and_is_not_dispatched_again(pool: PgPoo
);
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn once_routine_fires_for_exactly_one_of_concurrent_claims_and_then_is_done(pool: PgPool) {
+ insert_user(&pool, USER_A).await;
+ let repo = test_repo(pool);
+ let at = (Utc::now() - chrono::Duration::seconds(1)).trunc_subsecs(0);
+ let mut action = sample_action(user_owner(USER_A), "check back");
+ action.trigger = ActionTrigger::Once { at };
+ action.next_run_at = Some(at);
+ let created = repo.create_action(action).await.unwrap();
+ let id = created.id.unwrap();
+ assert_eq!(
+ repo.get_action(&id).await.unwrap().unwrap().trigger,
+ ActionTrigger::Once { at }
+ );
+ let polled = repo.get_next_unclaimed_actions(10).await.unwrap();
+ assert_eq!(polled.len(), 1);
+ assert_eq!(polled[0].next_run_at, Some(at));
+
+ let (first, second) = tokio::join!(
+ repo.claim_action(&id, created.configuration_revision, created.next_run_at),
+ repo.claim_action(&id, created.configuration_revision, created.next_run_at),
+ );
+ let token = match (first, second) {
+ (Ok(token), Err(_)) | (Err(_), Ok(token)) => token,
+ (first, second) => panic!("exactly one claim must win: {first:?} {second:?}"),
+ };
+ repo.update_next_run_at(&id).await.unwrap();
+ repo.release_action(&id, token).await.unwrap();
+
+ assert!(
+ repo.claim_action(&id, created.configuration_revision, created.next_run_at)
+ .await
+ .is_err(),
+ "a worker holding the polled snapshot must not fire it again"
+ );
+ let done = repo.get_action(&id).await.unwrap().unwrap();
+ assert_eq!(done.next_run_at, None);
+ assert!(done.enabled);
+ assert!(
+ repo.get_next_unclaimed_actions(10)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn once_inside_multiple_is_stored_and_other_shapes_are_rejected(pool: PgPool) {
+ insert_user(&pool, USER_A).await;
+ let repo = test_repo(pool.clone());
+ let at = (Utc::now() + chrono::Duration::seconds(2)).trunc_subsecs(0);
+ let mut action = sample_action(user_owner(USER_A), "mixed");
+ action.trigger = serde_json::from_value(json!({"type": "multiple", "triggers": [
+ {"type": "cron", "schedule": DAILY_9AM, "timezone": "UTC"},
+ {"type": "once", "at": at},
+ ]}))
+ .unwrap();
+ action.next_run_at = Some(at);
+ let created = repo.create_action(action.clone()).await.unwrap();
+ assert_eq!(
+ repo.get_action(&created.id.unwrap())
+ .await
+ .unwrap()
+ .unwrap()
+ .trigger,
+ action.trigger
+ );
+
+ for (kind, config) in [
+ ("once", json!({"type": "once"})),
+ (
+ "once",
+ json!({"type": "multiple", "triggers": [{"type": "once", "at": at}]}),
+ ),
+ ] {
+ let error = sqlx::query!(
+ r#"
+ INSERT INTO scheduled_action (id, owner, name, kind, task, trigger_type, trigger_config, next_run_at, enabled)
+ VALUES ($1, $2, 'invalid', 'Agent', '{}', $3, $4, NULL, false)
+ "#,
+ macro_uuid::generate_uuid_v7(),
+ USER_A,
+ kind,
+ config,
+ )
+ .execute(&pool)
+ .await
+ .expect_err("a once row needs its own configuration");
+ assert_eq!(
+ error.as_database_error().unwrap().code().as_deref(),
+ Some("23514")
+ );
+ }
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn multiple_triggers_survive_grant_listing_and_configuration_updates(pool: PgPool) {
insert_user(&pool, USER_A).await;
diff --git a/crates/trigger_context/src/lib.rs b/crates/trigger_context/src/lib.rs
index 04451a5456..94852142d4 100644
--- a/crates/trigger_context/src/lib.rs
+++ b/crates/trigger_context/src/lib.rs
@@ -470,6 +470,11 @@ pub enum RoutineTrigger {
/// The timezone it is read in.
timezone: String,
},
+ /// A single run at an exact time.
+ Once {
+ /// When it runs.
+ at: DateTime<Utc>,
+ },
/// Events it watches.
Events {
/// The event names, such as `email.message_received`.
diff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.md
index f3af162355..02344e0e84 100644
--- a/docs/agent-guide/navigation.md
+++ b/docs/agent-guide/navigation.md
@@ -1126,7 +1126,11 @@ natural date search (**tomorrow 9am**, **in 2 hours**) and an inline calendar wi
time controls. Click **Add trigger** to confirm. Click a saved chip to edit it;
**Done** applies changes and **Cancel** leaves it unchanged. The panel floats over
the composer without moving it. Recurring schedules retain their time zones;
-one-off times use the browser’s local time.
+one-off times use the browser’s local time. A one-off saves a `once` trigger
+(`{type: 'once', at}`, the same one agents create through the SDK to check back
+later), runs within about a second of its time, runs as soon as it is saved when
+the time has passed, and then shows **Completed**; its chip reads **Once at**
+the time.
The event menu groups Macro activity triggers by surface:
diff --git a/packages/lexical-core/tests/agent-trigger-context.test.ts b/packages/lexical-core/tests/agent-trigger-context.test.ts
index 1e578dd830..9a384ede09 100644
--- a/packages/lexical-core/tests/agent-trigger-context.test.ts
+++ b/packages/lexical-core/tests/agent-trigger-context.test.ts
@@ -552,6 +552,37 @@ describe('composeAgentContextPrompt with a trigger', () => {
);
});
+ it('renders a once routine run', () => {
+ const markdown = composeAgentContextPrompt({
+ promptMarkdown: 'Check whether the deploy finished.',
+ trigger: {
+ kind: 'routine',
+ routine_id: 'r-3',
+ name: 'Check back on the deploy',
+ owner: {
+ id: 'macro|[email protected]',
+ name: 'Julia',
+ email: '[email protected]',
+ },
+ instructions: 'Report the deploy status in the thread.',
+ triggers: [{ type: 'once', at: '2026-10-08T09:00:02Z' }],
+ firing: {
+ type: 'scheduled',
+ scheduled_for: '2026-10-08T09:00:02Z',
+ schedule: 'once at 2026-10-08T09:00:02Z',
+ },
+ },
+ });
+
+ expect(hiddenContext(markdown)).toContain(
+ [
+ ' <triggers>',
+ ' <once at="2026-10-08T09:00:02Z"/>',
+ ' </triggers>',
+ ].join('\n')
+ );
+ });
+
it('renders a routine fired by a task status change, with the change and the condition', () => {
const markdown = composeAgentContextPrompt({
promptMarkdown: 'Escalate the blocker.',
diff --git a/packages/lexical-core/utils/agent-context.ts b/packages/lexical-core/utils/agent-context.ts
index f2e6e333dc..c6e6b828fd 100644
--- a/packages/lexical-core/utils/agent-context.ts
+++ b/packages/lexical-core/utils/agent-context.ts
@@ -203,6 +203,7 @@ export type RoutineContext = {
/** One of the ways a routine runs. */
export type RoutineTrigger =
| { type: 'schedule'; cron: string; timezone: string }
+ | { type: 'once'; at: string }
| {
type: 'events';
events: string[];
@@ -1468,6 +1469,7 @@ function routineTriggerNode(trigger: RoutineTrigger): FxpNode {
.with({ type: 'schedule' }, ({ cron, timezone }) =>
el('schedule', [], { cron, timezone })
)
+ .with({ type: 'once' }, ({ at }) => el('once', [], { at }))
.with(
{ type: 'events' },
({ events, entity_ids, github, payload_match, condition }) =>
diff --git a/packages/sdk/generated/scheduled-action/types.gen.ts b/packages/sdk/generated/scheduled-action/types.gen.ts
index 3d08f19e54..3804584bd5 100644
--- a/packages/sdk/generated/scheduled-action/types.gen.ts
+++ b/packages/sdk/generated/scheduled-action/types.gen.ts
@@ -72,6 +72,9 @@ export type ActionTrigger = {
} | {
filters: EventFilters;
type: 'events';
+} | {
+ at: string;
+ type: 'once';
} | {
triggers: RoutineTriggers;
type: 'multiple';
@@ -338,6 +341,9 @@ export type RoutineTrigger = {
} | {
filters: EventFilters;
type: 'events';
+} | {
+ at: string;
+ type: 'once';
};
/**
diff --git a/packages/sdk/specs/scheduled-action.json b/packages/sdk/specs/scheduled-action.json
index b04a46fa95..fc827002a0 100644
--- a/packages/sdk/specs/scheduled-action.json
+++ b/packages/sdk/specs/scheduled-action.json
@@ -1021,6 +1021,21 @@
}
}
},
+ {
+ "type": "object",
+ "description": "Fires once at `at`, or as soon as it is saved when `at` has passed.",
+ "required": ["at", "type"],
+ "properties": {
+ "at": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "type": {
+ "type": "string",
+ "enum": ["once"]
+ }
+ }
+ },
{
"type": "object",
"required": ["triggers", "type"],
@@ -1540,6 +1555,21 @@
"enum": ["events"]
}
}
+ },
+ {
+ "type": "object",
+ "description": "Fires once at `at`, or as soon as it is saved when `at` has passed.",
+ "required": ["at", "type"],
+ "properties": {
+ "at": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "type": {
+ "type": "string",
+ "enum": ["once"]
+ }
+ }
}
],
"description": "An individual trigger in a routine's trigger list."
diff --git a/packages/sdk/src/entities/routines/routine.ts b/packages/sdk/src/entities/routines/routine.ts
index ad74d3fb62..072be73321 100644
--- a/packages/sdk/src/entities/routines/routine.ts
+++ b/packages/sdk/src/entities/routines/routine.ts
@@ -27,9 +27,15 @@ export type RoutineEventFilter = Omit<EventFilter, 'ids' | 'condition'> & {
condition?: string;
};
-/** One schedule or set of event selectors. */
+/**
+ * One schedule, one exact time, or one set of event selectors. A `once`
+ * trigger runs a single time at `at` (RFC 3339), within about a second; a time
+ * already past runs as soon as the routine is saved. Use it to check back on
+ * something later instead of waiting inside a program.
+ */
export type SingleRoutineTrigger =
| Extract<RoutineTrigger, { type: 'cron' }>
+ | Extract<RoutineTrigger, { type: 'once' }>
| { type: 'events'; filters: RoutineEventFilter[] };
/** One or multiple routine triggers. */
@@ -40,6 +46,7 @@ export type RoutineTriggerOptions =
function singleTriggerBody(trigger: SingleRoutineTrigger): RoutineTrigger {
return match(trigger)
.with({ type: 'cron' }, (value) => value)
+ .with({ type: 'once' }, (value) => value)
.with({ type: 'events' }, (value) => ({
type: 'events' as const,
filters: value.filters.map(({ entities, ...filter }) => ({
@@ -57,6 +64,7 @@ function triggerBody(trigger: RoutineTriggerOptions): ActionTrigger {
triggers: value.triggers.map(singleTriggerBody),
}))
.with({ type: 'cron' }, singleTriggerBody)
+ .with({ type: 'once' }, singleTriggerBody)
.with({ type: 'events' }, singleTriggerBody)
.exhaustive();
}
diff --git a/services/agent_harness_service/src/public_mcp/code_mode_instructions.md b/services/agent_harness_service/src/public_mcp/code_mode_instructions.md
index 5b5e1bbd28..52b5b825f7 100644
--- a/services/agent_harness_service/src/public_mcp/code_mode_instructions.md
+++ b/services/agent_harness_service/src/public_mcp/code_mode_instructions.md
@@ -1 +1 @@
-Code mode is on. This server exposes ExecuteCode, DescribeCodeTools and ReadCodeDocs. ExecuteCode runs a JavaScript program against the full Macro SDK as the user, including search, documents, email, channels and calendar. Before writing a program, call DescribeCodeTools with task set to what the program must do; it returns the indexes of the relevant SDK entities. Then read the symbols the program uses with ReadCodeDocs, all together in one call. Do not guess SDK methods or options. If a program fails with an SDK error, read the symbol involved and fix the program. Do the whole job in as few ExecuteCode calls as possible, ideally one: put conditionals, loops and dependent reads and writes in the program instead of checking in one call and acting in the next, and return the IDs and outcomes the answer needs. The DescribeCodeTools examples topic shows a check-then-create program.
+Code mode is on. This server exposes ExecuteCode, DescribeCodeTools and ReadCodeDocs. ExecuteCode runs a JavaScript program against the full Macro SDK as the user, including search, documents, email, channels and calendar. Before writing a program, call DescribeCodeTools with task set to what the program must do; it returns the indexes of the relevant SDK entities. Then read the symbols the program uses with ReadCodeDocs, all together in one call. Do not guess SDK methods or options. If a program fails with an SDK error, read the symbol involved and fix the program. Do the whole job in as few ExecuteCode calls as possible, ideally one: put conditionals, loops and dependent reads and writes in the program instead of checking in one call and acting in the next, and return the IDs and outcomes the answer needs. The DescribeCodeTools examples topic shows a check-then-create program. Never sleep, call setTimeout or poll inside ExecuteCode to wait for something. To check back later, create a routine with a once trigger due shortly, macro.routines.create({trigger: {type: "once", at}, ...}), whose prompt says what to check and where to report, then finish; it runs within about a second of at.
diff --git a/services/lexical-service/src/endpoints/agent-context.test.ts b/services/lexical-service/src/endpoints/agent-context.test.ts
index 9c22589194..0d17f11bb0 100644
--- a/services/lexical-service/src/endpoints/agent-context.test.ts
+++ b/services/lexical-service/src/endpoints/agent-context.test.ts
@@ -52,6 +52,28 @@ describe('agent context', () => {
expect(markdown).toContain('your private conversation with the user');
});
+ it('composes a run of a routine that fires once', async () => {
+ const response = await request({
+ promptMarkdown: 'Check whether the deploy finished.',
+ trigger: {
+ kind: 'routine',
+ routine_id: 'r-1',
+ name: 'Check back on the deploy',
+ owner: { id: 'macro|[email protected]', name: 'Ada' },
+ instructions: 'Report the deploy status in the thread.',
+ triggers: [{ type: 'once', at: '2026-10-08T09:00:02Z' }],
+ firing: {
+ type: 'scheduled',
+ scheduled_for: '2026-10-08T09:00:02Z',
+ schedule: 'once at 2026-10-08T09:00:02+00:00',
+ },
+ },
+ });
+ expect(response.status).toBe(200);
+ const { markdown }: { markdown: string } = await response.json();
+ expect(markdown).toContain(`once at=\\"2026-10-08T09:00:02Z\\"`);
+ });
+
it('states the current time the harness sends', async () => {
const response = await request({
promptMarkdown: 'what is due today?',
diff --git a/services/lexical-service/src/endpoints/agent-context.ts b/services/lexical-service/src/endpoints/agent-context.ts
index 9c972d622f..ff8d524123 100644
--- a/services/lexical-service/src/endpoints/agent-context.ts
+++ b/services/lexical-service/src/endpoints/agent-context.ts
@@ -346,6 +346,10 @@ const routineTrigger = z.discriminatedUnion('type', [
cron: z.string().min(1),
timezone: z.string().min(1),
}),
+ z.object({
+ type: z.literal('once'),
+ at: z.string().min(1),
+ }),
z.object({
type: z.literal('events'),
events: z.array(z.string().min(1)),
diff --git a/static_assets/schema.graphql b/static_assets/schema.graphql
index afb3154ab4..09f5e81c97 100644
--- a/static_assets/schema.graphql
+++ b/static_assets/schema.graphql
@@ -7520,11 +7520,29 @@ type GraphqlScheduledActionMultipleTrigger {
"""
schedules: [GraphqlScheduledActionCronTrigger!]!
"""
+ Single runs at exact times.
+ """
+ once: [GraphqlScheduledActionOnceTrigger!]!
+ """
Events that can also trigger this routine.
"""
events: GraphqlScheduledActionEventsTrigger
}
+"""
+A routine that runs a single time.
+"""
+type GraphqlScheduledActionOnceTrigger {
+ """
+ When the routine runs, as RFC 3339.
+ """
+ at: String!
+ """
+ Whether that run is still ahead. False once it has run.
+ """
+ pending: Boolean!
+}
+
"""
A task property a filter watches.
"""
@@ -7542,7 +7560,7 @@ type GraphqlScheduledActionPropertySelector {
"""
The way a routine starts.
"""
-union GraphqlScheduledActionTrigger = GraphqlScheduledActionCronTrigger | GraphqlScheduledActionEventsTrigger | GraphqlScheduledActionMultipleTrigger
+union GraphqlScheduledActionTrigger = GraphqlScheduledActionCronTrigger | GraphqlScheduledActionEventsTrigger | GraphqlScheduledActionOnceTrigger | GraphqlScheduledActionMultipleTrigger
"""
The persisted state of a scheduled delivery.