From 0dbda6ecd476013561ba1cdb0c2f453807a6f558 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Fri, 18 Sep 2026 23:05:14 +0000 Subject: [PATCH] Fix manual invocation run name precedence (GEN-2126) --- packages/app/src/flow-service.ts | 2 +- packages/app/src/job-domain.ts | 4 +- packages/app/test/job-domain.test.ts | 25 +++++++ packages/app/test/manual-invocation.test.ts | 67 +++++++++++++++++++ .../app/test/manual-run-name.browser.test.ts | 36 ++++++++++ .../postgres-invocation-repository.test.ts | 7 +- 6 files changed, 137 insertions(+), 4 deletions(-) create mode 100644 packages/app/test/manual-invocation.test.ts create mode 100644 packages/app/test/manual-run-name.browser.test.ts diff --git a/packages/app/src/flow-service.ts b/packages/app/src/flow-service.ts index 121c10f1..59ae2e02 100644 --- a/packages/app/src/flow-service.ts +++ b/packages/app/src/flow-service.ts @@ -131,7 +131,7 @@ export class ApiService { 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"); const service = new InvocationService(repository, value => encrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY)); - const result = await service.invoke(jobId, { source: "manual", triggerId: trigger.id, claimKey: input.idempotencyKey ? `manual:${input.idempotencyKey}` : `manual:${crypto.randomUUID()}`, context: { [trigger.slug]: { prompt: input.prompt, data: input.data ?? {} } } }); + const result = await service.invoke(jobId, { source: "manual", name: input.name, triggerId: trigger.id, claimKey: input.idempotencyKey ? `manual:${input.idempotencyKey}` : `manual:${crypto.randomUUID()}`, context: { [trigger.slug]: { prompt: input.prompt, data: input.data ?? {} } } }); if (this.env.SCHEDULER) await this.env.SCHEDULER.get(this.env.SCHEDULER.idFromName("global")).fetch("https://scheduler/wake", { method: "POST" }); return { invocationId: result.invocation.id, runId: result.run.id, state: result.run.state, duplicate: result.duplicate }; } diff --git a/packages/app/src/job-domain.ts b/packages/app/src/job-domain.ts index 3fb2f9c9..8706d769 100644 --- a/packages/app/src/job-domain.ts +++ b/packages/app/src/job-domain.ts @@ -40,6 +40,8 @@ export interface Job { export interface InvocationRequest { source: InvocationSource; + /** Optional display name for a manual run; takes precedence over the template. */ + name?: string; triggerId: string; context: Record; /** Stable, source-owned key used to claim this occurrence exactly once. */ @@ -129,7 +131,7 @@ export class InvocationService { if (!input.triggerId || !input.context || typeof input.context !== "object" || Array.isArray(input.context)) throw new InvocationError("invalid_invocation", "A trigger and structured context are required."); const createdAt = this.clock(); const invocation: Invocation = { id: this.makeId(), jobId, source: input.source, claimKey: input.claimKey, triggerId: input.triggerId, context: input.context, ...(input.occurrence ? { occurrence: input.occurrence } : {}), createdAt }; - const run: JobRun = { id: this.makeId(), jobId, invocationId: invocation.id, state: "queued", encryptedPrompt: await this.encryptPrompt(renderJobPrompt(job, input.context)), runName: renderRunName(job.runNameTemplate ?? "", input.context, job.name), createdAt, updatedAt: createdAt }; + const run: JobRun = { id: this.makeId(), jobId, invocationId: invocation.id, state: "queued", encryptedPrompt: await this.encryptPrompt(renderJobPrompt(job, input.context)), runName: (input.source === "manual" ? input.name?.trim() : undefined) || renderRunName(job.runNameTemplate ?? "", input.context, job.name), createdAt, updatedAt: createdAt }; if (!await this.repository.insertInvocationAndRun(invocation, run)) { const winner = await this.repository.findInvocation(jobId, input.claimKey); if (!winner) throw new Error("Invocation claim was lost without a persisted winner."); diff --git a/packages/app/test/job-domain.test.ts b/packages/app/test/job-domain.test.ts index d8268840..6df2079b 100644 --- a/packages/app/test/job-domain.test.ts +++ b/packages/app/test/job-domain.test.ts @@ -47,6 +47,31 @@ describe("job invocation domain", () => { expect(result.run.runName).toBe("Review GEN-2113"); }); + it("persists explicit manual names and returns the original name on replay", async () => { + const repository = new MemoryRepository(); + repository.jobs.set("job-1", job({ runNameTemplate: "Template name" })); + const service = new InvocationService(repository, async value => value); + const request = { source: "manual" as const, name: "GEN-2106 — Issue title", triggerId: "manual-1", claimKey: "manual:issue", context: { "trigger-1": { data: { identifier: "GEN-2106" } } } }; + const first = await service.invoke("job-1", request); + expect((await repository.findInvocation("job-1", request.claimKey))?.run.runName).toBe(request.name); + const retry = await service.invoke("job-1", { ...request, name: "Changed name" }); + expect(retry).toEqual({ ...first, duplicate: true }); + }); + + it.each(["webhook", "schedule", "jobLifecycle"] as const)("keeps %s names template-derived", async source => { + const repository = new MemoryRepository(); + repository.jobs.set("job-1", job({ runNameTemplate: "Automatic" })); + const result = await new InvocationService(repository, async value => value).invoke("job-1", { source, name: "Manual override", triggerId: "trigger", claimKey: "event", context: {} }); + expect(result.run.runName).toBe("Automatic"); + }); + + it.each(["", " "])("uses the template for an empty manual domain name %j", async name => { + const repository = new MemoryRepository(); + repository.jobs.set("job-1", job({ runNameTemplate: "{{trigger-1.data.identifier}}" })); + const result = await new InvocationService(repository, async value => value).invoke("job-1", { source: "manual", name, triggerId: "manual-1", claimKey: "event", context: { "trigger-1": { data: { identifier: "GEN-2106" } } } }); + expect(result.run.runName).toBe("GEN-2106"); + }); + it("starts queued runs only while the job has capacity", async () => { const repository = new MemoryRepository(); const service = new InvocationService(repository, async value => value, undefined, () => "then"); const first = await service.invoke("job-1", { source: "manual", triggerId: "manual-1", claimKey: "one", context: { "trigger-1": { prompt: "go" } } }); diff --git a/packages/app/test/manual-invocation.test.ts b/packages/app/test/manual-invocation.test.ts new file mode 100644 index 00000000..8ef10434 --- /dev/null +++ b/packages/app/test/manual-invocation.test.ts @@ -0,0 +1,67 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { ApiService } from "../src/flow-service"; +import { protectedApiFetch } from "../src/protected-api"; +import { decrypt } from "../src/crypto"; +import type { Invocation, Job, JobRun } from "../src/job-domain"; + +vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {} })); + +afterEach(() => vi.restoreAllMocks()); + +describe("manual invocation API and shared service", () => { + const name = "GEN-2106 — Issue title"; + async function invoke(input: Record, template = "{{trigger-1.data.identifier}} — {{trigger-1.data.title}}", transport = "REST") { + const job: Job = { + id: "job-1", name: "dev", slug: "dev", promptTemplate: "{{trigger-1.prompt}} {{trigger-1.data.identifier}}", + runNameTemplate: template, model: "", executionTarget: { connectionId: "exe-1", workspace: "", cwd: "", agentKind: "codex" }, + concurrencyLimit: 1, enabled: true, createdAt: "now", updatedAt: "now", + triggers: [{ id: "manual-1", jobId: "job-1", kind: "manual", slug: "trigger-1", enabled: true, config: {}, createdAt: "now", updatedAt: "now" }], + }; + let persisted: { invocation: Invocation; run: JobRun } | undefined; + const repository = { + getJob: async () => job, + findInvocation: async () => persisted ?? null, + insertInvocationAndRun: async (invocation: Invocation, run: JobRun) => { persisted = structuredClone({ invocation, run }); return true; }, + }; + vi.spyOn(ApiService.prototype as any, "authorize").mockResolvedValue(undefined); + vi.spyOn(ApiService.prototype as any, "jobs").mockReturnValue(repository); + const key = btoa("a".repeat(32)); + const env = { CREDENTIAL_ENCRYPTION_KEY: key, APP_ORIGIN: "https://example.com" } as any; + const request = async (body: Record) => { + const response = await protectedApiFetch(new Request("https://example.com" + (transport === "REST" ? "/api/v1/jobs/job-1/invocations" : "/mcp"), { + method: "POST", headers: { Host: "example.com", "Content-Type": "application/json", Accept: "application/json, text/event-stream" }, + body: JSON.stringify(transport === "REST" ? body : { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "invoke_job", arguments: { jobId: "job-1", ...body } } }), + }), env, {} as any, {} as any); + if (transport === "REST") return response; + expect(response.status).toBe(200); + const text = await response.text(); + const message = JSON.parse(text.startsWith("event:") ? text.split("\n").find(line => line.startsWith("data:"))!.slice(5) : text); + expect(message.error).toBeUndefined(); + expect(message.result.isError).not.toBe(true); + return Response.json(message.result.structuredContent, { status: 202 }); + }; + const response = await request({ prompt: "Fix", data: { identifier: "GEN-2106", title: "Issue title" }, idempotencyKey: "issue-1", ...input }); + expect(response.status).toBe(202); + const result = await response.json() as any; + expect(result.runId).toBe(persisted?.run.id); + expect(await decrypt(persisted!.run.encryptedPrompt, key)).toBe("Fix GEN-2106"); + expect(persisted!.invocation.context).toEqual({ "trigger-1": { prompt: "Fix", data: { identifier: "GEN-2106", title: "Issue title" } } }); + return { persisted: persisted!, request, result }; + } + + it.each(["REST", "MCP"])("persists the %s name instead of the template and retains it on replay", async transport => { + const { persisted, request, result } = await invoke({ name: " " + name + " " }, "Template name", transport); + expect(persisted.run.runName).toBe(name); + const retry = await request({ name: "Replacement", idempotencyKey: "issue-1", data: { identifier: "changed" } }); + expect(await retry.json()).toEqual({ ...result, duplicate: true }); + expect(persisted.run.runName).toBe(name); + }); + + it("renders the name from normalized manual trigger data", async () => { + expect((await invoke({})).persisted.run.runName).toBe(name); + }); + + it.each(["", "{{trigger-1.data.missing}}", "{{#invalid}}"])("falls back to the Job name for template %j", async template => { + expect((await invoke({}, template)).persisted.run.runName).toBe("dev"); + }); +}); diff --git a/packages/app/test/manual-run-name.browser.test.ts b/packages/app/test/manual-run-name.browser.test.ts new file mode 100644 index 00000000..7c835a0c --- /dev/null +++ b/packages/app/test/manual-run-name.browser.test.ts @@ -0,0 +1,36 @@ +// @vitest-environment happy-dom +import { afterEach, expect, it, vi } from "vitest"; +import { jobRunPage } from "../src/ui"; +import { InvocationService, type Job } from "../src/job-domain"; + +declare const document: any; + +afterEach(() => { vi.unstubAllGlobals(); document.body.innerHTML = ""; }); + +it("displays the persisted manual name as the run title and breadcrumb", async () => { + const name = "GEN-2106 — Fix "; + const job = { id: "job-1", name: "dev", enabled: true, promptTemplate: "", runNameTemplate: "Template" } as Job; + let persisted: any; + const service = new InvocationService({ + getJob: async () => job, + findInvocation: async () => null, + insertInvocationAndRun: async (invocation, run) => { persisted = structuredClone(run); return true; }, + countActiveRuns: async () => 0, + markRunRunning: async () => { throw new Error("Unexpected start"); }, + }, async value => value); + await service.invoke(job.id, { source: "manual", name, triggerId: "manual-1", claimKey: "manual:issue", context: {} }); + vi.stubGlobal("fetch", vi.fn(async (input: unknown) => { + const url = String(input); + if (url.includes("/trace")) return Response.json({ items: [], nextCursor: null }); + if (url.includes("/api/v1/jobs/")) return Response.json(job); + return Response.json({ id: persisted.id, job_id: job.id, run_name: persisted.runName, state: "succeeded", created_at: persisted.createdAt }); + })); + const html = jobRunPage({ email: "owner@example.com" }, persisted.id); + document.body.innerHTML = html.match(/]*>([\s\S]*?)<\/body>/)?.[1] ?? ""; + const script = [...html.matchAll(/