From b99ebfb3d55ce17dde4ac8ec31e7808a5b292611 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Wed, 28 Oct 2026 15:43:15 +0000 Subject: [PATCH] Add all-runs-complete job trigger --- packages/api-client/src/schema.d.ts | 95 ++++++ .../api/migrations/0023_job_idle_trigger.sql | 4 + packages/api/src/flow-schemas.ts | 1 + packages/api/src/job-contracts.ts | 1 + packages/api/src/job-domain.ts | 4 +- .../api/src/postgres/automation-scheduler.ts | 29 +- packages/api/src/postgres/schema.ts | 4 +- packages/api/src/trigger-context.ts | 5 + packages/api/test/job-edited.test.ts | 6 + .../api/test/job-lifecycle.postgres.test.ts | 38 ++- .../app/src/features/jobs/editor-state.ts | 1 + .../app/src/features/jobs/trigger-editor.tsx | 4 +- packages/docs/openapi.yaml | 280 ++++++++++++++++++ 13 files changed, 464 insertions(+), 8 deletions(-) create mode 100644 packages/api/migrations/0023_job_idle_trigger.sql diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index e0210b1b..cc74eb6b 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -1993,6 +1993,16 @@ export interface components { sourceJobIds: string[]; states: ("succeeded" | "failed" | "stopped" | "edited")[]; }; + } | { + id?: string; + slug?: string; + /** @constant */ + kind: "jobIdle"; + /** @default true */ + enabled: boolean; + config: { + sourceJobIds: string[]; + }; })[]; skillIds?: string[]; }; @@ -4729,6 +4739,21 @@ export interface operations { jobId: string; createdAt: string; updatedAt: string; + } | { + /** Format: uuid */ + id: string; + slug: string; + /** @constant */ + kind: "jobIdle"; + /** @default true */ + enabled: boolean; + config: { + sourceJobIds: string[]; + }; + /** Format: uuid */ + jobId: string; + createdAt: string; + updatedAt: string; })[]; skills?: { /** Format: uuid */ @@ -4904,6 +4929,21 @@ export interface operations { jobId: string; createdAt: string; updatedAt: string; + } | { + /** Format: uuid */ + id: string; + slug: string; + /** @constant */ + kind: "jobIdle"; + /** @default true */ + enabled: boolean; + config: { + sourceJobIds: string[]; + }; + /** Format: uuid */ + jobId: string; + createdAt: string; + updatedAt: string; })[]; skills?: { /** Format: uuid */ @@ -5082,6 +5122,21 @@ export interface operations { jobId: string; createdAt: string; updatedAt: string; + } | { + /** Format: uuid */ + id: string; + slug: string; + /** @constant */ + kind: "jobIdle"; + /** @default true */ + enabled: boolean; + config: { + sourceJobIds: string[]; + }; + /** Format: uuid */ + jobId: string; + createdAt: string; + updatedAt: string; })[]; skills?: { /** Format: uuid */ @@ -5432,6 +5487,21 @@ export interface operations { jobId: string; createdAt: string; updatedAt: string; + } | { + /** Format: uuid */ + id: string; + slug: string; + /** @constant */ + kind: "jobIdle"; + /** @default true */ + enabled: boolean; + config: { + sourceJobIds: string[]; + }; + /** Format: uuid */ + jobId: string; + createdAt: string; + updatedAt: string; })[]; skills?: { /** Format: uuid */ @@ -5565,6 +5635,16 @@ export interface operations { sourceJobIds: string[]; states: ("succeeded" | "failed" | "stopped" | "edited")[]; }; + } | { + id?: string; + slug?: string; + /** @constant */ + kind: "jobIdle"; + /** @default true */ + enabled?: boolean; + config: { + sourceJobIds: string[]; + }; })[]; skillIds?: string[]; /** Format: date-time */ @@ -5715,6 +5795,21 @@ export interface operations { jobId: string; createdAt: string; updatedAt: string; + } | { + /** Format: uuid */ + id: string; + slug: string; + /** @constant */ + kind: "jobIdle"; + /** @default true */ + enabled: boolean; + config: { + sourceJobIds: string[]; + }; + /** Format: uuid */ + jobId: string; + createdAt: string; + updatedAt: string; })[]; skills?: { /** Format: uuid */ diff --git a/packages/api/migrations/0023_job_idle_trigger.sql b/packages/api/migrations/0023_job_idle_trigger.sql new file mode 100644 index 00000000..2720b32d --- /dev/null +++ b/packages/api/migrations/0023_job_idle_trigger.sql @@ -0,0 +1,4 @@ +ALTER TABLE app.triggers DROP CONSTRAINT triggers_kind_check; +ALTER TABLE app.triggers ADD CONSTRAINT triggers_kind_check CHECK (kind IN ('manual','schedule','webhook','jobLifecycle','jobIdle')); +ALTER TABLE app.invocations DROP CONSTRAINT invocations_source_check; +ALTER TABLE app.invocations ADD CONSTRAINT invocations_source_check CHECK (source IN ('manual','schedule','webhook','jobLifecycle','jobIdle')); diff --git a/packages/api/src/flow-schemas.ts b/packages/api/src/flow-schemas.ts index da8fffd3..a0cf91f9 100644 --- a/packages/api/src/flow-schemas.ts +++ b/packages/api/src/flow-schemas.ts @@ -32,6 +32,7 @@ export const triggerSchema = z.discriminatedUnion("kind", [ z.object({ id: z.string().min(1).optional(), slug: z.string().regex(/^trigger-[1-9][0-9]*$/).optional(), kind: z.literal("jobLifecycle"), enabled: z.boolean().default(true), config: z.object({ sourceJobIds: z.array(z.string().min(1)).min(1), states: z.array(z.enum(["succeeded", "failed", "stopped", "edited"])).min(1), }).strict() }).strict(), + z.object({ id: z.string().min(1).optional(), slug: z.string().regex(/^trigger-[1-9][0-9]*$/).optional(), kind: z.literal("jobIdle"), enabled: z.boolean().default(true), config: z.object({ sourceJobIds: z.array(z.string().min(1)).min(1) }).strict() }).strict(), ]); export const jobInputSchema = z.object({ projectId: z.guid().optional(), diff --git a/packages/api/src/job-contracts.ts b/packages/api/src/job-contracts.ts index c576c2d8..18588414 100644 --- a/packages/api/src/job-contracts.ts +++ b/packages/api/src/job-contracts.ts @@ -31,6 +31,7 @@ export const triggerResponse = z.discriminatedUnion("kind", [ triggerSchema.options[1].extend(triggerIdentity), triggerSchema.options[2].extend({ ...triggerIdentity, config: webhookResponse }), triggerSchema.options[3].extend(triggerIdentity), + triggerSchema.options[4].extend(triggerIdentity), ]); export const jobResponse = z.object({ id: z.guid(), projectId: z.guid().optional(), name: z.string(), slug: z.string(), enabled: z.boolean(), diff --git a/packages/api/src/job-domain.ts b/packages/api/src/job-domain.ts index ecc53220..1826e4ba 100644 --- a/packages/api/src/job-domain.ts +++ b/packages/api/src/job-domain.ts @@ -1,7 +1,7 @@ import Mustache from "mustache"; import { renderTextTemplate } from "./text-template"; -export type TriggerKind = "manual" | "schedule" | "webhook" | "jobLifecycle"; +export type TriggerKind = "manual" | "schedule" | "webhook" | "jobLifecycle" | "jobIdle"; export type InvocationSource = "manual" | TriggerKind; export type JobRunState = "queued" | "reserved" | "running" | "succeeded" | "failed" | "stopped"; @@ -129,7 +129,7 @@ export class InvocationService { async invoke(jobId: string, input: InvocationRequest): Promise { if (!input.claimKey?.trim()) throw new InvocationError("invalid_invocation", "An invocation claim key is required."); - if (!(["manual", "schedule", "webhook", "jobLifecycle"] as const).includes(input.source)) throw new InvocationError("invalid_invocation", "Invocation source is invalid."); + if (!(["manual", "schedule", "webhook", "jobLifecycle", "jobIdle"] as const).includes(input.source)) throw new InvocationError("invalid_invocation", "Invocation source is invalid."); const job = await this.repository.getJob(jobId); if (!job) throw new InvocationError("job_not_found", "Job not found."); if (!job.enabled) throw new InvocationError("job_disabled", "Job is disabled."); diff --git a/packages/api/src/postgres/automation-scheduler.ts b/packages/api/src/postgres/automation-scheduler.ts index f53f89cb..df07b5b5 100644 --- a/packages/api/src/postgres/automation-scheduler.ts +++ b/packages/api/src/postgres/automation-scheduler.ts @@ -15,7 +15,7 @@ function skipFullQueue(error: unknown): void { /** Claims durable automatic signals in PostgreSQL. The alarm DO is only its clock. */ export class AutomationScheduler { constructor(private database: Database, private env: Env) {} - async process(): Promise { await this.githubVerifications(); await this.schedules(); await this.jobEdits(); await this.lifecycle(); } + async process(): Promise { await this.githubVerifications(); await this.schedules(); await this.jobEdits(); await this.lifecycle(); await this.jobIdle(); } private repository(tenantId: string) { return new PostgresJobRepository(this.database, tenantId, value => encrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY), value => decrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY)); } private async schedules() { for (let count = 0; count < 50; count++) { @@ -73,6 +73,33 @@ export class AutomationScheduler { } } + private async jobIdle() { + const rows = await this.database.pool.query(`SELECT t.tenant_id,t.id trigger_id,t.job_id,t.slug,r.id source_run_id,r.job_id source_job_id,r.updated_at + FROM app.triggers t JOIN app.jobs j ON j.tenant_id=t.tenant_id AND j.id=t.job_id + CROSS JOIN LATERAL jsonb_array_elements_text(t.config->'sourceJobIds') source_job(value) + JOIN LATERAL (SELECT id,job_id,updated_at FROM app.runs WHERE tenant_id=t.tenant_id AND job_id=source_job.value::uuid AND state IN ('succeeded','failed','stopped') ORDER BY updated_at DESC,id DESC LIMIT 1) r ON true + WHERE t.kind='jobIdle' AND t.enabled AND t.removed_at IS NULL AND j.enabled + AND r.updated_at > t.updated_at + AND NOT EXISTS ( + SELECT 1 FROM jsonb_array_elements_text(t.config->'sourceJobIds') watched(value) + JOIN app.runs active ON active.tenant_id=t.tenant_id AND active.job_id=watched.value::uuid + WHERE active.state IN ('queued','reserved','starting','running','blocked','stopping') + ) + AND NOT EXISTS ( + SELECT 1 FROM jsonb_array_elements_text(t.config->'sourceJobIds') watched(value) + JOIN app.runs newer ON newer.tenant_id=t.tenant_id AND newer.job_id=watched.value::uuid + WHERE newer.state IN ('succeeded','failed','stopped') + AND (newer.updated_at,newer.id) > (r.updated_at,r.id) + ) + AND NOT EXISTS (SELECT 1 FROM app.lifecycle_deliveries d WHERE d.tenant_id=t.tenant_id AND d.trigger_id=t.id AND d.source_run_id=r.id AND d.terminal_state='runsZero') + ORDER BY r.updated_at LIMIT 100`); + for (const row of rows.rows) { + const completedAt = row.updated_at.toISOString(), context = { source_job_id: row.source_job_id, event: "runsZero", completed_at: completedAt }; + await new InvocationService(this.repository(row.tenant_id), value => encrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY)).invoke(row.job_id, { source: "jobIdle", triggerId: row.trigger_id, claimKey: `job-idle:${row.trigger_id}:${row.source_run_id}`, context: { [row.slug]: context }, occurrence: { occurredAt: completedAt, externalId: row.source_run_id, metadata: context } }).catch(skipFullQueue); + await this.database.pool.query("INSERT INTO app.lifecycle_deliveries(tenant_id,trigger_id,source_run_id,terminal_state) VALUES ($1,$2,$3,'runsZero') ON CONFLICT DO NOTHING", [row.tenant_id, row.trigger_id, row.source_run_id]); + } + } + private async githubVerifications() { const pending = await this.database.pool.query(`SELECT p.*,t.slug trigger_slug,t.config trigger_config,t.enabled trigger_enabled,t.removed_at,j.enabled job_enabled,g.state installation_state FROM app.pending_verifications p JOIN app.triggers t ON t.tenant_id=p.tenant_id AND t.id=p.trigger_id JOIN app.jobs j ON j.tenant_id=p.tenant_id AND j.id=p.job_id LEFT JOIN app.github_installations g ON g.tenant_id=p.tenant_id AND g.installation_id=p.installation_id WHERE p.next_attempt_at<=now() ORDER BY p.next_attempt_at LIMIT 20`); for (const row of pending.rows) { diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index 840993e9..c7174ae6 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -54,14 +54,14 @@ export const skills = app.table("skills", { export const jobSkills = app.table("job_skills", { tenantId: uuid("tenant_id").notNull(), jobId: uuid("job_id").notNull(), skillId: uuid("skill_id").notNull(), position: integer("position").notNull() }, t => [primaryKey({ columns: [t.tenantId, t.jobId, t.skillId] }), unique().on(t.tenantId, t.jobId, t.position), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.skillId], foreignColumns: [skills.tenantId, skills.id] }).onDelete("restrict")]); export const triggers = app.table("triggers", { tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), jobId: uuid("job_id").notNull(), kind: text("kind").$type().notNull(), slug: text("slug").notNull(), enabled: boolean("enabled").notNull().default(true), config: jsonb("config").$type>().notNull().default({}), position: integer("position").notNull().default(0), createdAt: createdAt(), updatedAt: updatedAt(), removedAt: timestamp("removed_at", { withTimezone: true }), -}, t => [primaryKey({ columns: [t.tenantId, t.id] }), uniqueIndex("triggers_active_slug").on(t.tenantId, t.jobId, t.slug).where(sql`${t.removedAt} is null`), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), check("no_webhook_handler_code", sql`NOT (${t.config} ? 'handlerCode')`), check("triggers_kind_check", sql`${t.kind} in ('manual','schedule','webhook','jobLifecycle')`)]); +}, t => [primaryKey({ columns: [t.tenantId, t.id] }), uniqueIndex("triggers_active_slug").on(t.tenantId, t.jobId, t.slug).where(sql`${t.removedAt} is null`), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), check("no_webhook_handler_code", sql`NOT (${t.config} ? 'handlerCode')`), check("triggers_kind_check", sql`${t.kind} in ('manual','schedule','webhook','jobLifecycle','jobIdle')`)]); // One-time cutover state; no legacy execution or configuration is retained. export const webhookConditionsCutover = app.table("webhook_conditions_cutover", { tenantId: uuid("tenant_id").notNull(), triggerId: uuid("trigger_id").notNull(), wasEnabled: boolean("was_enabled").notNull(), conditions: jsonb("conditions").$type>().notNull(), restoredAt: timestamp("restored_at", { withTimezone: true }), }, t => [primaryKey({ columns: [t.tenantId, t.triggerId] }), foreignKey({ columns: [t.tenantId, t.triggerId], foreignColumns: [triggers.tenantId, triggers.id] }).onDelete("cascade")]); export const invocations = app.table("invocations", { tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), jobId: uuid("job_id").notNull(), source: text("source").$type().notNull(), claimKey: text("claim_key").notNull(), triggerId: uuid("trigger_id").notNull(), context: jsonb("context").$type>().notNull(), occurrence: jsonb("occurrence").$type(), createdAt: createdAt(), -}, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.jobId, t.claimKey), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.triggerId], foreignColumns: [triggers.tenantId, triggers.id] }), check("invocations_source_check", sql`${t.source} in ('manual','schedule','webhook','jobLifecycle')`)]); +}, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.jobId, t.claimKey), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.triggerId], foreignColumns: [triggers.tenantId, triggers.id] }), check("invocations_source_check", sql`${t.source} in ('manual','schedule','webhook','jobLifecycle','jobIdle')`)]); export const jobRuns = app.table("job_runs", { tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), jobId: uuid("job_id").notNull(), invocationId: uuid("invocation_id").notNull(), state: text("state").$type<"queued" | "reserved" | "starting" | "running" | "blocked" | "stopping" | "succeeded" | "failed" | "stopped">().notNull(), encryptedPrompt: text("encrypted_prompt").notNull(), runName: text("run_name").notNull().default(""), launchLeaseExpiresAt: timestamp("launch_lease_expires_at", { withTimezone: true }), nextPollAt: timestamp("next_poll_at", { withTimezone: true }), createdAt: createdAt(), updatedAt: updatedAt(), startedAt: timestamp("started_at", { withTimezone: true }), }, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.invocationId), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.invocationId], foreignColumns: [invocations.tenantId, invocations.id] }).onDelete("cascade"), index("job_runs_queue").on(t.state, t.createdAt).where(sql`${t.state}='queued'`), index("job_runs_poll_due").on(t.nextPollAt).where(sql`${t.state} in ('running','blocked','stopping')`), index("job_runs_launch_lease").on(t.launchLeaseExpiresAt).where(sql`${t.state}='starting'`)]); diff --git a/packages/api/src/trigger-context.ts b/packages/api/src/trigger-context.ts index 515aecd6..89d8600f 100644 --- a/packages/api/src/trigger-context.ts +++ b/packages/api/src/trigger-context.ts @@ -59,6 +59,11 @@ export const triggerContextCatalog: Record = { { path: "logs", type: "array", description: "Sanitized console log records." }, { path: "exceptions", type: "array", description: "Sanitized exception records." }, ], + jobIdle: [ + { path: "source_job_id", type: "string", description: "Job whose runs have all completed." }, + { path: "event", type: "string", description: "Event name: runsZero." }, + { path: "completed_at", type: "string", description: "Completion timestamp of the last run (ISO 8601)." }, + ], jobLifecycle: [ { path: "event", type: "string", description: "Event name: edited for a job edit." }, { path: "edited_at", type: "string", description: "Job save timestamp for an edited event (ISO 8601)." }, diff --git a/packages/api/test/job-edited.test.ts b/packages/api/test/job-edited.test.ts index d04a7cb5..173c06bd 100644 --- a/packages/api/test/job-edited.test.ts +++ b/packages/api/test/job-edited.test.ts @@ -12,6 +12,12 @@ it("accepts edited alongside terminal events and rejects unknown lifecycle event expect(triggerSchema.safeParse({ ...trigger, config: { ...trigger.config, states: ["unknown"] } }).success).toBe(false); }); +it("accepts an all-runs-complete trigger with one or more source jobs", () => { + const trigger = { kind: "jobIdle", config: { sourceJobIds: ["source"] } }; + expect(triggerSchema.parse(trigger).config).toEqual(trigger.config); + expect(triggerSchema.safeParse({ ...trigger, config: { sourceJobIds: [] } }).success).toBe(false); +}); + // Use a dedicated migrated database; never a shared application database. describe.skipIf(!process.env.TEST_DATABASE_URL)("job edit delivery (PostgreSQL)", () => { const database = new Database({ connectionString: process.env.TEST_DATABASE_URL }); diff --git a/packages/api/test/job-lifecycle.postgres.test.ts b/packages/api/test/job-lifecycle.postgres.test.ts index d793ae3e..c98cfde2 100644 --- a/packages/api/test/job-lifecycle.postgres.test.ts +++ b/packages/api/test/job-lifecycle.postgres.test.ts @@ -26,14 +26,15 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("job lifecycle delivery (Po const tenants: string[] = []; const repository = (tenantId: string) => new PostgresJobRepository(database, tenantId, value => encrypt(value, key), value => decrypt(value, key)); const deliver = () => (new AutomationScheduler(database, { CREDENTIAL_ENCRYPTION_KEY: key } as any) as any).lifecycle(); + const deliverIdle = () => (new AutomationScheduler(database, { CREDENTIAL_ENCRYPTION_KEY: key } as any) as any).jobIdle(); async function tenant() { const id = crypto.randomUUID(); tenants.push(id); await database.pool.query("INSERT INTO app.tenants(id) VALUES ($1)", [id]); return id; } - async function job(tenantId: string, config?: Record, enabled = true) { + async function job(tenantId: string, config?: Record, enabled = true, kind: Trigger["kind"] = "jobLifecycle") { const id = crypto.randomUUID(), timestamp = new Date().toISOString(); - const trigger: Trigger = { id: crypto.randomUUID(), jobId: id, kind: config ? "jobLifecycle" : "manual", slug: "trigger-1", enabled, config: config ?? {}, createdAt: timestamp, updatedAt: timestamp }; + const trigger: Trigger = { id: crypto.randomUUID(), jobId: id, kind: config ? kind : "manual", slug: "trigger-1", enabled, config: config ?? {}, createdAt: timestamp, updatedAt: timestamp }; return repository(tenantId).create({ id, name: "Job", slug: "job-" + id, promptTemplate: "{{trigger-1.state}}", runNameTemplate: "", model: "", executionConfig: { connectionId: "test", workspace: "", cwd: "", agentKind: "codex" }, concurrencyLimit: 1, enabled: true, triggers: [trigger], createdAt: timestamp, updatedAt: timestamp } as Job); } async function complete(tenantId: string, source: Job, state: "succeeded" | "failed" | "stopped" = "succeeded") { @@ -71,6 +72,39 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("job lifecycle delivery (Po expect(await deliveries()).toHaveLength(1); }); + it("fires job-idle only for a completion after the trigger exists", async () => { + const a = await tenant(), source = await job(a); + await complete(a, source); + const target = await job(a, { sourceJobIds: [source.id] }, true, "jobIdle"); + await deliverIdle(); + expect(await invocations(a, target.id)).toHaveLength(0); + + const runId = await complete(a, source); + await deliverIdle(); + await deliverIdle(); + expect(await invocations(a, target.id)).toMatchObject([{ source: "jobIdle", context: { "trigger-1": { source_job_id: source.id, event: "runsZero" } } }]); + expect((await database.pool.query("SELECT * FROM app.lifecycle_deliveries WHERE tenant_id=$1 AND trigger_id=$2 AND source_run_id=$3 AND terminal_state='runsZero'", [a, target.triggers[0]!.id, runId])).rows).toHaveLength(1); + }); + + it("waits until every selected job has no queued or active runs", async () => { + const a = await tenant(), first = await job(a), second = await job(a); + const target = await job(a, { sourceJobIds: [first.id, second.id] }, true, "jobIdle"); + await complete(a, second); + const queued = await new InvocationService(repository(a), value => encrypt(value, key)).invoke(first.id, { + source: "manual", triggerId: first.triggers[0]!.id, claimKey: crypto.randomUUID(), context: {}, + }); + const activeRun = await runs.claimNext(); + expect(activeRun?.id).toBe(queued.run.id); + await deliverIdle(); + expect(await invocations(a, target.id)).toHaveLength(0); + + await runs.consumeWakeHint(); + await runs.terminal(activeRun!, "succeeded", "stored", undefined, true); + await deliverIdle(); + expect(await invocations(a, target.id)).toHaveLength(1); + expect(await invocations(a, target.id)).toMatchObject([{ source: "jobIdle" }]); + }); + it("matches each of multiple source IDs and legacy singular config with terminalStates", async () => { const a = await tenant(), first = await job(a), second = await job(a); const target = await job(a, { sourceJobIds: [first.id, second.id], states: ["succeeded", "stopped"] }); diff --git a/packages/app/src/features/jobs/editor-state.ts b/packages/app/src/features/jobs/editor-state.ts index bb17c85f..5a765327 100644 --- a/packages/app/src/features/jobs/editor-state.ts +++ b/packages/app/src/features/jobs/editor-state.ts @@ -39,6 +39,7 @@ export function validateJobInput(input: JobInput): string | undefined { if (!trigger.slug || !/^trigger-[1-9][0-9]*$/.test(trigger.slug)) return "Each trigger needs a valid stable identifier."; if (trigger.kind === "schedule" && (!trigger.config.cron.trim() || !trigger.config.timezone.trim())) return "Schedule triggers require a cron expression and timezone."; if (trigger.kind === "jobLifecycle" && (!trigger.config.sourceJobIds.length || !trigger.config.states.length)) return "Lifecycle triggers require a source job and state."; + if (trigger.kind === "jobIdle" && !trigger.config.sourceJobIds.length) return "All runs complete triggers require a source job."; if (trigger.kind === "webhook" && (trigger.config.provider === "linear" || trigger.config.provider === "clickup") && !trigger.config.matchRules?.length) return "Provider triggers require at least one matching rule."; } return undefined; diff --git a/packages/app/src/features/jobs/trigger-editor.tsx b/packages/app/src/features/jobs/trigger-editor.tsx index 3845a3c4..b36be3d1 100644 --- a/packages/app/src/features/jobs/trigger-editor.tsx +++ b/packages/app/src/features/jobs/trigger-editor.tsx @@ -11,6 +11,7 @@ const defaults: Record = { manual: { kind: "manual", enabled: true, config: {} }, schedule: { kind: "schedule", enabled: true, config: { cron: "0 * * * *", timezone: "UTC" } }, jobLifecycle: { kind: "jobLifecycle", enabled: true, config: { sourceJobIds: [], states: ["succeeded"] } }, + jobIdle: { kind: "jobIdle", enabled: true, config: { sourceJobIds: [] } }, webhook: { kind: "webhook", enabled: true, config: { provider: "linear", projectId: "", matchRules: [] } }, }; function ScheduleFields({ trigger, onChange }: { trigger: Extract; onChange: (value: Trigger) => void }) { @@ -34,9 +35,10 @@ export function TriggerEditor({ triggers, onChange, onValidityChange }: { trigge {trigger.kind === "webhook" && replace(index, { ...trigger, config })} onValidityChange={onValidityChange} />} {trigger.kind === "jobLifecycle" && <> replace(index, { ...trigger, config: { ...trigger.config, sourceJobIds } })} />
Lifecycle states{(["succeeded", "failed", "stopped", "edited"] as const).map(state => )}
} + {trigger.kind === "jobIdle" && <> replace(index, { ...trigger, config: { ...trigger.config, sourceJobIds } })} />

Starts when the selected job has no queued or active runs.

} {trigger.kind !== "manual" && } )} - + ; } diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 0b4869b5..994a48a8 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -1107,6 +1107,36 @@ components: - kind - config additionalProperties: false + - type: object + properties: + id: + type: string + minLength: 1 + slug: + type: string + pattern: ^trigger-[1-9][0-9]*$ + kind: + type: string + const: jobIdle + enabled: + default: true + type: boolean + config: + type: object + properties: + sourceJobIds: + minItems: 1 + type: array + items: + type: string + minLength: 1 + required: + - sourceJobIds + additionalProperties: false + required: + - kind + - config + additionalProperties: false skillIds: maxItems: 50 type: array @@ -6239,6 +6269,50 @@ paths: - createdAt - updatedAt additionalProperties: false + - type: object + properties: + id: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + slug: + type: string + kind: + type: string + const: jobIdle + enabled: + default: true + type: boolean + config: + type: object + properties: + sourceJobIds: + minItems: 1 + type: array + items: + type: string + minLength: 1 + required: + - sourceJobIds + additionalProperties: false + jobId: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + createdAt: + type: string + updatedAt: + type: string + required: + - id + - slug + - kind + - enabled + - config + - jobId + - createdAt + - updatedAt + additionalProperties: false skills: type: array items: @@ -6762,6 +6836,50 @@ paths: - createdAt - updatedAt additionalProperties: false + - type: object + properties: + id: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + slug: + type: string + kind: + type: string + const: jobIdle + enabled: + default: true + type: boolean + config: + type: object + properties: + sourceJobIds: + minItems: 1 + type: array + items: + type: string + minLength: 1 + required: + - sourceJobIds + additionalProperties: false + jobId: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + createdAt: + type: string + updatedAt: + type: string + required: + - id + - slug + - kind + - enabled + - config + - jobId + - createdAt + - updatedAt + additionalProperties: false skills: type: array items: @@ -7256,6 +7374,50 @@ paths: - createdAt - updatedAt additionalProperties: false + - type: object + properties: + id: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + slug: + type: string + kind: + type: string + const: jobIdle + enabled: + default: true + type: boolean + config: + type: object + properties: + sourceJobIds: + minItems: 1 + type: array + items: + type: string + minLength: 1 + required: + - sourceJobIds + additionalProperties: false + jobId: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + createdAt: + type: string + updatedAt: + type: string + required: + - id + - slug + - kind + - enabled + - config + - jobId + - createdAt + - updatedAt + additionalProperties: false skills: type: array items: @@ -8040,6 +8202,50 @@ paths: - createdAt - updatedAt additionalProperties: false + - type: object + properties: + id: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + slug: + type: string + kind: + type: string + const: jobIdle + enabled: + default: true + type: boolean + config: + type: object + properties: + sourceJobIds: + minItems: 1 + type: array + items: + type: string + minLength: 1 + required: + - sourceJobIds + additionalProperties: false + jobId: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + createdAt: + type: string + updatedAt: + type: string + required: + - id + - slug + - kind + - enabled + - config + - jobId + - createdAt + - updatedAt + additionalProperties: false skills: type: array items: @@ -8547,6 +8753,50 @@ paths: - createdAt - updatedAt additionalProperties: false + - type: object + properties: + id: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + slug: + type: string + kind: + type: string + const: jobIdle + enabled: + default: true + type: boolean + config: + type: object + properties: + sourceJobIds: + minItems: 1 + type: array + items: + type: string + minLength: 1 + required: + - sourceJobIds + additionalProperties: false + jobId: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + createdAt: + type: string + updatedAt: + type: string + required: + - id + - slug + - kind + - enabled + - config + - jobId + - createdAt + - updatedAt + additionalProperties: false skills: type: array items: @@ -8937,6 +9187,36 @@ paths: - kind - config additionalProperties: false + - type: object + properties: + id: + type: string + minLength: 1 + slug: + type: string + pattern: ^trigger-[1-9][0-9]*$ + kind: + type: string + const: jobIdle + enabled: + default: true + type: boolean + config: + type: object + properties: + sourceJobIds: + minItems: 1 + type: array + items: + type: string + minLength: 1 + required: + - sourceJobIds + additionalProperties: false + required: + - kind + - config + additionalProperties: false skillIds: maxItems: 50 type: array