From 0d6320bcb15845e2e98d48848e09906c7a5b2352 Mon Sep 17 00:00:00 2001 From: Brendan Date: Wed, 16 Sep 2026 23:54:26 +0000 Subject: [PATCH] Fix manual invocation idempotency key reuse --- docs/job-trigger-context.md | 2 +- packages/app/src/flow-schemas.ts | 4 +++- packages/app/src/protected-api.ts | 4 ++-- packages/app/src/tenant.ts | 8 +++++++- packages/app/test/flow-service.test.ts | 2 ++ packages/app/test/run-inspection.test.ts | 21 +++++++++++++++++++++ 6 files changed, 36 insertions(+), 5 deletions(-) diff --git a/docs/job-trigger-context.md b/docs/job-trigger-context.md index 5e3d47f1..6bea9a8b 100644 --- a/docs/job-trigger-context.md +++ b/docs/job-trigger-context.md @@ -23,7 +23,7 @@ The available value beneath a slug is: Every trigger returned by `GET /api/v1/jobs` and `GET /api/v1/jobs/:id` (and the corresponding MCP `list_jobs` and `get_job` tools) includes a `reflection` object. It contains the stable `slug`, trigger kind/provider, whether the result is dynamic, and a flat `paths` list with nested path, basic value type, description, and occasional example. The Job editor consumes this same canonical contract for Mustache autocomplete. A webhook with a replacing handler reports `dynamic: true` and an explicit `*`/`unknown` fallback because arbitrary handler output cannot be inferred safely. -Manual invocation accepts `{ "prompt": "...", "idempotencyKey": "..." }`. Parameter defaults and invocation, schedule, or webhook parameter overrides are not accepted. +Manual invocation accepts `{ "prompt": "...", "idempotencyKey": "..." }`. `idempotencyKey` is the client-facing value and must not include the reserved internal `manual:` prefix. Reusing the same value returns the original invocation. Run inspection exposes that reusable value as `invocation.idempotency_key`, while `invocation.claim_key` is the internal prefixed claim and must not be passed back to the invocation API. Parameter defaults and invocation, schedule, or webhook parameter overrides are not accepted. Run inspection returns `context` as the complete persisted object and `invocation.trigger_id` as the trigger that fired. Parameter-era stored Jobs are migrated: old context and parameters are retained beneath `legacy_context` and `legacy_parameters` in the corresponding trigger context. They are not used as global template variables. diff --git a/packages/app/src/flow-schemas.ts b/packages/app/src/flow-schemas.ts index 7a6d8815..6e40f866 100644 --- a/packages/app/src/flow-schemas.ts +++ b/packages/app/src/flow-schemas.ts @@ -40,7 +40,9 @@ export const jobInputSchema = z.object({ export const jobIdSchema = z.object({ jobId: z.string().min(1) }); export const manualInvocationSchema = z.object({ prompt: z.string().max(50_000).default(""), - idempotencyKey: z.string().trim().min(1).max(200).optional(), + idempotencyKey: z.string().trim().min(1).max(200).refine(key => !key.startsWith("manual:"), { + message: "idempotencyKey must not include the reserved manual: claim-key prefix", + }).optional(), }).strict(); export const jobHandlerTestSchema = z.object({ handlerCode: z.string().max(16_384), payload: z.record(z.string(), z.unknown()), diff --git a/packages/app/src/protected-api.ts b/packages/app/src/protected-api.ts index 77479d24..9ea51e7f 100644 --- a/packages/app/src/protected-api.ts +++ b/packages/app/src/protected-api.ts @@ -71,7 +71,7 @@ async function mcp(request: Request, service: ApiService, env: Env, ctx: Executi }); tool("list_exe_connections", "List safe metadata for saved exe.dev connections. API tokens are never returned.", z.object({}), () => service.listExeConnections()); tool("list_runs", "List authoritative job runs by job ID, state, and an optional case-insensitive literal substring of triggered context. Automatic webhook, schedule, and lifecycle signals coalesce, so query runs and the provider API for authoritative work. Context matches include only a bounded excerpt.", listRunsSchema, (input: any) => service.listRuns(queryOf(input))); - tool("get_run", "Get a run with its full triggered context, invocation metadata, execution metadata, output, and activity", runIdSchema, ({ runId }: any) => service.getRun(runId)); + tool("get_run", "Get a run with its full triggered context, invocation metadata, execution metadata, output, and activity. For manual invocations, invocation.idempotency_key is the client-reusable value; invocation.claim_key is internal.", runIdSchema, ({ runId }: any) => service.getRun(runId)); tool("stop_run", "Stop an active run", runIdSchema, ({ runId }: any) => service.stopRun(runId)); tool("list_jobs", "List jobs", z.object({}), () => service.listJobs()); tool("get_job", "Get a job", jobIdSchema, ({ jobId }: any) => service.getJob(jobId)); @@ -80,7 +80,7 @@ async function mcp(request: Request, service: ApiService, env: Env, ctx: Executi tool("delete_job", "Delete a job and its queued invocation history", jobIdSchema, ({ jobId }: any) => service.deleteJob(jobId)); tool("enable_job", "Enable a job", jobIdSchema, ({ jobId }: any) => service.setJobEnabled(jobId, true)); tool("disable_job", "Disable a job", jobIdSchema, ({ jobId }: any) => service.setJobEnabled(jobId, false)); - tool("invoke_job", "Invoke a job's manual trigger with a prompt exposed beneath that trigger's stable slug. Manual invocations are never coalesced.", manualInvocationSchema.extend({ jobId: z.string().min(1) }), ({ jobId, ...input }: any) => service.invokeJob(jobId, input)); + tool("invoke_job", "Invoke a job's manual trigger with a prompt exposed beneath that trigger's stable slug. Manual invocations are never coalesced. idempotencyKey is a client value and must not include the internal manual: claim-key prefix; reuse invocation.idempotency_key from get_run.", manualInvocationSchema.extend({ jobId: z.string().min(1) }), ({ jobId, ...input }: any) => service.invokeJob(jobId, input)); tool("list_job_webhook_activity", "List matching, rejected, duplicate, and accepted webhook activity for a job", z.object({ jobId: z.string().min(1), limit: z.number().int().min(1).max(100).default(50) }), ({ jobId, limit }: any) => service.listJobEvents(jobId, limit)); tool("test_job_webhook_handler", "Test an isolated synchronous Job webhook handler without creating a run. Returns the decision and never accepts credentials.", jobHandlerTestSchema, (input: any) => service.testJobHandler(input)); tool("list_execution_targets", "List non-secret execution target metadata and capabilities", z.object({}), () => service.listExecutionTargets()); diff --git a/packages/app/src/tenant.ts b/packages/app/src/tenant.ts index 887ba437..a383b95b 100644 --- a/packages/app/src/tenant.ts +++ b/packages/app/src/tenant.ts @@ -639,6 +639,9 @@ export class TenantV2 extends DurableObject { } private async invokeJob(jobId: string, input: any): Promise { + if (typeof input.idempotencyKey === "string" && input.idempotencyKey.trim().startsWith("manual:")) { + return Response.json({ error: "idempotencyKey must not include the reserved manual: claim-key prefix" }, { status: 400 }); + } const job = this.one("SELECT enabled FROM jobs WHERE id=?", jobId) as Row | undefined; if (!job) return new Response("Not found", { status: 404 }); if (!Boolean(job.enabled)) return Response.json({ error: "Job is disabled" }, { status: 409 }); @@ -872,7 +875,10 @@ export class TenantV2 extends DurableObject { try { context = JSON.parse(String(run.context || "{}")); } catch { context = { legacy: String(run.context ?? "") }; } try { occurrence = run.invocation_occurrence == null ? null : JSON.parse(String(run.invocation_occurrence)); } catch { /* Persisted invocation remains readable if metadata is malformed. */ } run.context = context; - run.invocation = { id: run.invocation_id, job_id: run.invocation_job_id, source: run.invocation_source, trigger_id: run.invocation_trigger_id, claim_key: run.invocation_claim_key, context, occurrence, created_at: run.invocation_created_at }; + const claimKey = String(run.invocation_claim_key); + const invocation: Record = { id: run.invocation_id, job_id: run.invocation_job_id, source: run.invocation_source, trigger_id: run.invocation_trigger_id, claim_key: claimKey, context, occurrence, created_at: run.invocation_created_at }; + if (run.invocation_source === "manual" && claimKey.startsWith("manual:")) invocation.idempotency_key = claimKey.slice("manual:".length); + run.invocation = invocation; } else { run.context = null; run.invocation = null; diff --git a/packages/app/test/flow-service.test.ts b/packages/app/test/flow-service.test.ts index d439fa31..8c640c2a 100644 --- a/packages/app/test/flow-service.test.ts +++ b/packages/app/test/flow-service.test.ts @@ -44,5 +44,7 @@ describe("shared API schemas", () => { expect(() => jobInputSchema.parse({ ...job, parameterDefaults: {} })).toThrow(); expect(() => manualInvocationSchema.parse({ parameters: {} })).toThrow(); expect(manualInvocationSchema.parse({ prompt: "ticket" })).toMatchObject({ prompt: "ticket" }); + expect(manualInvocationSchema.parse({ idempotencyKey: "dev-dispatch-gen-2032" })).toMatchObject({ idempotencyKey: "dev-dispatch-gen-2032" }); + expect(() => manualInvocationSchema.parse({ idempotencyKey: "manual:dev-dispatch-gen-2032" })).toThrow(/reserved manual: claim-key prefix/); }); }); diff --git a/packages/app/test/run-inspection.test.ts b/packages/app/test/run-inspection.test.ts index 14f1742f..edaaecbf 100644 --- a/packages/app/test/run-inspection.test.ts +++ b/packages/app/test/run-inspection.test.ts @@ -68,4 +68,25 @@ describe("run invocation inspection", () => { const legacyBody = await ((legacy as any).getRun("legacy-1") as Promise).then((response: Response) => response.json()) as any; expect(legacyBody).toMatchObject({ context: null, invocation: null }); }); + + it("exposes the reusable idempotency key for manual invocations", async () => { + const tenant = tenantWithRows((query) => query.includes("FROM runs r") ? [{ + id: "run-1", job_id: "job-1", state: "queued", backend_kind: "amp", capabilities: "[]", result: null, + context: '{"trigger-1":{"prompt":"go"}}', invocation_id: "inv-1", invocation_job_id: "job-1", invocation_source: "manual", invocation_trigger_id: "manual-1", + invocation_claim_key: "manual:dev-dispatch-gen-2032", invocation_occurrence: null, invocation_created_at: "2026-09-16T12:00:01Z", + }] : []); + + const body = await ((tenant as any).getRun("run-1") as Promise).then((response: Response) => response.json()) as any; + expect(body.invocation).toMatchObject({ + claim_key: "manual:dev-dispatch-gen-2032", + idempotency_key: "dev-dispatch-gen-2032", + }); + }); + + it("rejects an internal manual claim key before creating an invocation", async () => { + const tenant = Object.create(TenantV2.prototype) as TenantV2; + const response = await (tenant as any).invokeJob("job-1", { idempotencyKey: "manual:dev-dispatch-gen-2032" }) as Response; + expect(response.status).toBe(400); + await expect(response.json()).resolves.toEqual({ error: "idempotencyKey must not include the reserved manual: claim-key prefix" }); + }); });