Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/app/src/flow-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
}
Expand Down
4 changes: 3 additions & 1 deletion packages/app/src/job-domain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>;
/** Stable, source-owned key used to claim this occurrence exactly once. */
Expand Down Expand Up @@ -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.");
Expand Down
25 changes: 25 additions & 0 deletions packages/app/test/job-domain.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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" } } });
Expand Down
67 changes: 67 additions & 0 deletions packages/app/test/manual-invocation.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>, 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<string, unknown>) => {
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");
});
});
36 changes: 36 additions & 0 deletions packages/app/test/manual-run-name.browser.test.ts
Original file line number Diff line number Diff line change
@@ -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 <issue>";
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(/<body[^>]*>([\s\S]*?)<\/body>/)?.[1] ?? "";
const script = [...html.matchAll(/<script>([\s\S]*?)<\/script>/g)].at(-1)![1];
new Function(script)();
await vi.waitFor(() => expect(document.querySelector("h1")?.textContent).toBe(name));
expect(document.title).toBe(name + " — Factorize");
expect(document.querySelector('[aria-current="page"]')?.textContent).toBe(name);
expect(document.querySelector("h1 issue")).toBeNull();
});
7 changes: 5 additions & 2 deletions packages/app/test/postgres-invocation-repository.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,17 @@ import type { Invocation, JobRun } from "../src/job-domain";

const tenantId = "10000000-0000-4000-8000-000000000001";
const invocation: Invocation = { id: "20000000-0000-4000-8000-000000000001", jobId: "30000000-0000-4000-8000-000000000001", source: "manual", claimKey: "manual:one", triggerId: "40000000-0000-4000-8000-000000000001", context: { value: 1 }, createdAt: "2026-09-18T00:00:00.000Z" };
const run: JobRun = { id: "50000000-0000-4000-8000-000000000001", jobId: invocation.jobId, invocationId: invocation.id, state: "queued", encryptedPrompt: "ciphertext", createdAt: invocation.createdAt, updatedAt: invocation.createdAt };
const row = { invocation_id: invocation.id, job_id: invocation.jobId, source: invocation.source, claim_key: invocation.claimKey, trigger_id: invocation.triggerId, context: invocation.context, occurrence: null, invocation_created_at: new Date(invocation.createdAt), run_id: run.id, run_state: run.state, encrypted_prompt: run.encryptedPrompt, run_name: "", run_created_at: new Date(run.createdAt), run_updated_at: new Date(run.updatedAt), started_at: null };
const run: JobRun = { id: "50000000-0000-4000-8000-000000000001", jobId: invocation.jobId, invocationId: invocation.id, state: "queued", encryptedPrompt: "ciphertext", runName: "GEN-2106 — Issue title", createdAt: invocation.createdAt, updatedAt: invocation.createdAt };
const row = { invocation_id: invocation.id, job_id: invocation.jobId, source: invocation.source, claim_key: invocation.claimKey, trigger_id: invocation.triggerId, context: invocation.context, occurrence: null, invocation_created_at: new Date(invocation.createdAt), run_id: run.id, run_state: run.state, encrypted_prompt: run.encryptedPrompt, run_name: run.runName, run_created_at: new Date(run.createdAt), run_updated_at: new Date(run.updatedAt), started_at: null };

describe("InvocationRepository", () => {
it("creates invocation, run, and wake hint in one transaction", async () => {
const query = vi.fn().mockResolvedValueOnce({ rows: [], rowCount: 0 }).mockResolvedValueOnce({ rows: [{ id: invocation.id }], rowCount: 1 }).mockResolvedValueOnce({ rows: [], rowCount: 0 }).mockResolvedValueOnce({ rows: [], rowCount: 1 }).mockResolvedValueOnce({ rows: [], rowCount: 1 }).mockResolvedValueOnce({ rows: [row], rowCount: 1 });
const database = { pool: {}, transaction: (work: (client: { query: typeof query }) => unknown) => work({ query }) } as unknown as Database;
const result = await new InvocationRepository(database, tenantId).create(invocation, run);
expect(result.duplicate).toBe(false);
expect(result.run.runName).toBe(run.runName);
expect(query.mock.calls[3][1][6]).toBe(run.runName);
expect(query).toHaveBeenCalledTimes(6);
expect(query.mock.calls[0][1][0]).toBe(tenantId);
expect(query.mock.calls[4][0]).toContain("app.wake_hints");
Expand All @@ -25,6 +27,7 @@ describe("InvocationRepository", () => {
const database = { pool: {}, transaction: (work: (client: { query: typeof query }) => unknown) => work({ query }) } as unknown as Database;
const result = await new InvocationRepository(database, tenantId).create(invocation, run);
expect(result.duplicate).toBe(true);
expect(result.run.runName).toBe(run.runName);
expect(query).toHaveBeenCalledTimes(3);
});

Expand Down
Loading