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: 2 additions & 0 deletions packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4623,6 +4623,8 @@ export interface operations {
/** @enum {string} */
jobKind?: "Agent" | "Code";
enabled?: boolean;
runningCount?: number;
concurrencyLimit?: number;
provider?: string;
resource?: string;
}[];
Expand Down
5 changes: 3 additions & 2 deletions packages/api/src/flow-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,8 @@ export class ApiService {
await this.authorize("projects:read");
if (!await this.projects().get(projectId)) throw new ServiceError(404, "not_found", "Project not found");
const db = databaseFor(this.env), tenantId = this.auth.tenantId;
const jobs = await db.pool.query<any>(`SELECT j.id,j.name,j.enabled,j.execution_config,
const jobs = await db.pool.query<any>(`SELECT j.id,j.name,j.enabled,j.execution_config,j.concurrency_limit,
(SELECT count(*)::int FROM app.job_runs r WHERE r.tenant_id=j.tenant_id AND r.job_id=j.id AND r.state IN ('reserved','starting','running','blocked','stopping')) running_count,
COALESCE(jsonb_agg(jsonb_build_object('id',t.id,'kind',t.kind,'enabled',t.enabled,'config',CASE
WHEN t.kind='jobLifecycle' THEN jsonb_build_object('sourceJobIds',t.config->'sourceJobIds','sourceJobId',t.config->'sourceJobId','states',t.config->'states')
WHEN t.kind='jobIdle' THEN jsonb_build_object('sourceJobIds',t.config->'sourceJobIds')
Expand All @@ -275,7 +276,7 @@ export class ApiService {
FROM app.jobs j LEFT JOIN app.triggers t ON t.tenant_id=j.tenant_id AND t.job_id=j.id AND t.removed_at IS NULL
WHERE j.tenant_id=$1 AND j.project_id=$2 GROUP BY j.tenant_id,j.id ORDER BY j.id`, [tenantId, projectId]);
const ids = new Set<string>(jobs.rows.map(row => row.id));
const nodes: any[] = jobs.rows.map(row => ({ id: row.id, type: "job", label: row.name, jobKind: row.execution_config?.executionType === "code" ? "Code" : "Agent", enabled: row.enabled }));
const nodes: any[] = jobs.rows.map(row => ({ id: row.id, type: "job", label: row.name, jobKind: row.execution_config?.executionType === "code" ? "Code" : "Agent", enabled: row.enabled, runningCount: Number(row.running_count ?? 0), concurrencyLimit: row.concurrency_limit }));
const edges: any[] = [];
for (const job of jobs.rows) for (const trigger of job.triggers) {
if (trigger.kind === "jobLifecycle") for (const source of trigger.config?.sourceJobIds ?? (trigger.config?.sourceJobId ? [trigger.config.sourceJobId] : [])) if (ids.has(source)) edges.push({ id: `${trigger.id}:${source}:${job.id}`, source, target: job.id, label: (trigger.config?.states ?? []).map((state: string) => state === "succeeded" ? "Succeeded" : state === "failed" ? "Failed" : state === "stopped" ? "Stopped" : "Edited").join(", "), kind: "lifecycle", enabled: Boolean(job.enabled && trigger.enabled) });
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/project-graph-contracts.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { z } from "zod";

export const projectGraphResponse = z.object({
nodes: z.array(z.object({ id: z.string(), type: z.enum(["job", "webhook"]), label: z.string(), jobKind: z.enum(["Agent", "Code"]).optional(), enabled: z.boolean().optional(), provider: z.string().optional(), resource: z.string().optional() })),
nodes: z.array(z.object({ id: z.string(), type: z.enum(["job", "webhook"]), label: z.string(), jobKind: z.enum(["Agent", "Code"]).optional(), enabled: z.boolean().optional(), runningCount: z.number().int().nonnegative().optional(), concurrencyLimit: z.number().int().positive().optional(), provider: z.string().optional(), resource: z.string().optional() })),
edges: z.array(z.object({ id: z.string(), source: z.string(), target: z.string(), label: z.string(), kind: z.enum(["lifecycle", "idle", "manual", "webhook"]), enabled: z.boolean() })),
});
7 changes: 4 additions & 3 deletions packages/api/test/project-graph.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ describe("project graph", () => {
const source = "00000000-0000-4000-8000-000000000003", destination = "00000000-0000-4000-8000-000000000004", other = "00000000-0000-4000-8000-000000000005";
it("returns every project job and derives stable configured edges without secret config", async () => {
const jobs = [
{ id: source, name: "Build", enabled: true, execution_config: { agentKind: "codex" }, triggers: [] },
{ id: destination, name: "Deploy", enabled: false, execution_config: { executionType: "code", agentKind: "codex" }, triggers: [
{ id: source, name: "Build", enabled: true, concurrency_limit: 4, running_count: 2, execution_config: { agentKind: "codex" }, triggers: [] },
{ id: destination, name: "Deploy", enabled: false, concurrency_limit: 1, running_count: 0, execution_config: { executionType: "code", agentKind: "codex" }, triggers: [
{ id: "lifecycle", kind: "jobLifecycle", enabled: true, config: { sourceJobIds: [source, other], states: ["failed", "stopped", "edited"] } },
{ id: "idle", kind: "jobIdle", enabled: false, config: { sourceJobIds: [source] } },
{ id: "manual", kind: "manual", enabled: true, config: {} },
Expand All @@ -31,7 +31,8 @@ describe("project graph", () => {
const graph = await service.getProjectGraph(projectId);
expect(projectGraphResponse.safeParse(graph).success).toBe(true);
expect(graph.nodes).toHaveLength(3);
expect(graph.nodes.find(node => node.id === destination)).toMatchObject({ jobKind: "Code", enabled: false });
expect(graph.nodes.find(node => node.id === destination)).toMatchObject({ jobKind: "Code", enabled: false, runningCount: 0, concurrencyLimit: 1 });
expect(graph.nodes.find(node => node.id === source)).toMatchObject({ runningCount: 2, concurrencyLimit: 4 });
expect(graph.edges.map(edge => [edge.kind, edge.label, edge.enabled])).toEqual([
["lifecycle", "Failed, Stopped, Edited", false], ["idle", "Idle", false],
["webhook", "github · Repository 42", false], ["manual", "Manual", false],
Expand Down
25 changes: 21 additions & 4 deletions packages/app/src/features/projects/graph.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,11 @@ export function ProjectGraph({ projectId }: { projectId: string }) {
if (query.error) return <div role="alert" className="py-6">{query.error.message} <Button onClick={() => void query.refetch()}>Retry</Button></div>;
if (!query.data?.nodes.length) return <Card className="py-10 text-center"><p>No jobs in this project yet.</p></Card>;
const graph = query.data;
const edgeCounts = new Map<string, number>();
const edgeGroups = new Map<string, Graph["edges"]>();
for (const edge of graph.edges) {
const pair = JSON.stringify([edge.source, edge.target].sort());
edgeGroups.set(pair, [...(edgeGroups.get(pair) ?? []), edge]);
}
const zoom = (factor: number) => {
const next = Math.max(.3, Math.min(2.5, scale * factor));
const center = { x: layout.width / 2, y: layout.height / 2 };
Expand All @@ -60,10 +64,23 @@ export function ProjectGraph({ projectId }: { projectId: string }) {
</div>
<div className="overflow-hidden rounded-xl border border-stone-200 bg-stone-50 dark:border-slate-800 dark:bg-slate-950" onPointerDown={event => { if (event.target === event.currentTarget) { event.currentTarget.setPointerCapture(event.pointerId); setDrag({ x: event.clientX - offset.x, y: event.clientY - offset.y }); } }} onPointerMove={event => { if (drag) setOffset({ x: event.clientX - drag.x, y: event.clientY - drag.y }); }} onPointerUp={() => setDrag(null)}>
<svg role="img" aria-label={`Workflow graph with ${graph.nodes.filter(node => node.type === "job").length} jobs and ${graph.edges.length} connections`} viewBox={`0 0 ${layout.width} ${layout.height}`} className="h-[min(68vh,700px)] min-h-[360px] w-full touch-none" preserveAspectRatio="xMidYMid meet">
<defs><marker id="graph-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M 0 0 L 10 5 L 0 10 z" fill="currentColor" /></marker></defs>
<defs><marker id="graph-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M 0 0 L 10 5 L 0 10 z" fill="context-stroke" /></marker><marker id="graph-arrow-start" viewBox="0 0 10 10" refX="1" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M 0 0 L 10 5 L 0 10 z" fill="context-stroke" /></marker></defs>
<g transform={`translate(${offset.x} ${offset.y}) scale(${scale})`}>
{graph.edges.map(edge => { const from = layout.positions.get(edge.source), to = layout.positions.get(edge.target); if (!from || !to) return null; const pair = `${edge.source}:${edge.target}`, count = edgeCounts.get(pair) ?? 0; edgeCounts.set(pair, count + 1); const bend = count * 18; const muted = !edge.enabled, startX = from.x + (graph.nodes.find(node => node.id === edge.source)?.type === "webhook" ? 145 : 170); return <g key={edge.id} onClick={() => setSelectedEdge(edge)} className="cursor-pointer" role="button" tabIndex={0} aria-label={`${edge.label} connection`} onKeyDown={event => { if (event.key === "Enter" || event.key === " ") setSelectedEdge(edge); }}><path d={`M ${startX} ${from.y + 35} Q ${(from.x + to.x) / 2 + 65 + bend} ${(from.y + to.y) / 2 + bend} ${to.x} ${to.y + 35}`} fill="none" stroke={muted ? "#a8a29e" : edge.kind === "manual" ? "#7c3aed" : edge.kind === "webhook" ? "#0284c7" : "#0f766e"} strokeWidth={selectedEdge?.id === edge.id ? 4 : 2} strokeDasharray={muted ? "6 5" : undefined} markerEnd="url(#graph-arrow)"/><text x={(from.x + to.x) / 2 + 50 + bend} y={(from.y + to.y) / 2 - 5 + bend} textAnchor="middle" className="fill-slate-700 text-[12px] dark:fill-slate-200">{edge.label}</text></g>; })}
{graph.nodes.map(node => { const p = layout.positions.get(node.id)!; const isJob = node.type === "job", muted = isJob && !node.enabled; return <g key={node.id} transform={`translate(${p.x} ${p.y})`} className={isJob ? "cursor-pointer" : ""} role={isJob ? "link" : undefined} tabIndex={isJob ? 0 : undefined} aria-label={isJob ? `${node.jobKind}: ${node.label}${muted ? ", disabled" : ""}` : node.label} onClick={() => isJob && void navigate({ to: "/jobs/$jobId", params: { jobId: node.id } })} onKeyDown={event => { if (isJob && (event.key === "Enter" || event.key === " ")) void navigate({ to: "/jobs/$jobId", params: { jobId: node.id } }); }}><rect width={isJob ? 170 : 145} height="70" rx="12" fill={muted ? "#e7e5e4" : isJob ? "#fff" : "#e0f2fe"} stroke={muted ? "#a8a29e" : isJob ? "#0f766e" : "#0284c7"} strokeWidth="2" strokeDasharray={muted ? "5 4" : undefined}/><text x="14" y="27" className="fill-slate-800 text-[12px] font-semibold dark:fill-slate-900">{isJob ? node.jobKind : node.provider}</text><text x="14" y="49" className="fill-slate-700 text-[12px] dark:fill-slate-800">{node.label.length > 19 ? node.label.slice(0, 18) + "…" : node.label}</text></g>; })}
{[...edgeGroups].map(([pair, edges]) => {
const [leftId, rightId] = JSON.parse(pair) as [string, string], left = layout.positions.get(leftId), right = layout.positions.get(rightId);
if (!left || !right) return null;
const leftNode = graph.nodes.find(node => node.id === leftId), rightNode = graph.nodes.find(node => node.id === rightId);
const leftWidth = leftNode?.type === "webhook" ? 145 : 170, rightWidth = rightNode?.type === "webhook" ? 145 : 170;
const leftIsLeft = left.x <= right.x, from = leftIsLeft ? left : right, to = leftIsLeft ? right : left;
const fromId = leftIsLeft ? leftId : rightId, toId = leftIsLeft ? rightId : leftId;
const startWidth = leftIsLeft ? leftWidth : rightWidth, endX = to.x;
const forward = edges.some(edge => edge.source === fromId && edge.target === toId), reverse = edges.some(edge => edge.source === toId && edge.target === fromId);
const muted = edges.every(edge => !edge.enabled), label = [...new Set(edges.map(edge => edge.label).filter(Boolean))].join(" · ");
const stroke = muted ? "#a8a29e" : edges.length === 1 && edges[0].kind === "manual" ? "#7c3aed" : edges.length === 1 && edges[0].kind === "webhook" ? "#0284c7" : "#0f766e";
const groupId = edges.map(edge => edge.id).sort().join("|");
return <g key={groupId} onClick={() => setSelectedEdge(edges[0])} className="cursor-pointer" role="button" tabIndex={0} aria-label={`${label || "Workflow"} connection${edges.length > 1 ? `, ${edges.length} triggers` : ""}`} onKeyDown={event => { if (event.key === "Enter" || event.key === " ") setSelectedEdge(edges[0]); }}><path d={`M ${from.x + startWidth} ${from.y + 35} Q ${(from.x + startWidth + endX) / 2} ${(from.y + to.y) / 2 + 35} ${endX} ${to.y + 35}`} fill="none" stroke={stroke} strokeWidth={selectedEdge && edges.some(edge => edge.id === selectedEdge.id) ? 4 : 2} strokeDasharray={muted ? "6 5" : undefined} markerStart={reverse ? "url(#graph-arrow-start)" : undefined} markerEnd={forward ? "url(#graph-arrow)" : undefined}/><text x={(from.x + startWidth + endX) / 2} y={(from.y + to.y) / 2 + 28} textAnchor="middle" className="fill-slate-700 text-[12px] dark:fill-slate-200">{label}</text></g>;
})}
{graph.nodes.map(node => { const p = layout.positions.get(node.id)!; const isJob = node.type === "job", muted = isJob && !node.enabled, active = isJob && (node.runningCount ?? 0) > 0, height = isJob ? 92 : 70; return <g key={node.id} transform={`translate(${p.x} ${p.y})`} className={isJob ? "cursor-pointer" : ""} role={isJob ? "link" : undefined} tabIndex={isJob ? 0 : undefined} aria-label={isJob ? `${node.jobKind}: ${node.label}${muted ? ", disabled" : ""}${active ? `, running${node.concurrencyLimit && node.concurrencyLimit > 1 ? `, ${node.runningCount}/${node.concurrencyLimit} active` : ""}` : ", not running"}` : node.label} onClick={() => isJob && void navigate({ to: "/jobs/$jobId", params: { jobId: node.id } })} onKeyDown={event => { if (isJob && (event.key === "Enter" || event.key === " ")) void navigate({ to: "/jobs/$jobId", params: { jobId: node.id } }); }}><rect width={isJob ? 170 : 145} height={height} rx="12" fill={muted ? "#e7e5e4" : isJob ? "#fff" : "#e0f2fe"} stroke={muted ? "#a8a29e" : isJob ? "#0f766e" : "#0284c7"} strokeWidth="2" strokeDasharray={muted ? "5 4" : undefined}/><text x="14" y="27" className="fill-slate-800 text-[12px] font-semibold dark:fill-slate-900">{isJob ? node.jobKind : node.provider}</text><text x="14" y="49" className="fill-slate-700 text-[12px] dark:fill-slate-800">{node.label.length > 19 ? node.label.slice(0, 18) + "…" : node.label}</text>{isJob && <><circle cx="19" cy="70" r="5" fill={active ? "#059669" : "#a8a29e"} className={active ? "motion-safe:animate-pulse" : undefined}/><text x="30" y="74" className={`text-[11px] font-medium ${active ? "fill-emerald-700" : "fill-slate-500"}`}>{active ? `Running${node.concurrencyLimit && node.concurrencyLimit > 1 ? ` · ${node.runningCount}/${node.concurrencyLimit}` : ""}` : "Not running"}</text></>}</g>; })}
</g>
</svg>
</div>
Expand Down
14 changes: 11 additions & 3 deletions packages/app/test/jobs.browser.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -85,17 +85,25 @@ test("project graph preserves disabled and multiple connections and navigates to
await page.route("**/api/v1/job-summaries?**", route => route.fulfill({ json: { items: [], nextCursor: null } }));
await page.route(`**/api/v1/projects/${projectId}/graph`, route => route.fulfill({ json: {
nodes: [
{ id: jobId, type: "job", label: "Build", jobKind: "Agent", enabled: true },
{ id: secondJob, type: "job", label: "Deploy", jobKind: "Code", enabled: false },
{ id: jobId, type: "job", label: "Build", jobKind: "Agent", enabled: true, runningCount: 2, concurrencyLimit: 4 },
{ id: secondJob, type: "job", label: "Deploy", jobKind: "Code", enabled: false, runningCount: 0, concurrencyLimit: 1 },
], edges: [
{ id: "lifecycle-a", source: jobId, target: secondJob, label: "Failed, Stopped", kind: "lifecycle", enabled: false },
{ id: "idle-a", source: jobId, target: secondJob, label: "Idle", kind: "idle", enabled: false },
{ id: "manual-a", source: jobId, target: secondJob, label: "Manual", kind: "manual", enabled: false },
{ id: "lifecycle-reverse", source: secondJob, target: jobId, label: "Succeeded", kind: "lifecycle", enabled: true },
],
} }));
await page.goto(origin + `/projects/${projectId}`);
await page.getByRole("button", { name: "Graph", exact: true }).click();
await page.getByRole("img", { name: /2 jobs and 3 connections/ }).waitFor();
await page.getByRole("img", { name: /2 jobs and 4 connections/ }).waitFor();
await page.getByText("Running · 2/4", { exact: true }).waitFor();
await page.getByText("Not running", { exact: true }).waitFor();
const combined = page.getByRole("button", { name: /Failed, Stopped · Idle · Manual · Succeeded connection, 4 triggers/ });
await combined.waitFor();
assert.equal(await page.getByRole("button", { name: /connection, 4 triggers/ }).count(), 1);
assert.equal(await combined.locator("path").getAttribute("marker-start"), "url(#graph-arrow-start)");
assert.equal(await combined.locator("path").getAttribute("marker-end"), "url(#graph-arrow)");
await page.getByRole("link", { name: "Code: Deploy, disabled" }).click();
await page.waitForURL(new RegExp(`/jobs/${secondJob}`));
await context.close();
Expand Down
8 changes: 8 additions & 0 deletions packages/docs/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5810,6 +5810,14 @@ paths:
- Code
enabled:
type: boolean
runningCount:
type: integer
minimum: 0
maximum: 9007199254740991
concurrencyLimit:
type: integer
exclusiveMinimum: 0
maximum: 9007199254740991
provider:
type: string
resource:
Expand Down
Loading