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
3 changes: 2 additions & 1 deletion packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1039,7 +1039,7 @@ export interface paths {
};
/**
* Get a project's workflow graph
* @description Returns every job in the project and configured lifecycle, idle, manual invocation permission, and external webhook source connections. Connections are derived from executable trigger configuration and current permission grants. Only safe webhook provider and resource metadata is returned.
* @description Returns every job in the project and configured lifecycle, idle, manual invocation permission, and external webhook source connections. Connections are derived from executable trigger configuration and current permission grants. Webhook edge labels are short readable provider or event names; details may include configured technical resource identifiers as secondary context.
*
* Requires the projects:read scope.
*
Expand Down Expand Up @@ -4635,6 +4635,7 @@ export interface operations {
source: string;
target: string;
label: string;
details?: string;
/** @enum {string} */
kind: "lifecycle" | "idle" | "manual" | "webhook";
enabled: boolean;
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/api-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -662,7 +662,7 @@ export const API_ROUTES: RouteContract[] = [
),
route("POST", "/api/v1/projects", "flows:write", { summary: "Create project", responses: { "201": { description: "Created", content: { "application/json": { schema: jsonSchema(projectResponse, "output") } } } } }, (service, { body }) => service.createProject(body), { body: projectInput }),
route("GET", "/api/v1/projects/{projectId}", "flows:read", { summary: "Get project", responses: { "200": { description: "Project", content: { "application/json": { schema: jsonSchema(projectResponse, "output") } } } } }, (service, { params }) => service.getProject(params.projectId)),
route("GET", "/api/v1/projects/{projectId}/graph", "flows:read", { summary: "Get a project's workflow graph", description: "Returns every job in the project and configured lifecycle, idle, manual invocation permission, and external webhook source connections. Connections are derived from executable trigger configuration and current permission grants. Only safe webhook provider and resource metadata is returned.", responses: { "200": { description: "Complete project graph", content: { "application/json": { schema: jsonSchema(projectGraphResponse, "output") } } } } }, (service, { params }) => service.getProjectGraph(params.projectId)),
route("GET", "/api/v1/projects/{projectId}/graph", "flows:read", { summary: "Get a project's workflow graph", description: "Returns every job in the project and configured lifecycle, idle, manual invocation permission, and external webhook source connections. Connections are derived from executable trigger configuration and current permission grants. Webhook edge labels are short readable provider or event names; details may include configured technical resource identifiers as secondary context.", responses: { "200": { description: "Complete project graph", content: { "application/json": { schema: jsonSchema(projectGraphResponse, "output") } } } } }, (service, { params }) => service.getProjectGraph(params.projectId)),
route("PUT", "/api/v1/projects/{projectId}", "flows:write", { summary: "Update project", responses: { "200": { description: "Updated", content: { "application/json": { schema: jsonSchema(projectResponse, "output") } } } } }, (service, { params, body }) => service.updateProject(params.projectId, body), { body: projectInput }),
route("DELETE", "/api/v1/projects/{projectId}", "flows:write", { summary: "Delete empty project", responses: { "200": { description: "Deleted" } } }, (service, { params }) => service.deleteProject(params.projectId)),
route("GET", "/api/v1/skills", "skills:read", { summary: "Search global skills", responses: { "200": { description: "Skills", content: { "application/json": { schema: jsonSchema(skillPage, "output") } } } } }, (service, { query }) => service.listSkills(query), { query: skillQuery }),
Expand Down
23 changes: 17 additions & 6 deletions packages/api/src/flow-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ import { RunRepository } from "./postgres/run-repository";
import { safeDiagnosticText } from "./harness-diagnostics";
import { skillInput, skillUpdateInput, skillPage, skillResponse, skillJobsResponse, previewSkillInput, composePrompt } from "./skills";

const PROJECT_GRAPH_LABEL_MAX_CHARS = 24;

export class ServiceError extends Error {
constructor(public status: number, public code: string, message: string) { super(message); }
}
Expand Down Expand Up @@ -281,19 +283,28 @@ export class ApiService {
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, runningCount: Number(row.running_count ?? 0), concurrencyLimit: row.concurrency_limit }));
const edges: any[] = [];
const shortLabel = (value: string) => value.length > PROJECT_GRAPH_LABEL_MAX_CHARS ? `${value.slice(0, PROJECT_GRAPH_LABEL_MAX_CHARS - 1).trimEnd()}…` : value;
const providerLabels: Record<string, string> = { linear: "Linear", clickup: "ClickUp", github: "GitHub", cloudflareTail: "Cloudflare Tail" };
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) });
if (trigger.kind === "jobIdle") for (const source of trigger.config?.sourceJobIds ?? []) if (ids.has(source)) edges.push({ id: `${trigger.id}:${source}:${job.id}`, source, target: job.id, label: "Idle", kind: "idle", enabled: Boolean(job.enabled && trigger.enabled) });
if (trigger.kind === "jobLifecycle") for (const source of trigger.config?.sourceJobIds ?? (trigger.config?.sourceJobId ? [trigger.config.sourceJobId] : [])) if (ids.has(source)) {
const states = (trigger.config?.states ?? []) as string[];
const fullLabel = states.map(state => ({ succeeded: "Succeeded", failed: "Failed", stopped: "Stopped", edited: "Edited" } as Record<string, string>)[state] ?? state).join(", ") || "Lifecycle";
edges.push({ id: `${trigger.id}:${source}:${job.id}`, source, target: job.id, label: shortLabel(fullLabel), details: fullLabel, kind: "lifecycle", enabled: Boolean(job.enabled && trigger.enabled) });
}
if (trigger.kind === "jobIdle") for (const source of trigger.config?.sourceJobIds ?? []) if (ids.has(source)) edges.push({ id: `${trigger.id}:${source}:${job.id}`, source, target: job.id, label: "Idle", details: "Runs when the source job becomes idle", kind: "idle", enabled: Boolean(job.enabled && trigger.enabled) });
if (trigger.kind === "webhook") {
const config = trigger.config ?? {}, provider = String(config.provider ?? "webhook").slice(0, 50);
const config = trigger.config ?? {}, provider = String(config.provider ?? "webhook").slice(0, 50), displayProvider = providerLabels[provider] ?? "Webhook";
const resource = (provider === "linear" ? String(config.projectId ?? "Project") : provider === "clickup" ? String(config.listId ?? "List") : provider === "github" ? String(config.repositoryId ? `Repository ${config.repositoryId}` : config.event ?? "Repository") : provider === "cloudflareTail" ? "Tail" : "External source").slice(0, 120);
const source = `webhook:${provider}:${resource}`;
if (!nodes.some(node => node.id === source)) nodes.push({ id: source, type: "webhook", label: `${provider} · ${resource}`, provider, resource });
edges.push({ id: `${trigger.id}:${source}:${job.id}`, source, target: job.id, label: `${provider} · ${resource}`, kind: "webhook", enabled: Boolean(job.enabled && trigger.enabled) });
const event = String(config.event ?? "").toLowerCase();
const label = provider === "github" && ["pull_request", "pull_request_target"].includes(event) ? "GitHub PR" : provider === "github" && event === "issues" ? "GitHub Issue" : provider === "github" && event === "push" ? "GitHub Push" : displayProvider;
const details = [displayProvider, [config.event, config.action].filter(Boolean).join(" "), resource && !["Tail", "External source"].includes(resource) ? resource : ""].filter(Boolean).join(" · ");
if (!nodes.some(node => node.id === source)) nodes.push({ id: source, type: "webhook", label: displayProvider, provider, resource });
edges.push({ id: `${trigger.id}:${source}:${job.id}`, source, target: job.id, label: shortLabel(label), details, kind: "webhook", enabled: Boolean(job.enabled && trigger.enabled) });
}
}
const grants = await db.pool.query<any>(`SELECT p.source_job_id,p.destination_job_id FROM app.manual_invocation_permissions p JOIN app.jobs s ON s.tenant_id=p.tenant_id AND s.id=p.source_job_id JOIN app.jobs d ON d.tenant_id=p.tenant_id AND d.id=p.destination_job_id WHERE p.tenant_id=$1 AND s.project_id=$2 AND d.project_id=$2 ORDER BY p.source_job_id,p.destination_job_id`, [tenantId, projectId]);
for (const grant of grants.rows) edges.push({ id: `manual:${grant.source_job_id}:${grant.destination_job_id}`, source: grant.source_job_id, target: grant.destination_job_id, label: "Manual", kind: "manual", enabled: Boolean(jobs.rows.find(row => row.id === grant.source_job_id)?.enabled && jobs.rows.find(row => row.id === grant.destination_job_id)?.enabled) });
for (const grant of grants.rows) edges.push({ id: `manual:${grant.source_job_id}:${grant.destination_job_id}`, source: grant.source_job_id, target: grant.destination_job_id, label: "Manual", details: "Manual invocation permission", kind: "manual", enabled: Boolean(jobs.rows.find(row => row.id === grant.source_job_id)?.enabled && jobs.rows.find(row => row.id === grant.destination_job_id)?.enabled) });
return { nodes, edges };
}
async createProject(input: { name: string; description?: string }) { await this.authorize("projects:write"); try { return await this.projects().create(input.name, input.description); } catch (error: any) { if (error?.code === "23505") throw new ServiceError(409, "conflict", "A project with this name already exists"); throw error; } }
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
Expand Up @@ -2,5 +2,5 @@ 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(), 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() })),
edges: z.array(z.object({ id: z.string(), source: z.string(), target: z.string(), label: z.string(), details: z.string().optional(), kind: z.enum(["lifecycle", "idle", "manual", "webhook"]), enabled: z.boolean() })),
});
1 change: 1 addition & 0 deletions packages/api/test/api-boundary.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,7 @@ describe("Worker OpenAPI request/response boundaries", () => {
await assertResponse(await request("GET", path + "?limit=101"), "GET", path, 400);
await assertResponse(await request("GET", path + "?cursor=broken"), "GET", path, 400);
await assertResponse(await request("GET", path + "?sort=title&cursor=00000000-0000-4000-8000-000000000001"), "GET", path, 400);
await assertResponse(await request("GET", path + "?sort=title&cursor=00000000-0000-4000-8000-000000000001"), "GET", path, 400);
await assertResponse(await request("GET", path, undefined, { auth: { ...auth, scopes: ["runs:read"] } }), "GET", path, 403);
}
expect(summaries).toHaveBeenCalledWith({ limit: 2, q: "Review", enabled: "true" }, true);
Expand Down
36 changes: 34 additions & 2 deletions packages/api/test/project-graph.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ describe("project graph", () => {
{ id: "manual", kind: "manual", enabled: true, config: {} },
{ id: "schedule", kind: "schedule", enabled: true, config: {} },
{ id: "hook", kind: "webhook", enabled: true, config: { provider: "github", repositoryId: 42, signingSecret: "never-return-this" } },
{ id: "hook-copy", kind: "webhook", enabled: true, config: { provider: "github", repositoryId: 42 } },
{ id: "linear", kind: "webhook", enabled: true, config: { provider: "linear", projectId: "00000000-0000-4000-8000-000000000099" } },
{ id: "clickup", kind: "webhook", enabled: true, config: { provider: "clickup", listId: "123456789" } },
{ id: "github-pr", kind: "webhook", enabled: true, config: { provider: "github", repositoryId: 42, event: "pull_request" } },
{ id: "tail", kind: "webhook", enabled: true, config: { provider: "cloudflareTail", integrationId: "tail-secret-ish-id" } },
] },
];
const query = vi.fn(async (sql: string, values: unknown[]) => {
Expand All @@ -30,18 +35,45 @@ describe("project graph", () => {
vi.spyOn(service as any, "projects").mockReturnValue({ get: async (id: string) => id === projectId ? { id } : null });
const graph = await service.getProjectGraph(projectId);
expect(projectGraphResponse.safeParse(graph).success).toBe(true);
expect(graph.nodes).toHaveLength(3);
expect(graph.nodes).toHaveLength(6);
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],
["webhook", "GitHub", false], ["webhook", "GitHub", false], ["webhook", "Linear", false], ["webhook", "ClickUp", false], ["webhook", "GitHub PR", false], ["webhook", "Cloudflare Tail", false], ["manual", "Manual", false],
]);
const duplicateLabels = graph.edges.filter(edge => edge.label === "GitHub");
expect(duplicateLabels).toHaveLength(2);
expect(new Set(duplicateLabels.map(edge => edge.id)).size).toBe(2);
expect(new Set(duplicateLabels.map(edge => edge.source))).toEqual(new Set(["webhook:github:Repository 42"]));
expect(graph.edges[0].details).toBe("Failed, Stopped, Edited");
expect(graph.nodes.find(node => node.type === "webhook" && node.provider === "linear")).toMatchObject({ label: "Linear", resource: "00000000-0000-4000-8000-000000000099" });
expect(graph.nodes.find(node => node.type === "webhook" && node.provider === "clickup")).toMatchObject({ label: "ClickUp", resource: "123456789" });
expect(graph.edges.find(edge => edge.label === "Linear")?.label).not.toContain("00000000-0000-4000-8000-000000000099");
expect(graph.edges.find(edge => edge.label === "ClickUp")?.label).not.toContain("123456789");
expect(graph.edges.every(edge => edge.label.length <= 24)).toBe(true);
expect(graph.edges.some(edge => edge.source === other)).toBe(false);
expect(JSON.stringify(graph)).not.toContain("never-return-this");
expect(query.mock.calls[0][0]).not.toContain("'config',t.config");
expect(query).toHaveBeenCalledTimes(2);
});
it("keeps lifecycle states and long names bounded while using readable provider fallbacks", async () => {
const longStates = ["succeeded", "failed", "stopped", "edited"];
const rows = [{ id: source, name: "Build", enabled: true, execution_config: {}, triggers: [] }, { id: destination, name: "Deploy", enabled: true, execution_config: {}, triggers: [
{ id: "all-states", kind: "jobLifecycle", enabled: true, config: { sourceJobIds: [source], states: longStates } },
{ id: "missing-provider", kind: "webhook", enabled: true, config: { projectId: "opaque-resource" } },
{ id: "long-event", kind: "webhook", enabled: true, config: { provider: "github", event: "pull_request_target" } },
] }];
const query = vi.fn(async (sql: string) => sql.includes("FROM app.jobs j LEFT JOIN app.triggers") ? { rows, rowCount: rows.length } : { rows: [], rowCount: 0 });
const service = new ApiService({ DATABASE: { pool: { query } } } as any, { tenantId, userId: "owner", sessionVersion: 1, scopes: ["projects:read"] } as any);
vi.spyOn(service as any, "authorize").mockResolvedValue(undefined);
vi.spyOn(service as any, "projects").mockReturnValue({ get: async () => ({ id: projectId }) });
const graph = await service.getProjectGraph(projectId);
expect(graph.edges.map(edge => edge.label)).toEqual(["Succeeded, Failed, Stop…", "Webhook", "GitHub PR"]);
expect(graph.edges[0].details).toBe("Succeeded, Failed, Stopped, Edited");
expect(graph.nodes.find(node => node.type === "webhook")).toMatchObject({ label: "Webhook", provider: "webhook" });
expect(graph.edges.every(edge => edge.label.length <= 24)).toBe(true);
});
it("rejects missing or cross-tenant projects before reading jobs", async () => {
const query = vi.fn();
const service = new ApiService({ DATABASE: { pool: { query } } } as any, { tenantId, userId: "owner", sessionVersion: 1, scopes: ["projects:read"] } as any);
Expand Down
2 changes: 1 addition & 1 deletion packages/app/src/features/projects/graph-flow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { RunStatusLabel } from "../../shared/ui";
import { routeAroundNodes, roundedPath, type GraphRect, type GraphSide } from "./graph-geometry";

export type GraphNode = { id: string; type: string; label: string; provider?: string; jobKind?: string; enabled?: boolean; runningCount?: number; concurrencyLimit?: number };
export type GraphConnection = { id: string; source: string; target: string; label: string; kind: string; enabled: boolean };
export type GraphConnection = { id: string; source: string; target: string; label: string; details?: string; kind: string; enabled: boolean };
type GraphNodeData = { graphNode: GraphNode; onOpen: (id: string) => void };
type GraphEdgeData = { connections: GraphConnection[]; labels: string[]; count: number; muted: boolean; reverse: boolean; selected: boolean; onSelect: (edge: GraphConnection) => void; onGroup: (edges: GraphConnection[], trigger: HTMLButtonElement) => void; route: ReturnType<typeof routeAroundNodes> };
type FlowNode = Node<GraphNodeData, "job" | "webhook" | "bounds">;
Expand Down
Loading
Loading