From e6806fbcbc2b68a946e51bf52b29920cb4d3cf76 Mon Sep 17 00:00:00 2001 From: Brendan Date: Thu, 17 Sep 2026 00:55:06 +0000 Subject: [PATCH] Add ClickUp task trigger integration --- README.md | 7 ++ packages/app/.dev.vars.example | 2 + packages/app/src/clickup.ts | 22 +++++++ packages/app/src/flow-schemas.ts | 1 + packages/app/src/index.ts | 44 +++++++++++++ packages/app/src/tenant.ts | 66 ++++++++++++++++++- packages/app/src/trigger-availability.ts | 5 +- packages/app/src/trigger-context.ts | 8 +++ packages/app/src/types.ts | 4 +- packages/app/src/ui.ts | 27 +++++--- packages/app/src/webhook-trigger.ts | 7 +- packages/app/test/clickup.test.ts | 16 +++++ .../app/test/trigger-availability.test.ts | 8 +-- packages/app/test/webhook-trigger.test.ts | 9 ++- 14 files changed, 204 insertions(+), 22 deletions(-) create mode 100644 packages/app/src/clickup.ts create mode 100644 packages/app/test/clickup.test.ts diff --git a/README.md b/README.md index 7eca1ebc..956f81f2 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,7 @@ For a headless machine, authenticate first with `npx wrangler login --device --b - A Cloudflare account with Workers enabled. - A Linear OAuth application with webhooks enabled. +- Optional: a ClickUp OAuth application for ClickUp task triggers. - An exe.dev VM with Herdr and your coding agent (such as Codex or Claude) installed. - An exe.dev HTTPS API token restricted to the exact SSH destination Factorize will use, for example `ssh exedev@my-vm`. @@ -90,6 +91,10 @@ Use authorization-code OAuth and enable **Webhooks** on the OAuth application. C After changing the webhook settings, re-authorize existing workspaces so Linear creates a fresh workspace subscription. +## Configure ClickUp + +Create a ClickUp OAuth application with the callback URL `https://your-domain.example/auth/clickup/callback`, then store its client ID and secret in `CLICKUP_CLIENT_ID` and `CLICKUP_CLIENT_SECRET`. Connecting ClickUp from Settings registers the signed task webhook automatically. ClickUp triggers can filter a list by status, tag, assignee, or creator; all configured rules must match. + ## Create a Job 1. Sign in with Linear. @@ -107,6 +112,8 @@ Cloudflare Worker failures can also start Jobs through the separately deployable | `LINEAR_CLIENT_ID` | Linear OAuth client ID | | `LINEAR_CLIENT_SECRET` | Linear OAuth client secret | | `LINEAR_WEBHOOK_SIGNING_SECRET` | Verifies Linear webhook signatures | +| `CLICKUP_CLIENT_ID` | ClickUp OAuth client ID | +| `CLICKUP_CLIENT_SECRET` | ClickUp OAuth client secret; ClickUp also uses a per-installation webhook secret stored encrypted by Factorize | | `CREDENTIAL_ENCRYPTION_KEY` | Base64-encoded 32-byte key for encrypted credentials | | `SESSION_SIGNING_SECRET` | Independent secret for signed browser sessions | | `APP_ORIGIN` | Public Worker origin, configured in `packages/app/wrangler.jsonc` | diff --git a/packages/app/.dev.vars.example b/packages/app/.dev.vars.example index 7f050b7e..0cee53a5 100644 --- a/packages/app/.dev.vars.example +++ b/packages/app/.dev.vars.example @@ -3,6 +3,8 @@ LINEAR_CLIENT_ID= LINEAR_CLIENT_SECRET= # Copy this once from the Webhooks section of the Linear OAuth app settings. LINEAR_WEBHOOK_SIGNING_SECRET= +CLICKUP_CLIENT_ID= +CLICKUP_CLIENT_SECRET= # base64-encoded 32 random bytes: openssl rand -base64 32 CREDENTIAL_ENCRYPTION_KEY= # a separate random value for signed browser sessions diff --git a/packages/app/src/clickup.ts b/packages/app/src/clickup.ts new file mode 100644 index 00000000..f117d2a1 --- /dev/null +++ b/packages/app/src/clickup.ts @@ -0,0 +1,22 @@ +import type { MatchRule } from "./types"; + +export type ClickUpTask = Record & { id?: string; list?: { id?: string }; status?: { status?: string }; assignees?: Array<{ id?: number | string }>; tags?: Array<{ name?: string }>; creator?: { id?: number | string } }; + +export function matchingClickUpTask(task: ClickUpTask, listId: string, rules: MatchRule[]): boolean { + if (!task.id || String(task.list?.id ?? "") !== listId || !rules.length) return false; + return rules.every(rule => { + if (rule.type === "status") return task.status?.status === rule.targetId; + if (rule.type === "label") return task.tags?.some(tag => tag.name === rule.targetId) === true; + if (rule.type === "creator") return String(task.creator?.id ?? "") === rule.targetId; + return task.assignees?.some(person => String(person.id) === rule.targetId) === true; + }); +} + +export const clickUpHeaders = (token: string) => ({ Authorization: token, "Content-Type": "application/json" }); + +export async function clickUpJson(token: string, path: string): Promise { + const response = await fetch(`https://api.clickup.com/api/v2${path}`, { headers: clickUpHeaders(token) }); + const body = await response.json().catch(() => ({})) as any; + if (!response.ok) throw new Error(body.err ?? body.error ?? `ClickUp request failed (${response.status})`); + return body; +} diff --git a/packages/app/src/flow-schemas.ts b/packages/app/src/flow-schemas.ts index 6e40f866..ab51b910 100644 --- a/packages/app/src/flow-schemas.ts +++ b/packages/app/src/flow-schemas.ts @@ -16,6 +16,7 @@ export const runIdSchema = z.object({ runId: z.string().min(1) }); const webhookCommonSchema = z.object({ handlerCode: z.string().max(16_384).optional() }); export const webhookTriggerConfigSchema = z.discriminatedUnion("provider", [ webhookCommonSchema.extend({ provider: z.literal("linear"), projectId: z.string().min(1), matchRules: z.array(matchRuleSchema).min(1) }).strict(), + webhookCommonSchema.extend({ provider: z.literal("clickup"), listId: z.string().min(1), matchRules: z.array(matchRuleSchema).min(1) }).strict(), webhookCommonSchema.extend({ provider: z.literal("github"), installationId: z.number().int().positive(), repositoryId: z.number().int().positive(), event: z.string().min(1).default("pull_request"), action: z.string().min(1).default("dequeued") }).strict(), webhookCommonSchema.extend({ provider: z.literal("cloudflareTail"), integrationId: z.string().min(1) }).strict(), ]); diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index e57d9697..50be3435 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -141,6 +141,35 @@ app.post("/auth/logout", (c) => { return c.redirect("/"); }); +app.get("/auth/clickup", async (c) => { + const session = await owner(c); if (!session) return c.redirect("/auth/linear"); + if (!c.env.CLICKUP_CLIENT_ID) return c.text("ClickUp OAuth is not configured", 503); + const state = await signSession({ ...session, exp: Math.floor(Date.now() / 1000) + 600 }, c.env.SESSION_SIGNING_SECRET); + setCookie(c, "clickup_oauth_state", state, { httpOnly: true, secure: new URL(c.env.APP_ORIGIN).protocol === "https:", sameSite: "Lax", path: "/auth/clickup", maxAge: 600 }); + const redirect = new URL("https://app.clickup.com/api"); + redirect.searchParams.set("client_id", c.env.CLICKUP_CLIENT_ID); + redirect.searchParams.set("redirect_uri", `${c.env.APP_ORIGIN}/auth/clickup/callback`); + redirect.searchParams.set("state", state); + return c.redirect(redirect.toString()); +}); + +app.get("/auth/clickup/callback", async (c) => { + const session = await owner(c), code = c.req.query("code"), state = c.req.query("state"); + if (!session || !code || !state || state !== getCookie(c, "clickup_oauth_state") || !c.env.CLICKUP_CLIENT_ID || !c.env.CLICKUP_CLIENT_SECRET) return c.text("Invalid ClickUp OAuth state", 400); + const tokenResponse = await fetch("https://api.clickup.com/api/v2/oauth/token", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ client_id: c.env.CLICKUP_CLIENT_ID, client_secret: c.env.CLICKUP_CLIENT_SECRET, code }) }); + const tokens = await tokenResponse.json() as { access_token?: string }; + if (!tokenResponse.ok || !tokens.access_token) return c.text("ClickUp token exchange failed", 502); + const teamsResponse = await fetch("https://api.clickup.com/api/v2/team", { headers: { Authorization: tokens.access_token } }); + const teams = await teamsResponse.json() as any, team = teams.teams?.[0]; + if (!teamsResponse.ok || !team?.id) return c.text("Could not identify a ClickUp workspace", 502); + const hookResponse = await fetch(`https://api.clickup.com/api/v2/team/${encodeURIComponent(team.id)}/webhook`, { method: "POST", headers: { Authorization: tokens.access_token, "Content-Type": "application/json" }, body: JSON.stringify({ endpoint: `${c.env.APP_ORIGIN}/webhooks/clickup/${encodeURIComponent(session.tenantId)}`, events: ["taskCreated", "taskUpdated", "taskStatusUpdated", "taskAssigneeUpdated", "taskTagUpdated", "taskMoved"] }) }); + const hook = await hookResponse.json() as any; + if (!hookResponse.ok || !hook.id) return c.text("Could not register the ClickUp webhook", 502); + await tenant(c, session.tenantId).fetch("https://tenant/connections/clickup", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ accessToken: tokens.access_token, teamId: String(team.id), teamName: team.name, webhookId: String(hook.id), webhookSecret: hook.secret }) }); + deleteCookie(c, "clickup_oauth_state", { path: "/auth/clickup" }); + return c.redirect("/settings/integrations"); +}); + app.get("/api/connections/status", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); return tenant(c, session.tenantId).fetch("https://tenant/connections/status"); @@ -173,6 +202,14 @@ app.get("/api/linear/options", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); return tenant(c, session.tenantId).fetch("https://tenant/linear/options"); }); +app.get("/api/clickup/lists", async (c) => { + const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); + return tenant(c, session.tenantId).fetch("https://tenant/clickup/lists"); +}); +app.get("/api/clickup/options", async (c) => { + const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); + return tenant(c, session.tenantId).fetch(`https://tenant/clickup/options?listId=${encodeURIComponent(c.req.query("listId") ?? "")}`); +}); app.get("/api/github/installations", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); return tenant(c, session.tenantId).fetch("https://tenant/github/installations"); @@ -251,6 +288,13 @@ app.post("/webhooks/linear", async (c) => { return tenant(c, organizationId).fetch("https://tenant/webhook/linear", { method: "POST", headers: { "Content-Type": "application/json", "Linear-Delivery": `linear:${deliveryId}` }, body: raw }); }); +app.post("/webhooks/clickup/:tenantId", async (c) => { + const raw = await c.req.text(); + if (new TextEncoder().encode(raw).byteLength > 262_144) return c.text("Payload too large", 413); + try { JSON.parse(raw); } catch { return c.text("Invalid JSON", 400); } + return tenant(c, c.req.param("tenantId")).fetch("https://tenant/webhook/clickup", { method: "POST", headers: { "Content-Type": "application/json", "X-Signature": c.req.header("X-Signature") ?? "" }, body: raw }); +}); + app.post("/webhooks/github", async (c) => { if (!c.env.GITHUB_WEBHOOK_SECRET) return c.text("Webhook verification is not configured", 503); const raw = await c.req.text(); diff --git a/packages/app/src/tenant.ts b/packages/app/src/tenant.ts index f319bdc6..caac3e48 100644 --- a/packages/app/src/tenant.ts +++ b/packages/app/src/tenant.ts @@ -1,6 +1,6 @@ import { DurableObject } from "cloudflare:workers"; import Mustache from "mustache"; -import { decrypt, encrypt } from "./crypto"; +import { decrypt, encrypt, equalHmac } from "./crypto"; import { agentListCommand, agentOutputCommand, agentStartupBlocked, agentStatusCommand, connectionCheckCommand, defaultAgentCommand, exec, garbageCollectPaneCommand, herdrAgentStatus, herdrCheckCommand, paneGetCommand, paneProcessInfoCommand, replaceForegroundCommand, startAgentCommand, startAgentInPaneCommand, stopAgentCommand, validateWorktreeLeaseCommand, type ExeConnection } from "./exe"; import { findOwnedAgent, ownsPane, parseAgent, parseAgentList, parsePaneProcess, type HerdrIdentity } from "./recovery"; import { LINEAR_ISSUE_PROJECT_QUERY, LINEAR_OPTION_QUERIES, LINEAR_PROJECTS_QUERY, isLinearAuthenticationError, refreshLinearToken } from "./linear"; @@ -20,6 +20,7 @@ import { catchUpOccurrence, nextOccurrence, validateScheduleConfig, type Schedul import { adaptWebhook, publicWebhookConfig, validateWebhookHandler, type WebhookProvider, type WebhookTriggerConfig } from "./webhook-trigger"; import { reflectTriggerContext } from "./trigger-context"; import { installedTriggerAvailability, sameProviderReference } from "./trigger-availability"; +import { clickUpJson, matchingClickUpTask } from "./clickup"; export { DEFAULT_CONTEXT_TEMPLATE, linearTicketPrompt, renderContextTemplate } from "./linear-source"; @@ -216,7 +217,10 @@ export class TenantV2 extends DurableObject { if (request.method === "DELETE" && accessToken) return this.revokeAccessToken(decodeURIComponent(accessToken[1])); if (request.method === "GET" && url.pathname === "/linear/projects") return await this.linearProjects(); if (request.method === "GET" && url.pathname === "/linear/options") return await this.linearOptions(); + if (request.method === "GET" && url.pathname === "/clickup/lists") return await this.clickUpLists(); + if (request.method === "GET" && url.pathname === "/clickup/options") return await this.clickUpOptions(url.searchParams.get("listId")); if (request.method === "PUT" && url.pathname === "/connections/linear") return await this.saveLinear(await request.json()); + if (request.method === "PUT" && url.pathname === "/connections/clickup") return await this.saveClickUp(await request.json()); if (request.method === "PUT" && url.pathname === "/connections/exe") return await this.saveExe(await request.json()); if (request.method === "POST" && url.pathname === "/connections/exe/test") return await this.testExe(await request.json()); if (request.method === "PUT" && url.pathname === "/connections/amp") return await this.saveAmp(await request.json()); @@ -229,6 +233,7 @@ export class TenantV2 extends DurableObject { const tailTestMatch = url.pathname.match(/^\/connections\/cloudflare-tail\/([^/]+)\/test$/); if (request.method === "POST" && tailTestMatch) return await this.testTailIntegration(decodeURIComponent(tailTestMatch[1])); if (request.method === "POST" && url.pathname === "/webhook/linear") return await this.acceptLinearWebhook(await request.json() as Record, request.headers.get("linear-delivery")); + if (request.method === "POST" && url.pathname === "/webhook/clickup") { const raw = await request.text(); return await this.acceptClickUpWebhook(raw, request.headers.get("X-Signature")); } if (request.method === "POST" && url.pathname === "/webhook/github") return await this.acceptGitHubWebhook(await request.json() as Record, request.headers.get("github-delivery"), request.headers.get("github-event")); const tailMatch = url.pathname.match(/^\/webhook\/cloudflare\/([^/]+)$/); if (request.method === "POST" && tailMatch) return await this.acceptCloudflareTail(decodeURIComponent(tailMatch[1]), await request.text(), request.headers); @@ -286,6 +291,15 @@ export class TenantV2 extends DurableObject { return json({ ok: true }); } + private async saveClickUp(input: unknown): Promise { + const value = input as { accessToken?: string; teamId?: string; teamName?: string; webhookId?: string; webhookSecret?: string }; + if (!value.accessToken || !value.teamId || !value.webhookId || !value.webhookSecret) throw new Error("ClickUp token, workspace, and webhook are required"); + const prior = await this.connection<{ accessToken: string; webhookId?: string }>("clickup"); + if (prior?.webhookId && prior.webhookId !== value.webhookId) await fetch(`https://api.clickup.com/api/v2/webhook/${encodeURIComponent(prior.webhookId)}`, { method: "DELETE", headers: { Authorization: prior.accessToken } }).catch(() => undefined); + await this.putConnection("clickup", value); + return json({ ok: true }); + } + private async saveExe(input: unknown): Promise { const value = input as ExeConnectionInput; if (!value.vmName || !value.apiToken || !value.cwd || !value.agentKind) throw new Error("SSH destination, API token, agent, and working directory are required"); @@ -411,11 +425,13 @@ export class TenantV2 extends DurableObject { private async connectionStatus(): Promise { const linear = await this.connection<{ organizationName?: string; viewerEmail?: string }>("linear"); + const clickup = await this.connection<{ teamName?: string }>("clickup"); const connections = await this.exeConnections(); const exe = await this.connection("exe"); const ampConnections = await this.ampConnections(); return json({ linear: linear ? { organizationName: linear.organizationName ?? null, viewerEmail: linear.viewerEmail ?? null } : null, + clickup: clickup ? { teamName: clickup.teamName ?? null } : null, exe: exe ? { vmName: exe.vmName, agentKind: exe.agentKind, cwd: exe.cwd, herdrCommand: exe.herdrCommand ?? "herdr", agentCommand: exe.agentCommand ?? defaultAgentCommand(exe.agentKind) } : null, exeConnections: connections.map(({ apiToken, ...connection }) => connection), ampConnections: ampConnections.map(({ accessToken, ...connection }) => connection), @@ -520,6 +536,7 @@ export class TenantV2 extends DurableObject { private async providerTriggerAvailability(kind: unknown, config: Record): Promise<{ available: boolean; reason: string | null }> { if (kind !== "webhook") return { available: true, reason: null }; if (config.provider === "linear") return await this.connection("linear") ? { available: true, reason: null } : { available: false, reason: "Reconnect Linear to use this trigger." }; + if (config.provider === "clickup") return await this.connection("clickup") ? { available: true, reason: null } : { available: false, reason: "Connect ClickUp to use this trigger." }; if (config.provider === "github") { const installation = this.one("SELECT state FROM github_installations WHERE installation_id=?", Number(config.installationId)) as Row | undefined; return installation?.state === "active" ? { available: true, reason: null } : { available: false, reason: "Reconnect this GitHub installation to use this trigger." }; @@ -530,9 +547,10 @@ export class TenantV2 extends DurableObject { private async triggerAvailability(): Promise { const linear = Boolean(await this.connection("linear")); + const clickup = Boolean(await this.connection("clickup")); const githubStates = this.rows("SELECT state FROM github_installations").map(row => String(row.state)); const cloudflareTail = (await this.tailIntegrations()).length; - return json(installedTriggerAvailability(linear, githubStates, cloudflareTail)); + return json(installedTriggerAvailability(linear, clickup, githubStates, cloudflareTail)); } private sameProviderReference(trigger: any, previous?: Row): boolean { @@ -958,6 +976,29 @@ export class TenantV2 extends DurableObject { return json({ statuses: statusData.workflowStates.nodes, users: userData.users.nodes, labels: labelData.issueLabels.nodes }); } + private async clickUpLists(): Promise { + const connection = await this.connection<{ accessToken: string; teamId: string }>("clickup"); + if (!connection) throw new Error("Connect ClickUp first"); + const spaces = (await clickUpJson(connection.accessToken, `/team/${connection.teamId}/space?archived=false`)).spaces ?? []; + const lists: Array<{ id: string; name: string }> = []; + for (const space of spaces) { + const [folderData, folderless] = await Promise.all([ + clickUpJson(connection.accessToken, `/space/${space.id}/folder?archived=false`), + clickUpJson(connection.accessToken, `/space/${space.id}/list?archived=false`), + ]); + for (const list of folderless.lists ?? []) lists.push({ id: String(list.id), name: `${space.name} / ${list.name}` }); + for (const folder of folderData.folders ?? []) for (const list of folder.lists ?? []) lists.push({ id: String(list.id), name: `${space.name} / ${folder.name} / ${list.name}` }); + } + return json(lists); + } + + private async clickUpOptions(listId: string | null): Promise { + const connection = await this.connection<{ accessToken: string; teamId: string }>("clickup"); + if (!connection || !listId) throw new Error("Connect ClickUp and choose a list first"); + const [list, team, tags] = await Promise.all([clickUpJson(connection.accessToken, `/list/${encodeURIComponent(listId)}`), clickUpJson(connection.accessToken, `/team/${connection.teamId}`), clickUpJson(connection.accessToken, `/team/${connection.teamId}/tag`)]); + return json({ statuses: (list.statuses ?? []).map((x: any) => ({ id: x.status, name: x.status })), users: (team.team?.members ?? []).map((x: any) => ({ id: String(x.user.id), name: x.user.username ?? x.user.email })), labels: (tags.tags ?? []).map((x: any) => ({ id: x.name, name: x.name })) }); + } + private webhookJobs(provider: WebhookProvider): Array<{ job: Row; triggerId: string; triggerSlug: string; config: WebhookTriggerConfig }> { return this.rows("SELECT j.*,t.id AS trigger_id,t.slug AS trigger_slug,t.config AS trigger_config FROM jobs j JOIN triggers t ON t.job_id=j.id WHERE j.enabled=1 AND t.enabled=1 AND t.kind='webhook'") .flatMap(job => { try { const config = JSON.parse(String(job.trigger_config)) as WebhookTriggerConfig; return config.provider === provider ? [{ job, triggerId: String(job.trigger_id), triggerSlug: String(job.trigger_slug), config }] : []; } catch { return []; } }) as any; @@ -1008,6 +1049,27 @@ export class TenantV2 extends DurableObject { return new Response(null, { status: 200 }); } + private async acceptClickUpWebhook(raw: string, signature: string | null): Promise { + const connection = await this.connection<{ accessToken: string; webhookId: string; webhookSecret: string }>("clickup"); + if (!connection || !signature || !(await equalHmac(raw, signature, connection.webhookSecret))) return new Response("Invalid signature", { status: 401 }); + let event: Record; try { event = JSON.parse(raw); } catch { return new Response("Invalid JSON", { status: 400 }); } + if (!event.task_id || String(event.webhook_id) !== connection.webhookId) return new Response(null, { status: 202 }); + const relevant = event.event === "taskCreated" || ["taskStatusUpdated", "taskAssigneeUpdated", "taskTagUpdated", "taskMoved"].includes(String(event.event)) + || (event.event === "taskUpdated" && (event.history_items ?? []).some((item: any) => ["status", "assignee", "tags", "list_id", "creator"].includes(String(item.field)))); + if (!relevant) return new Response(null, { status: 202 }); + const task = await clickUpJson(connection.accessToken, `/task/${encodeURIComponent(String(event.task_id))}`); + const deliveryId = `clickup:${event.webhook_id}:${event.event}:${event.history_items?.[0]?.date ?? event.task_id}`; + for (const { job, triggerId, triggerSlug, config } of this.webhookJobs("clickup")) { + const payload = { ...event, task, matches: matchingClickUpTask(task, String(config.listId), config.matchRules ?? []) }; + const invocation = adaptWebhook(config, "clickup", deliveryId, payload, event.event); + if (!invocation) { this.recordJobEvent(String(job.id), "clickup", deliveryId, "ignored", "Task did not match this job trigger."); continue; } + const result = await this.signalAutomaticJob(String(job.id), "webhook", triggerId, `webhook:${triggerId}:${invocation.claimKey}`, { [triggerSlug]: invocation.payload }, { ...invocation.occurrence, metadata: { ...invocation.occurrence.metadata, triggerId } }); + this.recordJobEvent(String(job.id), "clickup", deliveryId, result?.duplicate ? "duplicate" : result ? "accepted" : "ignored", result ? "ClickUp task queued through canonical job invocation." : "Job was unavailable."); + } + await this.ctx.storage.setAlarm(Date.now()); + return new Response(null, { status: 200 }); + } + private async acceptGitHubWebhook(event: Record, deliveryId: string | null, eventName: string | null): Promise { if (!deliveryId || !eventName) return new Response("Missing delivery metadata", { status: 400 }); if (eventName !== "pull_request" || event.action !== "dequeued") await this.invokeWebhookJobs("github", deliveryId, event, eventName); diff --git a/packages/app/src/trigger-availability.ts b/packages/app/src/trigger-availability.ts index 302aaae2..e6733644 100644 --- a/packages/app/src/trigger-availability.ts +++ b/packages/app/src/trigger-availability.ts @@ -3,15 +3,17 @@ export type TriggerAvailability = { schedule: true; jobLifecycle: true; linear: boolean; + clickup: boolean; github: boolean; cloudflareTail: boolean; }; -export const installedTriggerAvailability = (linearConnected: boolean, githubStates: string[], tailInstallationCount: number): TriggerAvailability => ({ +export const installedTriggerAvailability = (linearConnected: boolean, clickupConnected: boolean, githubStates: string[], tailInstallationCount: number): TriggerAvailability => ({ manual: true, schedule: true, jobLifecycle: true, linear: linearConnected, + clickup: clickupConnected, github: githubStates.some(state => state === "active"), cloudflareTail: tailInstallationCount > 0, }); @@ -20,5 +22,6 @@ export const sameProviderReference = (next: Record, previous: Recor if (next.provider !== previous.provider) return false; if (next.provider === "github") return Number(next.installationId) === Number(previous.installationId); if (next.provider === "cloudflareTail") return next.integrationId === previous.integrationId; + if (next.provider === "clickup") return true; return next.provider === "linear"; }; diff --git a/packages/app/src/trigger-context.ts b/packages/app/src/trigger-context.ts index d35e52e8..a1e02970 100644 --- a/packages/app/src/trigger-context.ts +++ b/packages/app/src/trigger-context.ts @@ -25,6 +25,14 @@ export const triggerContextCatalog: Record = { { path: "issue.state.name", type: "string", description: "Current workflow state name." }, { path: "issue.project.name", type: "string", description: "Project name, when present." }, ], + clickup: [...commonWebhook, + { path: "task", type: "object", description: "Complete ClickUp task fetched for the authenticated delivery." }, + { path: "task.id", type: "string", description: "ClickUp task ID." }, + { path: "task.name", type: "string", description: "Task title." }, + { path: "task.description", type: "string", description: "Task description." }, + { path: "task.url", type: "string", description: "Canonical ClickUp task URL." }, + { path: "task.status.status", type: "string", description: "Current status name." }, + ], github: [...commonWebhook, { path: "action", type: "string", description: "GitHub webhook action." }, { path: "pull_request", type: "object", description: "Complete GitHub pull request payload." }, diff --git a/packages/app/src/types.ts b/packages/app/src/types.ts index ef0e9eb7..1a29fe3a 100644 --- a/packages/app/src/types.ts +++ b/packages/app/src/types.ts @@ -11,6 +11,8 @@ export interface Env { LINEAR_CLIENT_SECRET: string; LINEAR_OAUTH_SCOPES?: string; LINEAR_WEBHOOK_SIGNING_SECRET: string; + CLICKUP_CLIENT_ID?: string; + CLICKUP_CLIENT_SECRET?: string; CREDENTIAL_ENCRYPTION_KEY: string; SESSION_SIGNING_SECRET: string; GITHUB_APP_ID?: string; @@ -33,7 +35,7 @@ export type OAuthProps = { }; export interface WorkItem { - provider: "linear" | "github" | "cloudflare"; + provider: "linear" | "clickup" | "github" | "cloudflare"; claimKey: string; identifier: string; title: string; diff --git a/packages/app/src/ui.ts b/packages/app/src/ui.ts index 339dafcb..55d23537 100644 --- a/packages/app/src/ui.ts +++ b/packages/app/src/ui.ts @@ -70,13 +70,14 @@ export const jobPage = (viewer: { email: string }, jobId?: string) => shell(`${j

Add trigger

Provider credentials stay managed by Factorize.

+
`, `${uiHelpers} -const jobId=${JSON.stringify(jobId ?? null)},contextCatalog=${JSON.stringify(triggerContextCatalog)},form=$('#job'),dialog=$('#trigger-dialog'),triggerForm=$('#trigger-form');let triggers=[],editing=-1,resources={projects:[],options:{statuses:[],users:[],labels:[]},installations:[],tailInstallations:[],repositories:new Map(),jobs:[]},clientId=0,reservedSlugs=new Set(),availability={}; +const jobId=${JSON.stringify(jobId ?? null)},contextCatalog=${JSON.stringify(triggerContextCatalog)},form=$('#job'),dialog=$('#trigger-dialog'),triggerForm=$('#trigger-form');let triggers=[],editing=-1,resources={projects:[],clickupLists:[],options:{statuses:[],users:[],labels:[]},clickupOptions:{statuses:[],users:[],labels:[]},installations:[],tailInstallations:[],repositories:new Map(),jobs:[]},clientId=0,reservedSlugs=new Set(),availability={}; let slugEdited=Boolean(jobId);const jobSlug=value=>value.trim().toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-+|-+$/g,'').slice(0,30)||'job';form.name.addEventListener('input',()=>{if(!slugEdited)form.slug.value=jobSlug(form.name.value)});form.slug.addEventListener('input',()=>{slugEdited=true}); -const kinds={manual:'Manual',schedule:'Schedule',linear:'Linear',github:'GitHub',cloudflareTail:'Cloudflare Tail',jobLifecycle:'Job lifecycle'}; +const kinds={manual:'Manual',schedule:'Schedule',linear:'Linear',clickup:'ClickUp',github:'GitHub',cloudflareTail:'Cloudflare Tail',jobLifecycle:'Job lifecycle'}; const providerKind=t=>t.kind==='webhook'?t.config.provider:t.kind; const reflection=t=>t.reflection?.paths||contextCatalog[providerKind(t)]||[]; const triggerHints=()=>triggers.map(t=>({path:t.slug+'.*',type:'context',description:kinds[providerKind(t)]+' trigger context'})); @@ -90,7 +91,7 @@ async function refreshAvailability(){availability=await request('/api/v1/job-tri const ruleLabels={status:'Status',label:'Label',assignee:'Assignee',creator:'Creator',owner:'Owner'}; const ruleOptions=type=>type==='status'?resources.options.statuses:type==='label'?resources.options.labels:resources.options.users; const ruleSummary=rule=>ruleLabels[rule.type]+' is '+nameOf(ruleOptions(rule.type),rule.targetId); -function summary(t){const c=t.config||{},k=providerKind(t);if(k==='manual')return 'Prompt entered when run';if(k==='schedule')return c.cron+' · '+c.timezone;if(k==='linear')return nameOf(resources.projects,c.projectId)+' · '+(c.matchRules||[]).map(ruleSummary).join(' + ');if(k==='github'){const i=resources.installations.find(x=>String(x.installationId)===String(c.installationId));const repos=resources.repositories.get(String(c.installationId))||[];return (i?.accountLogin||c.installationId)+' · '+(repos.find(x=>String(x.id)===String(c.repositoryId))?.fullName||c.repositoryId)+' · '+c.event+'/'+c.action}if(k==='cloudflareTail')return 'Managed signed Tail endpoint'+(c.handlerCode?' · handler':'');return (c.sourceJobIds||[]).map(id=>resources.jobs.find(j=>j.id===id)?.name||id).join(', ')+' · '+(c.states||[]).join(', ')} +function summary(t){const c=t.config||{},k=providerKind(t);if(k==='manual')return 'Prompt entered when run';if(k==='schedule')return c.cron+' · '+c.timezone;if(k==='linear')return nameOf(resources.projects,c.projectId)+' · '+(c.matchRules||[]).map(ruleSummary).join(' + ');if(k==='clickup')return nameOf(resources.clickupLists,c.listId)+' · '+(c.matchRules||[]).map(ruleSummary).join(' + ');if(k==='github'){const i=resources.installations.find(x=>String(x.installationId)===String(c.installationId));const repos=resources.repositories.get(String(c.installationId))||[];return (i?.accountLogin||c.installationId)+' · '+(repos.find(x=>String(x.id)===String(c.repositoryId))?.fullName||c.repositoryId)+' · '+c.event+'/'+c.action}if(k==='cloudflareTail')return 'Managed signed Tail endpoint'+(c.handlerCode?' · handler':'');return (c.sourceJobIds||[]).map(id=>resources.jobs.find(j=>j.id===id)?.name||id).join(', ')+' · '+(c.states||[]).join(', ')} function render(){const rows=$('#trigger-rows');rows.innerHTML=triggers.map((t,i)=>''+esc(t.slug)+''+esc(kinds[providerKind(t)])+(t.actionRequired?'Action required':'')+''+esc(t.actionRequired||summary(t))+'
').join('');$('#trigger-empty').classList.toggle('hidden',triggers.length>0);const hints=triggerHints();$('#context-paths').innerHTML=hints.length?'Available context: '+hints.map(x=>'').join(''):'Add a trigger to expose context.';updateSuggestions()} const promptEditor=form.elements.promptTemplate,promptHighlight=$('#prompt-highlight'),suggestionMenu=$('#context-suggestions');let matches=[],activeSuggestion=0,expression=null; function highlightPrompt(){const source=promptEditor.value,pattern=/({{{[\s\S]*?}}}|{{[\s\S]*?}})/g;let html='',last=0,match;while((match=pattern.exec(source))){html+=esc(source.slice(last,match.index));const token=match[0],triple=token.startsWith('{{{'),open=triple?'{{{':'{{',close=triple?'}}}':'}}',value=token.slice(open.length,-close.length);html+=''+open+''+esc(value)+''+close+'';last=pattern.lastIndex}promptHighlight.innerHTML=html+esc(source.slice(last))+'\\n';promptHighlight.scrollTop=promptEditor.scrollTop;promptHighlight.scrollLeft=promptEditor.scrollLeft} @@ -110,16 +111,20 @@ function linearRuleRows(){return [...$('#linear-rules').querySelectorAll('[data- function syncLinearRuleButtons(){const rows=linearRuleRows();rows.forEach(row=>row.querySelector('[data-remove-linear-rule]').classList.toggle('invisible',rows.length===1))} function addLinearRule(rule={type:'status',targetId:''}){const row=document.createElement('div');row.dataset.linearRule='';row.className='grid gap-3 rounded-xl border border-stone-200 bg-stone-50 p-4 sm:grid-cols-[minmax(0,1fr)_minmax(0,1.4fr)_auto] sm:items-end dark:border-slate-700 dark:bg-slate-950';const typeLabel=document.createElement('label');typeLabel.className='label';typeLabel.textContent='Match on';const type=document.createElement('select');type.className='field';type.innerHTML=Object.entries(ruleLabels).map(([value,label])=>'').join('');type.value=rule.type;typeLabel.append(type);const valueLabel=document.createElement('label');valueLabel.className='label';valueLabel.textContent='Value';const value=document.createElement('select');value.className='field';const fill=()=>{value.replaceChildren(new Option('Choose '+ruleLabels[type.value].toLowerCase(),''),...ruleOptions(type.value).map(item=>new Option(item.name,item.id)));value.value=type.value===rule.type?rule.targetId:''};type.onchange=fill;fill();valueLabel.append(value);const remove=document.createElement('button');remove.type='button';remove.dataset.removeLinearRule='';remove.className='rounded-lg border border-red-200 px-3 py-2 text-sm font-semibold text-red-700 hover:bg-red-50 dark:border-red-900 dark:text-red-300';remove.textContent='Remove';remove.onclick=()=>{row.remove();syncLinearRuleButtons()};row.append(typeLabel,valueLabel,remove);$('#linear-rules').append(row);syncLinearRuleButtons()} function readLinearRules(){return linearRuleRows().map(row=>{const [type,target]=row.querySelectorAll('select');return {type:type.value,targetId:target.value}})} -async function openEditor(kind,index=-1){const current=index>=0?triggers[index]:null,k=current?providerKind(current):kind;if(!kinds[k])throw new Error('This trigger type is no longer supported.');editing=index;const c=current?.config||{};$('#dialog-title').textContent=(current?'Edit ':'Add ')+kinds[k]+' trigger';triggerForm.reset();document.querySelectorAll('[data-panel]').forEach(x=>x.classList.add('hidden'));const panel=document.querySelector('[data-panel="'+(k==='manual'?'none':k==='schedule'?'schedule':k==='linear'?'linear':k==='github'?'github':k==='jobLifecycle'?'jobLifecycle':'webhook')+'"]');panel?.classList.remove('hidden');triggerForm.dataset.kind=k;$('#dialog-error').classList.add('hidden');$('#handler-result').textContent='';if(k==='schedule'){triggerForm.elements.cron.value=c.cron||'0 9 * * *';triggerForm.elements.timezone.value=c.timezone||'UTC'}if(k==='linear'){options(triggerForm.elements.projectId,resources.projects,'name');triggerForm.elements.projectId.value=c.projectId||resources.projects[0]?.id||'';$('#linear-rules').replaceChildren();(c.matchRules?.length?c.matchRules:[{type:'status',targetId:''}]).forEach(addLinearRule)}if(k==='github'){options(triggerForm.elements.installationId,resources.installations,'accountLogin','installationId');triggerForm.elements.installationId.value=String(c.installationId||resources.installations[0]?.installationId||'');await syncRepositories(c.repositoryId);triggerForm.elements.event.value=c.event||'pull_request';triggerForm.elements.action.value=c.action||'dequeued'}if(k==='jobLifecycle'){options(triggerForm.elements.sourceJobId,resources.jobs.filter(j=>j.id!==jobId),'name');[...triggerForm.elements.sourceJobId.options].forEach(x=>x.selected=(c.sourceJobIds||[]).includes(x.value));triggerForm.querySelectorAll('[name=lifecycleState]').forEach(x=>x.checked=(c.states||['succeeded','failed']).includes(x.value))}if(['linear','github','cloudflareTail'].includes(k))triggerForm.elements.handlerCode.value=c.handlerCode||'';dialog.showModal();if(k==='schedule')previewSchedule()} +function clickupRuleRows(){return [...$('#clickup-rules').querySelectorAll('[data-clickup-rule]')]} +function addClickupRule(rule={type:'status',targetId:''}){const row=document.createElement('div');row.dataset.clickupRule='';row.className='grid gap-3 rounded-xl border border-stone-200 bg-stone-50 p-4 sm:grid-cols-[minmax(0,1fr)_minmax(0,1.4fr)_auto] sm:items-end dark:border-slate-700 dark:bg-slate-950';const typeLabel=document.createElement('label'),type=document.createElement('select'),valueLabel=document.createElement('label'),value=document.createElement('select'),remove=document.createElement('button');typeLabel.className=valueLabel.className='label';typeLabel.textContent='Match on';valueLabel.textContent='Value';type.className=value.className='field';type.innerHTML=Object.entries(ruleLabels).filter(([key])=>key!=='owner').map(([key,label])=>'').join('');type.value=rule.type;const fill=()=>{const items=type.value==='status'?resources.clickupOptions.statuses:type.value==='label'?resources.clickupOptions.labels:resources.clickupOptions.users;value.replaceChildren(new Option('Choose '+ruleLabels[type.value].toLowerCase(),''),...items.map(item=>new Option(item.name,item.id)));value.value=type.value===rule.type?rule.targetId:''};type.onchange=fill;fill();typeLabel.append(type);valueLabel.append(value);remove.type='button';remove.className='rounded-lg border border-red-200 px-3 py-2 text-sm font-semibold text-red-700';remove.textContent='Remove';remove.onclick=()=>row.remove();row.append(typeLabel,valueLabel,remove);$('#clickup-rules').append(row)} +function readClickupRules(){return clickupRuleRows().map(row=>{const [type,target]=row.querySelectorAll('select');return {type:type.value,targetId:target.value}})} +async function syncClickupOptions(rules=[{type:'status',targetId:''}]){const listId=triggerForm.elements.clickupListId.value;resources.clickupOptions=listId?await request('/api/clickup/options?listId='+encodeURIComponent(listId)):{statuses:[],users:[],labels:[]};$('#clickup-rules').replaceChildren();rules.forEach(addClickupRule)} +async function openEditor(kind,index=-1){const current=index>=0?triggers[index]:null,k=current?providerKind(current):kind;if(!kinds[k])throw new Error('This trigger type is no longer supported.');editing=index;const c=current?.config||{};$('#dialog-title').textContent=(current?'Edit ':'Add ')+kinds[k]+' trigger';triggerForm.reset();document.querySelectorAll('[data-panel]').forEach(x=>x.classList.add('hidden'));const panel=document.querySelector('[data-panel="'+(k==='manual'?'none':k==='schedule'?'schedule':k==='linear'?'linear':k==='clickup'?'clickup':k==='github'?'github':k==='jobLifecycle'?'jobLifecycle':'webhook')+'"]');panel?.classList.remove('hidden');triggerForm.dataset.kind=k;$('#dialog-error').classList.add('hidden');$('#handler-result').textContent='';if(k==='schedule'){triggerForm.elements.cron.value=c.cron||'0 9 * * *';triggerForm.elements.timezone.value=c.timezone||'UTC'}if(k==='linear'){options(triggerForm.elements.projectId,resources.projects,'name');triggerForm.elements.projectId.value=c.projectId||resources.projects[0]?.id||'';$('#linear-rules').replaceChildren();(c.matchRules?.length?c.matchRules:[{type:'status',targetId:''}]).forEach(addLinearRule)}if(k==='clickup'){options(triggerForm.elements.clickupListId,resources.clickupLists,'name');triggerForm.elements.clickupListId.value=c.listId||resources.clickupLists[0]?.id||'';resources.clickupOptions=await request('/api/clickup/options?listId='+encodeURIComponent(triggerForm.elements.clickupListId.value));$('#clickup-rules').replaceChildren();(c.matchRules?.length?c.matchRules:[{type:'status',targetId:''}]).forEach(addClickupRule)}if(k==='github'){options(triggerForm.elements.installationId,resources.installations,'accountLogin','installationId');triggerForm.elements.installationId.value=String(c.installationId||resources.installations[0]?.installationId||'');await syncRepositories(c.repositoryId);triggerForm.elements.event.value=c.event||'pull_request';triggerForm.elements.action.value=c.action||'dequeued'}if(k==='jobLifecycle'){options(triggerForm.elements.sourceJobId,resources.jobs.filter(j=>j.id!==jobId),'name');[...triggerForm.elements.sourceJobId.options].forEach(x=>x.selected=(c.sourceJobIds||[]).includes(x.value));triggerForm.querySelectorAll('[name=lifecycleState]').forEach(x=>x.checked=(c.states||['succeeded','failed']).includes(x.value))}if(['linear','clickup','github','cloudflareTail'].includes(k))triggerForm.elements.handlerCode.value=c.handlerCode||'';dialog.showModal();if(k==='schedule')previewSchedule()} async function previewSchedule(){const body={cron:triggerForm.elements.cron.value,timezone:triggerForm.elements.timezone.value};try{const x=await request('/api/v1/schedules/preview',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});$('#schedule-preview').textContent='Next occurrence: '+new Date(x.nextRunAt).toLocaleString()}catch(e){$('#schedule-preview').textContent=e.message}} -function configFromForm(){const k=triggerForm.dataset.kind,h=triggerForm.elements.handlerCode?.value.trim(),handler=h?{handlerCode:h}:{};if(k==='manual')return {kind:'manual',config:{}};if(k==='schedule')return {kind:'schedule',config:{cron:triggerForm.elements.cron.value.trim(),timezone:triggerForm.elements.timezone.value}};if(k==='linear')return {kind:'webhook',config:{provider:'linear',projectId:triggerForm.elements.projectId.value,matchRules:readLinearRules(),...handler}};if(k==='github')return {kind:'webhook',config:{provider:'github',installationId:Number(triggerForm.elements.installationId.value),repositoryId:Number(triggerForm.elements.repositoryId.value),event:triggerForm.elements.event.value.trim(),action:triggerForm.elements.action.value.trim(),...handler}};if(k==='cloudflareTail')return {kind:'webhook',config:{provider:k,integrationId:triggerForm.elements.tailIntegrationId.value}};return {kind:'jobLifecycle',config:{sourceJobIds:[...triggerForm.elements.sourceJobId.selectedOptions].map(x=>x.value),states:[...triggerForm.querySelectorAll('[name=lifecycleState]:checked')].map(x=>x.value)}}} -function validate(candidate){const k=providerKind(candidate);if(k==='manual'&&triggers.some((t,i)=>i!==editing&&providerKind(t)==='manual'))throw new Error('Only one Manual trigger can be configured.');if(k==='linear'&&(!candidate.config.projectId||!candidate.config.matchRules.length||candidate.config.matchRules.some(rule=>!rule.targetId)))throw new Error('Choose a Linear project and a value for every matching rule.');if(k==='github'&&(!candidate.config.installationId||!candidate.config.repositoryId))throw new Error('Choose a GitHub installation and repository.');if(k==='jobLifecycle'&&(!candidate.config.sourceJobIds[0]||!candidate.config.states.length))throw new Error('Choose a source job and at least one final state.');if(triggers.some((t,i)=>i!==editing&&JSON.stringify(t.config)===JSON.stringify(candidate.config)&&t.kind===candidate.kind))throw new Error('An identical trigger is already configured.')} +function configFromForm(){const k=triggerForm.dataset.kind,h=triggerForm.elements.handlerCode?.value.trim(),handler=h?{handlerCode:h}:{};if(k==='manual')return {kind:'manual',config:{}};if(k==='schedule')return {kind:'schedule',config:{cron:triggerForm.elements.cron.value.trim(),timezone:triggerForm.elements.timezone.value}};if(k==='linear')return {kind:'webhook',config:{provider:'linear',projectId:triggerForm.elements.projectId.value,matchRules:readLinearRules(),...handler}};if(k==='clickup')return {kind:'webhook',config:{provider:'clickup',listId:triggerForm.elements.clickupListId.value,matchRules:readClickupRules(),...handler}};if(k==='github')return {kind:'webhook',config:{provider:'github',installationId:Number(triggerForm.elements.installationId.value),repositoryId:Number(triggerForm.elements.repositoryId.value),event:triggerForm.elements.event.value.trim(),action:triggerForm.elements.action.value.trim(),...handler}};if(k==='cloudflareTail')return {kind:'webhook',config:{provider:k,integrationId:triggerForm.elements.tailIntegrationId.value}};return {kind:'jobLifecycle',config:{sourceJobIds:[...triggerForm.elements.sourceJobId.selectedOptions].map(x=>x.value),states:[...triggerForm.querySelectorAll('[name=lifecycleState]:checked')].map(x=>x.value)}}} +function validate(candidate){const k=providerKind(candidate);if(k==='manual'&&triggers.some((t,i)=>i!==editing&&providerKind(t)==='manual'))throw new Error('Only one Manual trigger can be configured.');if(k==='linear'&&(!candidate.config.projectId||!candidate.config.matchRules.length||candidate.config.matchRules.some(rule=>!rule.targetId)))throw new Error('Choose a Linear project and a value for every matching rule.');if(k==='clickup'&&(!candidate.config.listId||!candidate.config.matchRules.length||candidate.config.matchRules.some(rule=>!rule.targetId)))throw new Error('Choose a ClickUp list and a value for every matching rule.');if(k==='github'&&(!candidate.config.installationId||!candidate.config.repositoryId))throw new Error('Choose a GitHub installation and repository.');if(k==='jobLifecycle'&&(!candidate.config.sourceJobIds[0]||!candidate.config.states.length))throw new Error('Choose a source job and at least one final state.');if(triggers.some((t,i)=>i!==editing&&JSON.stringify(t.config)===JSON.stringify(candidate.config)&&t.kind===candidate.kind))throw new Error('An identical trigger is already configured.')} $('#trigger-rows').onclick=e=>{const b=e.target.closest('button');if(!b)return;const key=['edit','remove'].find(x=>b.dataset[x]!==undefined),i=Number(b.dataset[key]);if(key==='edit')openEditor(providerKind(triggers[i]),i);if(key==='remove'){if(providerKind(triggers[i])==='manual'){const error=$('#error');error.textContent='A Job must keep its Manual trigger. Disable it if manual runs should be unavailable.';error.classList.remove('hidden');return}triggers.splice(i,1);render()}}; -$('#trigger-rows').onchange=e=>{if(e.target.dataset.enable===undefined)return;triggers[Number(e.target.dataset.enable)].enabled=e.target.checked;render()};$('#add-trigger').onchange=e=>{const kind=e.target.value;e.target.value='';if(kind)openEditor(kind)};$('#add-linear-rule').onclick=()=>addLinearRule();$('#cancel-trigger').onclick=()=>dialog.close();triggerForm.elements.installationId.onchange=()=>syncRepositories();triggerForm.elements.cron.oninput=previewSchedule;triggerForm.elements.timezone.onchange=previewSchedule; +$('#trigger-rows').onchange=e=>{if(e.target.dataset.enable===undefined)return;triggers[Number(e.target.dataset.enable)].enabled=e.target.checked;render()};$('#add-trigger').onchange=e=>{const kind=e.target.value;e.target.value='';if(kind)openEditor(kind)};$('#add-linear-rule').onclick=()=>addLinearRule();$('#add-clickup-rule').onclick=()=>addClickupRule();$('#cancel-trigger').onclick=()=>dialog.close();triggerForm.elements.clickupListId.onchange=()=>syncClickupOptions();triggerForm.elements.installationId.onchange=()=>syncRepositories();triggerForm.elements.cron.oninput=previewSchedule;triggerForm.elements.timezone.onchange=previewSchedule; triggerForm.querySelectorAll('[name=scheduleMode]').forEach(input=>input.onchange=syncScheduleEditor);triggerForm.elements.intervalUnit.onchange=syncScheduleEditor;triggerForm.elements.intervalValue.oninput=syncScheduleEditor; triggerForm.onsubmit=e=>{e.preventDefault();try{const value=configFromForm();validate(value);if(editing>=0)triggers[editing]={...triggers[editing],...value};else triggers.push({...value,id:undefined,slug:nextSlug(),enabled:true,_clientId:++clientId});dialog.close();render()}catch(error){$('#dialog-error').textContent=error.message;$('#dialog-error').classList.remove('hidden')}}; $('#test-handler').onclick=async()=>{const output=$('#handler-result');try{const handlerCode=triggerForm.elements.handlerCode.value;if(!handlerCode)throw new Error('Enter handler code first.');const payload=JSON.parse(triggerForm.elements.testPayload.value);const result=await request('/api/v1/job-handlers/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({handlerCode,payload})});output.textContent=result.ok?'Accepted: '+JSON.stringify(result.decision):'Rejected: '+result.category}catch(e){output.textContent=e.message}}; -async function init(){const [targets,projects,linearOptions,installResponse,tails,jobs,current]=await Promise.all([request('/api/v1/execution-targets'),request('/api/linear/projects').catch(()=>[]),request('/api/linear/options').catch(()=>({statuses:[]})),fetch('/api/github/installations'),request('/api/connections/cloudflare-tail').catch(()=>[]),request('/api/v1/jobs'),jobId?request('/api/v1/jobs/'+encodeURIComponent(jobId)):null]);resources.projects=projects;resources.options=linearOptions;resources.installations=installResponse.ok?(await installResponse.json()).filter(x=>x.state==='active'):[];resources.tailInstallations=tails;resources.jobs=jobs;options(triggerForm.elements.tailIntegrationId,tails,'name','integrationId');options(form.executionTargetId,targets,'name');if(current){form.name.value=current.name;form.slug.value=current.slug;form.promptTemplate.value=current.promptTemplate;form.concurrencyLimit.value=current.concurrencyLimit;form.executionTargetId.value=current.executionTargetId;triggers=current.triggers.map(t=>({...t,config:{...t.config}}))}else triggers=[{kind:'manual',slug:'trigger-1',enabled:true,config:{}}];highlightPrompt();reservedSlugs=new Set(triggers.map(t=>t.slug));await refreshAvailability();render()} +async function init(){const [targets,projects,linearOptions,clickupLists,installResponse,tails,jobs,current]=await Promise.all([request('/api/v1/execution-targets'),request('/api/linear/projects').catch(()=>[]),request('/api/linear/options').catch(()=>({statuses:[]})),request('/api/clickup/lists').catch(()=>[]),fetch('/api/github/installations'),request('/api/connections/cloudflare-tail').catch(()=>[]),request('/api/v1/jobs'),jobId?request('/api/v1/jobs/'+encodeURIComponent(jobId)):null]);resources.projects=projects;resources.options=linearOptions;resources.clickupLists=clickupLists;resources.installations=installResponse.ok?(await installResponse.json()).filter(x=>x.state==='active'):[];resources.tailInstallations=tails;resources.jobs=jobs;options(triggerForm.elements.tailIntegrationId,tails,'name','integrationId');options(form.executionTargetId,targets,'name');if(current){form.name.value=current.name;form.slug.value=current.slug;form.promptTemplate.value=current.promptTemplate;form.concurrencyLimit.value=current.concurrencyLimit;form.executionTargetId.value=current.executionTargetId;triggers=current.triggers.map(t=>({...t,config:{...t.config}}))}else triggers=[{kind:'manual',slug:'trigger-1',enabled:true,config:{}}];highlightPrompt();reservedSlugs=new Set(triggers.map(t=>t.slug));await refreshAvailability();render()} window.addEventListener('focus',()=>refreshAvailability().catch(()=>{}));window.addEventListener('pageshow',()=>refreshAvailability().catch(()=>{})); form.onsubmit=async e=>{e.preventDefault();const error=$('#error');error.classList.add('hidden');try{if(!triggers.length)throw new Error('Add at least one trigger.');const body={name:form.name.value,slug:form.slug.value,promptTemplate:form.promptTemplate.value,concurrencyLimit:Number(form.concurrencyLimit.value),executionTargetId:form.executionTargetId.value,triggers:triggers.map(({_clientId,...t})=>t)};const result=await request('/api/v1/jobs'+(jobId?'/'+encodeURIComponent(jobId):''),{method:jobId?'PUT':'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});location.href='/jobs/'+encodeURIComponent(result.id)}catch(e){error.textContent=e.message;error.classList.remove('hidden');error.scrollIntoView({block:'center'})}};init().catch(e=>{const error=$('#error');error.textContent=e.message;error.classList.remove('hidden')});`); @@ -141,6 +146,7 @@ ${[["integrations", "Integrations"], ["api-keys", "API Keys"]].map(([id, label]) const integrationIcons: Record = { linear: ``, + clickup: ``, github: ``, exe: ``, amp: ``, @@ -150,9 +156,10 @@ const integrationIcons: Record = { export const settingsPage = (viewer: { email: string }) => shell("Integrations — Factorize", viewer, settingsLayout("integrations", `${dashboardHead("Integrations", "Connect every provider used by your Jobs. Stored credentials are write-only and are never displayed.")}

Available integrations

Choose a provider to review setup before anything changes.

-${[["linear","Linear","Issues and projects"],["github","GitHub","Repositories and triggers"],["exe","Exe.dev","VM execution"],["amp","Amp","Cloud execution"],["tail","Cloudflare Tail","Signed Worker Tail events"]].map(([id,name,description])=>``).join("")} +${[["linear","Linear","Issues and projects"],["clickup","ClickUp","Tasks and lists"],["github","GitHub","Repositories and triggers"],["exe","Exe.dev","VM execution"],["amp","Amp","Cloud execution"],["tail","Cloudflare Tail","Signed Worker Tail events"]].map(([id,name,description])=>``).join("")}

Connect Linear

You’ll leave Factorize to authorize access to your Linear workspace, then return here.

+

Connect ClickUp

Authorize a ClickUp workspace. Factorize will register the task webhook automatically.

Install the GitHub App

You’ll choose an account and repositories on GitHub, then return to Factorize.

Connect Exe.dev

This saves a write-only token and adds the VM as an execution target.

Connect Amp

This verifies and stores a write-only token for an Amp cloud project.

@@ -163,7 +170,7 @@ const integrationIcons=${JSON.stringify(integrationIcons)}; const testButton=(kind,id)=>''; const installedRow=(name,description,status,tone,actions)=>''+integrationIcons[name==='Cloudflare Tail'?'tail':name==='Exe.dev'?'exe':name.toLowerCase()]+''+esc(name)+'Details'+description+''+esc(status)+'
Actions
'+actions+'
'; async function disconnectGitHub(id){if(!confirm('Disconnect this GitHub installation from Factorize?'))return;await request('/api/github/installations/'+encodeURIComponent(id),{method:'DELETE'});await load()} -async function load(){const loading=$('#installed-loading'),list=$('#installed-integrations'),table=$('#installed-table'),empty=$('#installed-empty');loading.classList.remove('hidden');table.classList.add('hidden');empty.classList.add('hidden');$('#integration-error').classList.add('hidden');try{const [s,gh,tails]=await Promise.all([request('/api/connections/status'),fetch('/api/github/installations'),request('/api/connections/cloudflare-tail')]),rows=[];const exe=s.exeConnections||[],amps=s.ampConnections||[];badge('#linear-available-status',(s.linear?1:0)+' installed','neutral');badge('#exe-available-status',exe.length+' installed','neutral');badge('#amp-available-status',amps.length+' installed','neutral');badge('#tail-available-status',tails.length+' installed','neutral');$('#linear-action').textContent=s.linear?'Reconnect Linear':'Continue to Linear';if(s.linear)rows.push(installedRow('Linear',esc(s.linear.organizationName||'Linear workspace')+(s.linear.viewerEmail?' · '+esc(s.linear.viewerEmail):''),'Connected','ok',''));exe.forEach(c=>rows.push(installedRow('Exe.dev',esc(c.vmName)+' · '+esc(c.cwd)+' · '+esc(c.agentKind),'Connected','ok',testButton('exe',c.connectionId)+'')));amps.forEach(c=>rows.push(installedRow('Amp',esc(c.project),'Connected','ok',testButton('amp',c.connectionId)+'')));tails.forEach(c=>rows.push(installedRow('Cloudflare Tail',esc(c.name)+(c.referencedJobCount?' · '+c.referencedJobCount+' jobs':''),'Connected','ok','')));if(gh.status===404){badge('#github-available-status','Unavailable','neutral');$('#github-install').classList.add('hidden')}else if(!gh.ok){badge('#github-available-status','Action required','warn');rows.push(installedRow('GitHub','Installation status could not be loaded.','Action required','warn',''))}else{const installs=await gh.json(),active=installs.filter(x=>x.state==='active');badge('#github-available-status',active.length+' installed',installs.length&&!active.length?'warn':'neutral');$('#github-install').textContent=active.length?'Add another installation':'Continue to GitHub';installs.forEach(x=>rows.push(installedRow('GitHub',esc(x.accountLogin||'Installation '+x.installationId)+' · '+esc(x.accountType||'GitHub'),x.state==='active'?'Connected':x.state,'active'===x.state?'ok':'warn','Configure ↗')))}list.innerHTML=rows.join('');loading.classList.add('hidden');table.classList.toggle('hidden',!rows.length);empty.classList.toggle('hidden',rows.length>0);bindActions()}catch(e){loading.classList.add('hidden');empty.classList.remove('hidden');const error=$('#integration-error');error.textContent=e.message||'Could not load integration status. Try again.';error.classList.remove('hidden');['linear','github','exe','amp','tail'].forEach(id=>badge('#'+id+'-available-status','Unavailable','neutral'))}} +async function load(){const loading=$('#installed-loading'),list=$('#installed-integrations'),table=$('#installed-table'),empty=$('#installed-empty');loading.classList.remove('hidden');table.classList.add('hidden');empty.classList.add('hidden');$('#integration-error').classList.add('hidden');try{const [s,gh,tails]=await Promise.all([request('/api/connections/status'),fetch('/api/github/installations'),request('/api/connections/cloudflare-tail')]),rows=[];const exe=s.exeConnections||[],amps=s.ampConnections||[];badge('#linear-available-status',(s.linear?1:0)+' installed','neutral');badge('#clickup-available-status',(s.clickup?1:0)+' installed','neutral');badge('#exe-available-status',exe.length+' installed','neutral');badge('#amp-available-status',amps.length+' installed','neutral');badge('#tail-available-status',tails.length+' installed','neutral');$('#linear-action').textContent=s.linear?'Reconnect Linear':'Continue to Linear';if(s.linear)rows.push(installedRow('Linear',esc(s.linear.organizationName||'Linear workspace')+(s.linear.viewerEmail?' · '+esc(s.linear.viewerEmail):''),'Connected','ok',''));if(s.clickup)rows.push(installedRow('ClickUp',esc(s.clickup.teamName||'ClickUp workspace'),'Connected','ok',''));exe.forEach(c=>rows.push(installedRow('Exe.dev',esc(c.vmName)+' · '+esc(c.cwd)+' · '+esc(c.agentKind),'Connected','ok',testButton('exe',c.connectionId)+'')));amps.forEach(c=>rows.push(installedRow('Amp',esc(c.project),'Connected','ok',testButton('amp',c.connectionId)+'')));tails.forEach(c=>rows.push(installedRow('Cloudflare Tail',esc(c.name)+(c.referencedJobCount?' · '+c.referencedJobCount+' jobs':''),'Connected','ok','')));if(gh.status===404){badge('#github-available-status','Unavailable','neutral');$('#github-install').classList.add('hidden')}else if(!gh.ok){badge('#github-available-status','Action required','warn');rows.push(installedRow('GitHub','Installation status could not be loaded.','Action required','warn',''))}else{const installs=await gh.json(),active=installs.filter(x=>x.state==='active');badge('#github-available-status',active.length+' installed',installs.length&&!active.length?'warn':'neutral');$('#github-install').textContent=active.length?'Add another installation':'Continue to GitHub';installs.forEach(x=>rows.push(installedRow('GitHub',esc(x.accountLogin||'Installation '+x.installationId)+' · '+esc(x.accountType||'GitHub'),x.state==='active'?'Connected':x.state,'active'===x.state?'ok':'warn','Configure ↗')))}list.innerHTML=rows.join('');loading.classList.add('hidden');table.classList.toggle('hidden',!rows.length);empty.classList.toggle('hidden',rows.length>0);bindActions()}catch(e){loading.classList.add('hidden');empty.classList.remove('hidden');const error=$('#integration-error');error.textContent=e.message||'Could not load integration status. Try again.';error.classList.remove('hidden');['linear','clickup','github','exe','amp','tail'].forEach(id=>badge('#'+id+'-available-status','Unavailable','neutral'))}} function openSetup(kind){const dialog=$('#'+kind+'-setup');if(!dialog.open)dialog.showModal()} function closeSetup(kind){const dialog=$('#'+kind+'-setup');if(dialog.open)dialog.close()} async function tailAction(id,method){await request('/api/connections/cloudflare-tail/'+encodeURIComponent(id),{method});await load()} diff --git a/packages/app/src/webhook-trigger.ts b/packages/app/src/webhook-trigger.ts index 37fcf608..48e26c55 100644 --- a/packages/app/src/webhook-trigger.ts +++ b/packages/app/src/webhook-trigger.ts @@ -2,10 +2,10 @@ import { matchingIssue } from "./matcher"; import type { MatchRule } from "./types"; import { validateHandlerCode } from "./custom-handler"; -export type WebhookProvider = "linear" | "github" | "cloudflareTail"; +export type WebhookProvider = "linear" | "clickup" | "github" | "cloudflareTail"; export type WebhookTriggerConfig = { provider: WebhookProvider; - projectId?: string; matchRules?: MatchRule[]; installationId?: number; repositoryId?: number; + projectId?: string; listId?: string; matchRules?: MatchRule[]; installationId?: number; repositoryId?: number; event?: string; action?: string; integrationId?: string; signingSecret?: string; secret?: string; handlerCode?: string; }; export interface WebhookInvocation { @@ -20,6 +20,7 @@ export function adaptWebhook(config: WebhookTriggerConfig, provider: WebhookProv const data = payload.data ?? {}, projectId = data.project?.id ?? data.issue?.project?.id; if (!config.projectId || projectId !== config.projectId || !matchingIssue(payload, { projectId: config.projectId, matchRules: config.matchRules ?? [] })) return null; } + if (provider === "clickup" && (!config.listId || payload.task?.list?.id !== config.listId || payload.matches !== true)) return null; if (provider === "github") { if (payload.installation?.id !== config.installationId || payload.repository?.id !== config.repositoryId) return null; if ((eventName ?? "") !== (config.event ?? "pull_request") || payload.action !== (config.action ?? "dequeued")) return null; @@ -27,7 +28,7 @@ export function adaptWebhook(config: WebhookTriggerConfig, provider: WebhookProv const normalizedProvider = provider === "cloudflareTail" ? "cloudflare" : provider; const providerAliases = provider === "linear" ? { issue: payload.data?.issue ?? (payload.type === "Issue" ? payload.data : undefined) } - : {}; + : provider === "clickup" ? { task: payload.task } : {}; return { claimKey: `webhook:${normalizedProvider}:${deliveryId}`, payload: { ...payload, ...providerAliases, provider: normalizedProvider, event: eventName ?? payload.type ?? "webhook", delivery_id: deliveryId }, diff --git a/packages/app/test/clickup.test.ts b/packages/app/test/clickup.test.ts new file mode 100644 index 00000000..a31e2447 --- /dev/null +++ b/packages/app/test/clickup.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from "vitest"; +import { matchingClickUpTask } from "../src/clickup"; + +describe("ClickUp task matching", () => { + const task = { id: "task-1", list: { id: "list-1" }, status: { status: "in progress" }, assignees: [{ id: 7 }], tags: [{ name: "agent" }], creator: { id: 9 } }; + + it("requires the configured list and every rule", () => { + expect(matchingClickUpTask(task, "list-1", [{ type: "status", targetId: "in progress" }, { type: "label", targetId: "agent" }, { type: "assignee", targetId: "7" }, { type: "creator", targetId: "9" }])).toBe(true); + expect(matchingClickUpTask(task, "list-2", [{ type: "status", targetId: "in progress" }])).toBe(false); + expect(matchingClickUpTask(task, "list-1", [{ type: "status", targetId: "done" }])).toBe(false); + }); + + it("fails closed without rules", () => { + expect(matchingClickUpTask(task, "list-1", [])).toBe(false); + }); +}); diff --git a/packages/app/test/trigger-availability.test.ts b/packages/app/test/trigger-availability.test.ts index e63617d8..742b09cf 100644 --- a/packages/app/test/trigger-availability.test.ts +++ b/packages/app/test/trigger-availability.test.ts @@ -3,19 +3,19 @@ import { installedTriggerAvailability, sameProviderReference } from "../src/trig describe("job trigger availability", () => { it("only offers universal triggers with zero installations", () => { - expect(installedTriggerAvailability(false, [], 0)).toEqual({ manual: true, schedule: true, jobLifecycle: true, linear: false, github: false, cloudflareTail: false }); + expect(installedTriggerAvailability(false, false, [], 0)).toEqual({ manual: true, schedule: true, jobLifecycle: true, linear: false, clickup: false, github: false, cloudflareTail: false }); }); it("offers each provider for one matching installation", () => { - expect(installedTriggerAvailability(true, ["active"], 1)).toMatchObject({ linear: true, github: true, cloudflareTail: true }); + expect(installedTriggerAvailability(true, true, ["active"], 1)).toMatchObject({ linear: true, clickup: true, github: true, cloudflareTail: true }); }); it("handles multiple installations without changing the provider result", () => { - expect(installedTriggerAvailability(true, ["active", "active"], 2)).toMatchObject({ github: true, cloudflareTail: true }); + expect(installedTriggerAvailability(true, true, ["active", "active"], 2)).toMatchObject({ github: true, cloudflareTail: true }); }); it("ignores disconnected and stale GitHub installations", () => { - expect(installedTriggerAvailability(false, ["removed", "suspended"], 0)).toMatchObject({ linear: false, github: false, cloudflareTail: false }); + expect(installedTriggerAvailability(false, false, ["removed", "suspended"], 0)).toMatchObject({ linear: false, clickup: false, github: false, cloudflareTail: false }); }); it("preserves a stale trigger only when its installation reference is unchanged", () => { diff --git a/packages/app/test/webhook-trigger.test.ts b/packages/app/test/webhook-trigger.test.ts index 8befeb78..2fec7e95 100644 --- a/packages/app/test/webhook-trigger.test.ts +++ b/packages/app/test/webhook-trigger.test.ts @@ -14,12 +14,19 @@ describe("webhook Job trigger adapters", () => { expect(adaptWebhook(config, "github", "github:d2", { installation: { id: 7 }, repository: { id: 10 }, action: "dequeued" }, "pull_request")).toBeNull(); }); + it("matches normalized ClickUp tasks after authoritative filtering", () => { + const config = { provider: "clickup" as const, listId: "list-1", matchRules: [{ type: "status" as const, targetId: "done" }] }; + const payload = { event: "taskStatusUpdated", task: { id: "task-1", list: { id: "list-1" }, name: "Ship it" }, matches: true }; + expect(adaptWebhook(config, "clickup", "clickup:d1", payload)).toMatchObject({ payload: { provider: "clickup", task: { id: "task-1" } } }); + expect(adaptWebhook(config, "clickup", "clickup:d2", { ...payload, matches: false })).toBeNull(); + }); + it("never exposes webhook secrets", () => { expect(publicWebhookConfig({ provider: "cloudflareTail", signingSecret: "super-secret-value", handlerCode: "function handler(webhook) { return true; }" })).toEqual({ provider: "cloudflareTail", handlerCode: "function handler(webhook) { return true; }", secretConfigured: true }); }); it("validates optional handlers for every provider", () => { - for (const provider of ["linear", "github", "cloudflareTail"] as const) { + for (const provider of ["linear", "clickup", "github", "cloudflareTail"] as const) { expect(() => validateWebhookHandler({ provider, handlerCode: "function handler(webhook) { return { id: webhook.id }; }" })).not.toThrow(); } expect(() => validateWebhookHandler({ provider: "linear", handlerCode: "return true" })).toThrow("complete function handler(webhook)");