diff --git a/packages/app/migrations/0007_job_edit_deliveries.sql b/packages/app/migrations/0007_job_edit_deliveries.sql new file mode 100644 index 00000000..38963aec --- /dev/null +++ b/packages/app/migrations/0007_job_edit_deliveries.sql @@ -0,0 +1,28 @@ +CREATE TABLE app.job_edit_deliveries ( + tenant_id uuid NOT NULL, + event_id uuid NOT NULL, + trigger_id uuid NOT NULL, + source_job_id uuid NOT NULL, + edited_at timestamptz NOT NULL, + PRIMARY KEY (tenant_id, event_id, trigger_id), + FOREIGN KEY (tenant_id, trigger_id) REFERENCES app.triggers(tenant_id, id) ON DELETE CASCADE, + FOREIGN KEY (tenant_id, source_job_id) REFERENCES app.jobs(tenant_id, id) ON DELETE CASCADE +); +CREATE INDEX job_edit_deliveries_pending ON app.job_edit_deliveries(edited_at, event_id); + +CREATE OR REPLACE FUNCTION app.next_wake_at() RETURNS timestamptz LANGUAGE sql STABLE AS $$ + SELECT min(candidate) FROM ( + SELECT min(not_before) candidate FROM app.wake_hints + UNION ALL SELECT min(d.edited_at) FROM app.job_edit_deliveries d + JOIN app.triggers t ON t.tenant_id=d.tenant_id AND t.id=d.trigger_id + JOIN app.jobs j ON j.tenant_id=t.tenant_id AND j.id=t.job_id + WHERE t.enabled AND t.removed_at IS NULL AND j.enabled + AND t.config->'sourceJobIds' ? d.source_job_id::text AND t.config->'states' ? 'edited' + UNION ALL SELECT min(next_run_at) FROM app.schedule_state + UNION ALL SELECT min(next_attempt_at) FROM app.pending_verifications + UNION ALL SELECT min(launch_lease_expires_at) FROM app.job_runs WHERE state='starting' + UNION ALL SELECT min(next_poll_at) FROM app.job_runs WHERE state IN ('running','blocked','stopping') + UNION ALL SELECT min(cleanup_next_at) FROM app.runs WHERE NOT vm_cleanup_complete + ) wakes +$$; + diff --git a/packages/app/src/flow-schemas.ts b/packages/app/src/flow-schemas.ts index f2a29cdc..c10c4117 100644 --- a/packages/app/src/flow-schemas.ts +++ b/packages/app/src/flow-schemas.ts @@ -27,7 +27,7 @@ export const triggerSchema = z.discriminatedUnion("kind", [ }).strict() }).strict(), z.object({ id: z.string().min(1).optional(), slug: z.string().regex(/^trigger-[1-9][0-9]*$/).optional(), kind: z.literal("webhook"), enabled: z.boolean().default(true), config: webhookTriggerConfigSchema }).strict(), 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"])).min(1), + sourceJobIds: z.array(z.string().min(1)).min(1), states: z.array(z.enum(["succeeded", "failed", "stopped", "edited"])).min(1), }).strict() }).strict(), ]); export const jobInputSchema = z.object({ diff --git a/packages/app/src/flow-service.ts b/packages/app/src/flow-service.ts index 6d5aee3d..121c10f1 100644 --- a/packages/app/src/flow-service.ts +++ b/packages/app/src/flow-service.ts @@ -106,7 +106,9 @@ export class ApiService { async updateJob(jobId: string, input: JobInput) { await this.authorize("flows:write"); const repository = this.jobs(), current = await repository.getJob(jobId); if (!current) throw new ServiceError(404, "not_found", "Job not found"); const triggers = this.normalizedTriggers(input.triggers, current.triggers).map(trigger => ({ ...trigger, jobId })); - return this.presentJob(await repository.update({ ...current, name: input.name, slug: input.slug, promptTemplate: input.promptTemplate, runNameTemplate: input.runNameTemplate ?? "", model: input.model ?? "", effort: input.effort, executionTarget: await this.executionTarget(input.executionTargetId), concurrencyLimit: input.concurrencyLimit, triggers, updatedAt: new Date().toISOString() })); + const updated = await repository.update({ ...current, name: input.name, slug: input.slug, promptTemplate: input.promptTemplate, runNameTemplate: input.runNameTemplate ?? "", model: input.model ?? "", effort: input.effort, executionTarget: await this.executionTarget(input.executionTargetId), concurrencyLimit: input.concurrencyLimit, triggers, updatedAt: new Date().toISOString() }); + await this.wakeScheduler(); + return this.presentJob(updated); } async deleteJob(jobId: string) { await this.authorize("flows:write"); @@ -121,7 +123,10 @@ export class ApiService { if (!await repository.delete(jobId)) throw new ServiceError(404, "not_found", "Job not found"); return { id: jobId, deleted: true }; } - async setJobEnabled(jobId: string, enabled: boolean) { await this.authorize("flows:write"); const repository = this.jobs(); if (!await repository.setEnabled(jobId, enabled, new Date().toISOString())) throw new ServiceError(404, "not_found", "Job not found"); return { id: jobId, enabled }; } + private async wakeScheduler() { + if (this.env.SCHEDULER) await this.env.SCHEDULER.get(this.env.SCHEDULER.idFromName("global")).fetch("https://scheduler/wake", { method: "POST" }); + } + async setJobEnabled(jobId: string, enabled: boolean) { await this.authorize("flows:write"); const repository = this.jobs(); if (!await repository.setEnabled(jobId, enabled, new Date().toISOString())) throw new ServiceError(404, "not_found", "Job not found"); await this.wakeScheduler(); return { id: jobId, enabled }; } async invokeJob(jobId: string, input: ManualInvocationInput) { await this.authorize("runs:write"); const repository = this.jobs(), job = await repository.getJob(jobId); if (!job) throw new ServiceError(404, "not_found", "Job not found"); const trigger = job.triggers.find(value => value.kind === "manual" && value.enabled); if (!trigger) throw new ServiceError(409, "operation_failed", "The manual trigger is disabled"); diff --git a/packages/app/src/postgres/automation-scheduler.ts b/packages/app/src/postgres/automation-scheduler.ts index fa39b76c..e5ec2f1e 100644 --- a/packages/app/src/postgres/automation-scheduler.ts +++ b/packages/app/src/postgres/automation-scheduler.ts @@ -11,7 +11,7 @@ import { invokeCustomHandler } from "../custom-handler"; /** 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.lifecycle(); } + async process(): Promise { await this.githubVerifications(); await this.schedules(); await this.jobEdits(); await this.lifecycle(); } 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++) { @@ -29,6 +29,25 @@ export class AutomationScheduler { await service.invoke(due.job_id, { source: "schedule", triggerId: due.trigger_id, claimKey: `schedule:${due.trigger_id}:${occurredAt}`, context: { [due.slug]: occurrence }, occurrence }); } } + private async jobEdits() { + const pending = await this.database.pool.query(`SELECT d.*,t.job_id,t.slug FROM app.job_edit_deliveries d + JOIN app.triggers t ON t.tenant_id=d.tenant_id AND t.id=d.trigger_id + JOIN app.jobs j ON j.tenant_id=t.tenant_id AND j.id=t.job_id + WHERE t.enabled AND t.removed_at IS NULL AND j.enabled + AND t.config->'sourceJobIds' ? d.source_job_id::text AND t.config->'states' ? 'edited' + ORDER BY d.edited_at,d.event_id LIMIT 100`); + for (const row of pending.rows) { + const context = { source_job_id: row.source_job_id, event: "edited", edited_at: row.edited_at.toISOString() }; + // Acknowledge only after invocation succeeds. Retrying after a crash uses + // the same claim key and returns the existing run. + await new InvocationService(this.repository(row.tenant_id), value => encrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY)).invoke(row.job_id, { + source: "jobLifecycle", triggerId: row.trigger_id, claimKey: `job-edited:${row.trigger_id}:${row.event_id}`, + context: { [row.slug]: context }, occurrence: { occurredAt: context.edited_at, externalId: row.event_id, metadata: context }, + }); + await this.database.pool.query("DELETE FROM app.job_edit_deliveries WHERE tenant_id=$1 AND event_id=$2 AND trigger_id=$3", [row.tenant_id, row.event_id, row.trigger_id]); + } + } + private async lifecycle() { const rows = await this.database.pool.query(`SELECT t.tenant_id,t.id trigger_id,t.job_id,t.slug,t.config,r.id source_run_id,r.job_id source_job_id,r.state,r.updated_at FROM app.triggers t JOIN app.jobs j ON j.tenant_id=t.tenant_id AND j.id=t.job_id JOIN app.runs r ON r.tenant_id=t.tenant_id AND r.job_id=(t.config->>'sourceJobId')::uuid LEFT JOIN app.lifecycle_deliveries d ON d.tenant_id=t.tenant_id AND d.trigger_id=t.id AND d.source_run_id=r.id AND d.terminal_state=r.state WHERE t.kind='jobLifecycle' AND t.enabled AND t.removed_at IS NULL AND j.enabled AND r.state IN ('succeeded','failed','stopped') AND d.source_run_id IS NULL ORDER BY r.updated_at LIMIT 100`); for (const row of rows.rows) { diff --git a/packages/app/src/postgres/job-repository.ts b/packages/app/src/postgres/job-repository.ts index 5dd02e61..1a81791a 100644 --- a/packages/app/src/postgres/job-repository.ts +++ b/packages/app/src/postgres/job-repository.ts @@ -2,7 +2,7 @@ import type { Invocation, Job, JobRepository, JobRun, Trigger } from "../job-dom import type { Database, DatabaseClient } from "./database"; import { nextOccurrence, validateScheduleConfig } from "../schedule"; import { and, eq, isNull, sql } from "drizzle-orm"; -import { invocations, jobs, lifecycleDeliveries, pendingVerifications, scheduleState, triggers } from "./schema"; +import { invocations, jobs, jobEditDeliveries, lifecycleDeliveries, pendingVerifications, scheduleState, triggers } from "./schema"; type Crypt = (value: string) => Promise; type JobRow = typeof jobs.$inferSelect; @@ -44,6 +44,7 @@ export class PostgresJobRepository implements JobRepository { const existing: TriggerRow[] = await tx.select().from(triggers).where(and(eq(triggers.tenantId, this.tenantId), eq(triggers.jobId, job.id), isNull(triggers.removedAt))).orderBy(triggers.position); const [row] = await tx.update(jobs).set({ name: job.name, slug: job.slug, encryptedPromptTemplate: await this.encrypt(job.promptTemplate), encryptedRunNameTemplate: job.runNameTemplate ? await this.encrypt(job.runNameTemplate) : "", executionTarget: job.executionTarget, model: job.model, effort: job.effort ?? "", concurrencyLimit: job.concurrencyLimit, enabled: job.enabled, updatedAt: new Date(job.updatedAt) }).where(and(eq(jobs.tenantId, this.tenantId), eq(jobs.id, job.id))).returning(); await this.reconcileTriggers(tx, job, existing); + await this.recordEdit(tx, job.id, job.updatedAt); return this.mapped(row!, tx); }); } @@ -54,16 +55,29 @@ export class PostgresJobRepository implements JobRepository { if (!job) return false; const schedules: TriggerRow[] = await tx.select().from(triggers).where(and(eq(triggers.tenantId, this.tenantId), eq(triggers.jobId, id), eq(triggers.kind, "schedule"), isNull(triggers.removedAt))); for (const trigger of schedules) await tx.update(scheduleState).set({ nextRunAt: enabled && trigger.enabled ? nextOccurrence(validateScheduleConfig(trigger.config), new Date()) : null }).where(and(eq(scheduleState.tenantId, this.tenantId), eq(scheduleState.triggerId, trigger.id))); + await this.recordEdit(tx, id, changedAt); return true; }); } + private async recordEdit(tx: any, sourceJobId: string, editedAt: string): Promise { + // Snapshot matching subscribers with the edit, so later subscriptions cannot + // replay old edits. The outbox commits or rolls back with the job update. + await tx.execute(sql`INSERT INTO app.job_edit_deliveries(tenant_id,event_id,trigger_id,source_job_id,edited_at) + SELECT t.tenant_id,${crypto.randomUUID()}::uuid,t.id,${sourceJobId}::uuid,${editedAt}::timestamptz + FROM app.triggers t JOIN app.jobs j ON j.tenant_id=t.tenant_id AND j.id=t.job_id + WHERE t.tenant_id=${this.tenantId}::uuid AND t.job_id<>${sourceJobId}::uuid + AND t.kind='jobLifecycle' AND t.enabled AND t.removed_at IS NULL AND j.enabled + AND t.config->'sourceJobIds' ? ${sourceJobId} AND t.config->'states' ? 'edited'`); + } + private async reconcileTriggers(tx: any, job: Job, existing: TriggerRow[]): Promise { const desiredIds = new Set(job.triggers.map(trigger => trigger.id)); for (const old of existing.filter(trigger => !desiredIds.has(trigger.id))) { const referenced = await tx.select({ value: sql`1` }).from(invocations).where(and(eq(invocations.tenantId, this.tenantId), eq(invocations.triggerId, old.id))).limit(1) .then((rows: unknown[]) => rows.length > 0) || await tx.select({ value: sql`1` }).from(lifecycleDeliveries).where(and(eq(lifecycleDeliveries.tenantId, this.tenantId), eq(lifecycleDeliveries.triggerId, old.id))).limit(1).then((rows: unknown[]) => rows.length > 0) || await tx.select({ value: sql`1` }).from(pendingVerifications).where(and(eq(pendingVerifications.tenantId, this.tenantId), eq(pendingVerifications.triggerId, old.id))).limit(1).then((rows: unknown[]) => rows.length > 0); + await tx.delete(jobEditDeliveries).where(and(eq(jobEditDeliveries.tenantId, this.tenantId), eq(jobEditDeliveries.triggerId, old.id))); if (referenced) await tx.update(triggers).set({ enabled: false, removedAt: new Date(job.updatedAt), updatedAt: new Date(job.updatedAt) }).where(and(eq(triggers.tenantId, this.tenantId), eq(triggers.id, old.id))); else await tx.delete(triggers).where(and(eq(triggers.tenantId, this.tenantId), eq(triggers.id, old.id))); await tx.delete(scheduleState).where(and(eq(scheduleState.tenantId, this.tenantId), eq(scheduleState.triggerId, old.id))); diff --git a/packages/app/src/postgres/schema.ts b/packages/app/src/postgres/schema.ts index 09f1b8ac..9dee5e09 100644 --- a/packages/app/src/postgres/schema.ts +++ b/packages/app/src/postgres/schema.ts @@ -64,6 +64,9 @@ export const activeClaims = app.table("active_claims", { tenantId: uuid("tenant_ export const scheduleState = app.table("schedule_state", { tenantId: uuid("tenant_id").notNull(), triggerId: uuid("trigger_id").notNull(), jobId: uuid("job_id").notNull(), nextRunAt: timestamp("next_run_at", { withTimezone: true }), lastTriggeredAt: timestamp("last_triggered_at", { withTimezone: true }) }, t => [primaryKey({ columns: [t.tenantId, t.triggerId] }), foreignKey({ columns: [t.tenantId, t.triggerId], foreignColumns: [triggers.tenantId, triggers.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), index("schedules_due").on(t.nextRunAt).where(sql`${t.nextRunAt} is not null`)]); export const automaticWakes = app.table("automatic_wakes", { tenantId: uuid("tenant_id").notNull(), jobId: uuid("job_id").notNull(), trailingPending: boolean("trailing_pending").notNull().default(false), summary: jsonb("summary").$type>().notNull().default({}), updatedAt: updatedAt() }, t => [primaryKey({ columns: [t.tenantId, t.jobId] }), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade")]); +export const jobEditDeliveries = app.table("job_edit_deliveries", { + tenantId: uuid("tenant_id").notNull(), eventId: uuid("event_id").notNull(), triggerId: uuid("trigger_id").notNull(), sourceJobId: uuid("source_job_id").notNull(), editedAt: timestamp("edited_at", { withTimezone: true }).notNull(), +}, t => [primaryKey({ columns: [t.tenantId, t.eventId, t.triggerId] }), foreignKey({ columns: [t.tenantId, t.triggerId], foreignColumns: [triggers.tenantId, triggers.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.sourceJobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), index("job_edit_deliveries_pending").on(t.editedAt, t.eventId)]); export const lifecycleDeliveries = app.table("lifecycle_deliveries", { tenantId: uuid("tenant_id").notNull(), triggerId: uuid("trigger_id").notNull(), sourceRunId: uuid("source_run_id").notNull(), terminalState: text("terminal_state").notNull(), createdAt: createdAt() }, t => [primaryKey({ columns: [t.tenantId, t.triggerId, t.sourceRunId, t.terminalState] }), foreignKey({ columns: [t.tenantId, t.triggerId], foreignColumns: [triggers.tenantId, triggers.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.sourceRunId], foreignColumns: [runs.tenantId, runs.id] }).onDelete("cascade")]); export const jobEvents = app.table("job_events", { tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), jobId: uuid("job_id").notNull(), provider: text("provider").notNull(), deliveryId: text("delivery_id").notNull(), outcome: text("outcome").notNull(), detail: text("detail").notNull(), receivedAt: timestamp("received_at", { withTimezone: true }).notNull().defaultNow() }, t => [primaryKey({ columns: [t.tenantId, t.id] }), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), index("job_events_by_job").on(t.tenantId, t.jobId, t.receivedAt)]); export const webhookDeliveries = app.table("webhook_deliveries", { tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), id: uuid("id").notNull(), provider: text("provider").notNull(), deliveryId: text("delivery_id").notNull(), eventType: text("event_type").notNull().default("unknown"), eventAction: text("event_action").notNull().default("unknown"), outcome: text("outcome").notNull(), detail: text("detail").notNull(), receivedAt: timestamp("received_at", { withTimezone: true }).notNull().defaultNow() }, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.provider, t.deliveryId)]); @@ -97,7 +100,7 @@ export const runRelations = relations(runs, ({ one, many }) => ({ export const databaseSchema = { schemaMigrations, tenants, authUsers, authAccounts, authResetTokens, authSessions, oauthDeviceAuthorizations, members, accessTokens, connections, githubInstallations, githubSetupStates, jobs, triggers, invocations, jobRuns, runs, runArtifacts, - runTraceEvents, runActivity, activeClaims, scheduleState, automaticWakes, lifecycleDeliveries, jobEvents, + runTraceEvents, runActivity, activeClaims, scheduleState, automaticWakes, lifecycleDeliveries, jobEditDeliveries, jobEvents, webhookDeliveries, webhookDeliveryEvents, pendingVerifications, tailFingerprints, wakeHints, runTraceCursors, runTraceChunks, tenantRelations, jobRelations, triggerRelations, invocationRelations, runRelations, }; diff --git a/packages/app/src/trigger-context.ts b/packages/app/src/trigger-context.ts index 9a1440c7..10868a36 100644 --- a/packages/app/src/trigger-context.ts +++ b/packages/app/src/trigger-context.ts @@ -60,7 +60,9 @@ export const triggerContextCatalog: Record = { { path: "exceptions", type: "array", description: "Sanitized exception records." }, ], jobLifecycle: [ - { path: "source_job_id", type: "string", description: "Job whose run reached a final state." }, + { 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)." }, + { path: "source_job_id", type: "string", description: "Job that was edited or whose run reached a final state." }, { path: "source_run_id", type: "string", description: "Run that reached a final state." }, { path: "final_state", type: "string", description: "Observed final state: succeeded, failed, or stopped." }, { path: "transitioned_at", type: "string", description: "State transition as an ISO 8601 timestamp." }, diff --git a/packages/app/src/ui.ts b/packages/app/src/ui.ts index 735bb131..ff2fe2b0 100644 --- a/packages/app/src/ui.ts +++ b/packages/app/src/ui.ts @@ -101,7 +101,7 @@ export const jobPage = (viewer: { email: string }, jobId?: string) => shell(`${j - +
`, `${uiHelpers} const jobId=${JSON.stringify(jobId ?? null)},contextCatalog=${JSON.stringify(triggerContextCatalog)},form=$('#job'),dialog=$('#trigger-dialog'),triggerForm=$('#trigger-form');let triggers=[],editing=-1,resources={targets:[],projects:[],clickupLists:[],options:{statuses:[],users:[],labels:[]},clickupOptions:{statuses:[],users:[],labels:[]},githubOptions:{statuses:[],users:[],labels:[]},installations:[],tailInstallations:[],repositories:new Map(),jobs:[]},clientId=0,reservedSlugs=new Set(),availability={}; @@ -154,7 +154,7 @@ async function syncGithubIssueOptions(){const installationId=triggerForm.element async function openEditor(kind,index=-1){const current=index>=0?triggers[index]:null,k=current?providerKind(current):kind;if(!kinds[k])throw new Error('This trigger type is no longer supported.');editing=index;const c=current?.config||{};$('#dialog-title').textContent=(current?'Edit ':'Add ')+kinds[k]+' trigger';triggerForm.reset();document.querySelectorAll('[data-panel]').forEach(x=>x.classList.add('hidden'));const panel=document.querySelector('[data-panel="'+(k==='manual'?'none':k==='schedule'?'schedule':k==='linear'?'linear':k==='clickup'?'clickup':k==='github'?'github':k==='jobLifecycle'?'jobLifecycle':'webhook')+'"]');panel?.classList.remove('hidden');triggerForm.dataset.kind=k;$('#dialog-error').classList.add('hidden');$('#handler-result').textContent='';if(k==='schedule'){triggerForm.elements.cron.value=c.cron||'0 9 * * *';triggerForm.elements.timezone.value=c.timezone||'UTC'}if(k==='linear'){options(triggerForm.elements.projectId,resources.projects,'name');triggerForm.elements.projectId.value=c.projectId||resources.projects[0]?.id||'';$('#linear-rules').replaceChildren();(c.matchRules?.length?c.matchRules:[{type:'status',targetId:''}]).forEach(addLinearRule)}if(k==='clickup'){options(triggerForm.elements.clickupListId,resources.clickupLists,'name');triggerForm.elements.clickupListId.value=c.listId||resources.clickupLists[0]?.id||'';await syncClickupOptions(c.matchRules)}if(k==='github'){options(triggerForm.elements.installationId,resources.installations,'accountLogin','installationId');triggerForm.elements.installationId.value=String(c.installationId||resources.installations[0]?.installationId||'');await syncRepositories(c.repositoryId);$('#github-rules').replaceChildren();(c.matchRules?.length?c.matchRules:[{type:'status',targetId:''}]).forEach(addGithubRule);await syncGithubIssueOptions()}if(k==='jobLifecycle'){options(triggerForm.elements.sourceJobId,resources.jobs.filter(j=>j.id!==jobId),'name');[...triggerForm.elements.sourceJobId.options].forEach(x=>x.selected=(c.sourceJobIds||[]).includes(x.value));triggerForm.querySelectorAll('[name=lifecycleState]').forEach(x=>x.checked=(c.states||['succeeded','failed']).includes(x.value))}if(['linear','clickup','github','cloudflareTail'].includes(k))triggerForm.elements.handlerCode.value=c.handlerCode||'';dialog.showModal();if(k==='schedule')previewSchedule()} async function previewSchedule(){const body={cron:triggerForm.elements.cron.value,timezone:triggerForm.elements.timezone.value};try{const x=await request('/api/v1/schedules/preview',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});$('#schedule-preview').textContent='Next occurrence: '+new Date(x.nextRunAt).toLocaleString()}catch(e){$('#schedule-preview').textContent=e.message}} function configFromForm(){const k=triggerForm.dataset.kind,h=triggerForm.elements.handlerCode?.value.trim(),handler=h?{handlerCode:h}:{};if(k==='manual')return {kind:'manual',config:{}};if(k==='schedule')return {kind:'schedule',config:{cron:triggerForm.elements.cron.value.trim(),timezone:triggerForm.elements.timezone.value}};if(k==='linear')return {kind:'webhook',config:{provider:'linear',projectId:triggerForm.elements.projectId.value,matchRules:readLinearRules(),...handler}};if(k==='clickup')return {kind:'webhook',config:{provider:'clickup',listId:triggerForm.elements.clickupListId.value,matchRules:readClickupRules(),...handler}};if(k==='github')return {kind:'webhook',config:{provider:'github',installationId:Number(triggerForm.elements.installationId.value),repositoryId:Number(triggerForm.elements.repositoryId.value),matchRules:readGithubRules(),...handler}};if(k==='cloudflareTail')return {kind:'webhook',config:{provider:k,integrationId:triggerForm.elements.tailIntegrationId.value}};return {kind:'jobLifecycle',config:{sourceJobIds:[...triggerForm.elements.sourceJobId.selectedOptions].map(x=>x.value),states:[...triggerForm.querySelectorAll('[name=lifecycleState]:checked')].map(x=>x.value)}}} -function validate(candidate){const k=providerKind(candidate);if(k==='manual'&&triggers.some((t,i)=>i!==editing&&providerKind(t)==='manual'))throw new Error('Only one Manual trigger can be configured.');if(k==='linear'&&(!candidate.config.projectId||!candidate.config.matchRules.length||candidate.config.matchRules.some(rule=>!rule.targetId)))throw new Error('Choose a Linear project and a value for every matching rule.');if(k==='clickup'&&(!candidate.config.listId||!candidate.config.matchRules.length||candidate.config.matchRules.some(rule=>!rule.targetId)))throw new Error('Choose a ClickUp list and a value for every matching rule.');if(k==='github'&&(!candidate.config.installationId||!candidate.config.repositoryId||!candidate.config.matchRules.length||candidate.config.matchRules.some(rule=>!rule.targetId)))throw new Error('Choose a GitHub installation, repository, and a value for every matching rule.');if(k==='jobLifecycle'&&(!candidate.config.sourceJobIds[0]||!candidate.config.states.length))throw new Error('Choose a source job and at least one final state.');if(triggers.some((t,i)=>i!==editing&&JSON.stringify(t.config)===JSON.stringify(candidate.config)&&t.kind===candidate.kind))throw new Error('An identical trigger is already configured.')} +function validate(candidate){const k=providerKind(candidate);if(k==='manual'&&triggers.some((t,i)=>i!==editing&&providerKind(t)==='manual'))throw new Error('Only one Manual trigger can be configured.');if(k==='linear'&&(!candidate.config.projectId||!candidate.config.matchRules.length||candidate.config.matchRules.some(rule=>!rule.targetId)))throw new Error('Choose a Linear project and a value for every matching rule.');if(k==='clickup'&&(!candidate.config.listId||!candidate.config.matchRules.length||candidate.config.matchRules.some(rule=>!rule.targetId)))throw new Error('Choose a ClickUp list and a value for every matching rule.');if(k==='github'&&(!candidate.config.installationId||!candidate.config.repositoryId||!candidate.config.matchRules.length||candidate.config.matchRules.some(rule=>!rule.targetId)))throw new Error('Choose a GitHub installation, repository, and a value for every matching rule.');if(k==='jobLifecycle'&&(!candidate.config.sourceJobIds[0]||!candidate.config.states.length))throw new Error('Choose a source job and at least one event.');if(triggers.some((t,i)=>i!==editing&&JSON.stringify(t.config)===JSON.stringify(candidate.config)&&t.kind===candidate.kind))throw new Error('An identical trigger is already configured.')} $('#trigger-rows').onclick=e=>{const b=e.target.closest('button');if(!b)return;const key=['edit','remove'].find(x=>b.dataset[x]!==undefined),i=Number(b.dataset[key]);if(key==='edit')openEditor(providerKind(triggers[i]),i);if(key==='remove'){if(providerKind(triggers[i])==='manual'){const error=$('#error');error.textContent='A Job must keep its Manual trigger. Disable it if manual runs should be unavailable.';error.classList.remove('hidden');return}triggers.splice(i,1);render()}}; $('#trigger-rows').onchange=e=>{if(e.target.dataset.enable===undefined)return;triggers[Number(e.target.dataset.enable)].enabled=e.target.checked;render()};$('#add-trigger').onchange=e=>{const kind=e.target.value;e.target.value='';if(kind)openEditor(kind)};$('#add-linear-rule').onclick=()=>addLinearRule();$('#add-clickup-rule').onclick=()=>addClickupRule();$('#add-github-rule').onclick=()=>addGithubRule();$('#cancel-trigger').onclick=()=>dialog.close();triggerForm.elements.clickupListId.onchange=()=>syncClickupOptions();triggerForm.elements.installationId.onchange=async()=>{await syncRepositories();$('#github-rules').replaceChildren();addGithubRule();await syncGithubIssueOptions()};triggerForm.elements.repositoryId.onchange=()=>syncGithubIssueOptions();triggerForm.elements.cron.oninput=previewSchedule;triggerForm.elements.timezone.onchange=previewSchedule; triggerForm.querySelectorAll('[name=scheduleMode]').forEach(input=>input.onchange=syncScheduleEditor);triggerForm.elements.intervalUnit.onchange=syncScheduleEditor;triggerForm.elements.intervalValue.oninput=syncScheduleEditor; diff --git a/packages/app/test/job-edited.test.ts b/packages/app/test/job-edited.test.ts new file mode 100644 index 00000000..7e3b3bdf --- /dev/null +++ b/packages/app/test/job-edited.test.ts @@ -0,0 +1,114 @@ +import { afterAll, afterEach, describe, expect, it, vi } from "vitest"; +import { Database } from "../src/postgres/database"; +import { PostgresJobRepository } from "../src/postgres/job-repository"; +import { AutomationScheduler } from "../src/postgres/automation-scheduler"; +import { triggerSchema } from "../src/flow-schemas"; +import { encrypt, decrypt } from "../src/crypto"; +import type { Job, Trigger } from "../src/job-domain"; + +it("accepts edited alongside terminal events and rejects unknown lifecycle events", () => { + const trigger = { kind: "jobLifecycle", config: { sourceJobIds: ["source"], states: ["edited", "failed"] } }; + expect(triggerSchema.parse(trigger).config).toEqual(trigger.config); + expect(triggerSchema.safeParse({ ...trigger, config: { ...trigger.config, states: ["unknown"] } }).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 }); + const key = btoa("01234567890123456789012345678901"); + const tenants: string[] = []; + const repository = (tenantId: string) => new PostgresJobRepository(database, tenantId, value => encrypt(value, key), value => decrypt(value, key)); + 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, sourceIds: string[] = [], states = ["edited"], enabled = true) { + const id = crypto.randomUUID(), timestamp = new Date().toISOString(); + const triggers: Trigger[] = sourceIds.length ? [{ id: crypto.randomUUID(), jobId: id, kind: "jobLifecycle", slug: "trigger-1", enabled, config: { sourceJobIds: sourceIds, states }, createdAt: timestamp, updatedAt: timestamp }] : []; + return repository(tenantId).create({ id, name: "Job", slug: "job-" + id, promptTemplate: "{{trigger-1.event}} {{trigger-1.source_job_id}}", runNameTemplate: "", model: "", executionTarget: { connectionId: "test", workspace: "", cwd: "", agentKind: "codex" }, concurrencyLimit: 1, enabled: true, triggers, createdAt: timestamp, updatedAt: timestamp } as Job); + } + const pending = async () => (await database.pool.query("SELECT * FROM app.job_edit_deliveries WHERE tenant_id=ANY($1::uuid[])", [tenants])).rows; + const deliver = () => (new AutomationScheduler(database, { CREDENTIAL_ENCRYPTION_KEY: key } as any) as any).jobEdits(); + afterAll(() => database.close()); + afterEach(async () => { + vi.restoreAllMocks(); + await database.pool.query("DELETE FROM app.tenants WHERE id=ANY($1::uuid[])", [tenants]); + tenants.length = 0; + }); + + it("matches multiple source jobs, excludes self/other tenants/disabled and terminal-only subscribers", async () => { + const a = await tenant(), b = await tenant(), source = await job(a), other = await job(a); + const target = await job(a, [other.id, source.id]); + await job(a, [source.id], ["failed"]); + await job(a, [source.id], ["edited"], false); + const disabled = await job(a, [source.id]); + await repository(a).setEnabled(disabled.id, false, new Date().toISOString()); + await job(b, [source.id]); + expect(await pending()).toHaveLength(0); + await repository(a).update({ ...source, triggers: [{ ...target.triggers[0]!, id: crypto.randomUUID(), jobId: source.id, config: { sourceJobIds: [source.id], states: ["edited"] } }] }); + expect(await pending()).toMatchObject([{ trigger_id: target.triggers[0]!.id, source_job_id: source.id }]); + expect(await pending()).toHaveLength(1); + await repository(a).update(other); + expect(await pending()).toHaveLength(2); + await deliver(); + const runs = (await database.pool.query("SELECT i.context,r.state FROM app.invocations i JOIN app.job_runs r ON r.tenant_id=i.tenant_id AND r.invocation_id=i.id WHERE i.tenant_id=$1", [a])).rows; + expect(runs).toHaveLength(2); + expect(runs[0]).toMatchObject({ state: "queued", context: { "trigger-1": { event: "edited" } } }); + expect(await pending()).toHaveLength(0); + }); + + it("rolls back events with the edit and does not replay edits to later subscriptions", async () => { + const a = await tenant(), source = await job(a); + await repository(a).update(source); + await job(a, [source.id]); + expect(await pending()).toHaveLength(0); + const transaction = database.orm.transaction.bind(database.orm); + vi.spyOn(database.orm, "transaction").mockImplementation((work: any) => transaction(async tx => { await work(tx); throw new Error("rollback"); })); + await expect(repository(a).update({ ...source, name: "rolled back" })).rejects.toThrow("rollback"); + expect(await pending()).toHaveLength(0); + expect((await repository(a).getJob(source.id))?.name).toBe("Job"); + }); + + it("deduplicates a delivery retried after invocation commits but acknowledgement fails", async () => { + const a = await tenant(), source = await job(a), target = await job(a, [source.id]); + await repository(a).setEnabled(source.id, false, new Date().toISOString()); + const query = database.pool.query.bind(database.pool); + const spy = vi.spyOn(database.pool, "query").mockImplementation(((sql: string, ...args: any[]) => { + if (typeof sql === "string" && sql.startsWith("DELETE FROM app.job_edit_deliveries")) throw new Error("ack failed"); + return (query as any)(sql, ...args); + }) as any); + await expect(deliver()).rejects.toThrow("ack failed"); + expect(await pending()).toHaveLength(1); + spy.mockRestore(); + await deliver(); + expect(await pending()).toHaveLength(0); + expect((await database.pool.query("SELECT * FROM app.invocations WHERE tenant_id=$1 AND job_id=$2", [a, target.id])).rows).toHaveLength(1); + }); + + it("drops pending edits when a historically referenced trigger is removed", async () => { + const a = await tenant(), source = await job(a), target = await job(a, [source.id]); + await repository(a).update(source); + await deliver(); + await repository(a).update(source); + expect(await pending()).toHaveLength(1); + await repository(a).update({ ...target, triggers: [] }); + expect(await pending()).toHaveLength(0); + expect((await repository(a).getJob(target.id))?.triggers).toEqual([]); + }); + + it("retains failed deliveries, pauses disabled destinations, and cascades deletion", async () => { + const a = await tenant(), source = await job(a), target = await job(a, [source.id]); + await repository(a).update(source); + expect((await database.pool.query("SELECT app.next_wake_at() wake")).rows[0].wake).not.toBeNull(); + await repository(a).setEnabled(target.id, false, new Date().toISOString()); + await deliver(); + expect(await pending()).toHaveLength(1); + await repository(a).setEnabled(target.id, true, new Date().toISOString()); + const broken = new AutomationScheduler(database, { CREDENTIAL_ENCRYPTION_KEY: "invalid" } as any); + await expect((broken as any).jobEdits()).rejects.toThrow(); + expect(await pending()).toHaveLength(1); + await repository(a).delete(source.id); + expect(await pending()).toHaveLength(0); + }); +}); diff --git a/packages/docs/integrations/triggers.mdx b/packages/docs/integrations/triggers.mdx index 7891af81..1881c6a0 100644 --- a/packages/docs/integrations/triggers.mdx +++ b/packages/docs/integrations/triggers.mdx @@ -5,6 +5,10 @@ description: Configure schedules, provider webhooks, and lifecycle triggers. Schedule config is `{cron, timezone}`. Webhook config supports `linear` (`projectId`, non-empty `matchRules`), `clickup` (`listId`, rules), `github` (`installationId`, `repositoryId`, and rules or event/action), and `cloudflareTail` (`integrationId`). Match rule types are `owner`, `creator`, `status`, `label`, and `assignee`, each with a `targetId`. -Lifecycle config is `{sourceJobIds, states}`, where states are `succeeded`, `failed`, or `stopped`. Triggers have stable server-generated slugs (`trigger-1`, `trigger-2`, …); use them in Mustache templates. Disabled triggers do not fire. +Lifecycle config is `{sourceJobIds, states}`, where states are `succeeded`, `failed`, `stopped`, or `edited`. Triggers have stable server-generated slugs (`trigger-1`, `trigger-2`, …); use them in Mustache templates. Disabled triggers do not fire. Linear webhooks require a fresh HMAC timestamp/signature and configured OAuth subscription. ClickUp uses its OAuth connection and signed webhook. GitHub uses the connected App installation. Cloudflare Tail sends sanitized, signed delivery data to the generated destination. + +Choose **Job lifecycle → Edited** and one or more source jobs to run a job when another job is saved (including enable/disable saves). Creation and run status changes do not produce edit events. Each successful save is an event, even if the submitted values are unchanged. Only enabled subscribers in the same tenant are matched; a job cannot subscribe to its own edits. + +Edited events expose `{{trigger-1.source_job_id}}`, `{{trigger-1.event}}` (`edited`), and `{{trigger-1.edited_at}}`. Events are recorded in the save transaction and delivered by the scheduler with retry deduplication. Subscribers added later do not receive earlier edits. Pending events wait while the destination is disabled or no longer matches; removing a trigger or deleting its source job discards them. diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 78cd4270..474e46df 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -24,7 +24,7 @@ components: executionTargetId: { type: string, minLength: 1 } model: { type: string, maxLength: 120 } effort: { type: string, maxLength: 40 } - triggers: { type: array, maxItems: 50, items: { type: object } } + triggers: { type: array, maxItems: 50, items: { type: object }, description: "Job lifecycle config uses sourceJobIds and states (succeeded, failed, stopped, edited). Edited fires on successful job saves, including enable/disable; context contains source_job_id, event, and edited_at." } RunPage: { type: object, required: [items], properties: { items: { type: array, items: { type: object } }, nextCursor: { type: string, nullable: true } } } ManualInvocation: type: object