From f65a20fe4f436b512af39c10f4d31f038b957054 Mon Sep 17 00:00:00 2001 From: Brendan Date: Thu, 17 Sep 2026 00:54:08 +0000 Subject: [PATCH] GEN-2046 add GitHub Issues trigger --- packages/app/src/flow-schemas.ts | 2 +- packages/app/src/github-issue-matcher.ts | 44 +++++++++++++++++++ packages/app/src/index.ts | 4 ++ packages/app/src/tenant.ts | 23 ++++++++++ packages/app/src/trigger-context.ts | 6 +++ packages/app/src/ui.ts | 23 ++++++---- packages/app/src/webhook-trigger.ts | 5 ++- .../app/test/github-issue-matcher.test.ts | 23 ++++++++++ packages/app/test/trigger-context.test.ts | 1 + packages/app/test/ui.test.ts | 3 ++ packages/app/test/webhook-trigger.test.ts | 7 +++ 11 files changed, 131 insertions(+), 10 deletions(-) create mode 100644 packages/app/src/github-issue-matcher.ts create mode 100644 packages/app/test/github-issue-matcher.test.ts diff --git a/packages/app/src/flow-schemas.ts b/packages/app/src/flow-schemas.ts index 6e40f866..ab0618af 100644 --- a/packages/app/src/flow-schemas.ts +++ b/packages/app/src/flow-schemas.ts @@ -16,7 +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("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("github"), installationId: z.number().int().positive(), repositoryId: z.number().int().positive(), event: z.string().min(1).optional(), action: z.string().min(1).optional(), matchRules: z.array(matchRuleSchema).min(1).optional() }).strict().refine(value => Boolean(value.matchRules?.length || (value.event && value.action)), { message: "GitHub triggers require issue matching rules or an event and action" }), webhookCommonSchema.extend({ provider: z.literal("cloudflareTail"), integrationId: z.string().min(1) }).strict(), ]); export const triggerSchema = z.discriminatedUnion("kind", [ diff --git a/packages/app/src/github-issue-matcher.ts b/packages/app/src/github-issue-matcher.ts new file mode 100644 index 00000000..604309b8 --- /dev/null +++ b/packages/app/src/github-issue-matcher.ts @@ -0,0 +1,44 @@ +import type { MatchRule } from "./types"; + +type GitHubIssue = { + state?: string; + user?: { id?: number }; + assignee?: { id?: number } | null; + assignees?: Array<{ id?: number }>; + labels?: Array<{ id?: number }>; +}; + +type GitHubIssueEvent = { + action?: string; + issue?: GitHubIssue; + label?: { id?: number }; + assignee?: { id?: number }; +}; + +const idMatches = (value: number | undefined, target: string) => value !== undefined && String(value) === target; + +/** Returns true only when an issue currently matches every rule and this event made it enter that set. */ +export function matchingGitHubIssue(event: GitHubIssueEvent, rules: MatchRule[]): boolean { + const issue = event.issue; + if (!issue || !rules.length) return false; + + const matches = (rule: MatchRule): boolean => { + if (rule.type === "status") return issue.state === rule.targetId; + if (rule.type === "label") return issue.labels?.some(label => idMatches(label.id, rule.targetId)) === true; + if (rule.type === "creator") return idMatches(issue.user?.id, rule.targetId); + if (rule.type === "assignee" || rule.type === "owner") { + return issue.assignees?.some(assignee => idMatches(assignee.id, rule.targetId)) === true + || idMatches(issue.assignee?.id, rule.targetId); + } + return false; + }; + if (!rules.every(matches)) return false; + + const action = event.action; + if (action === "opened" || action === "reopened") return true; + return rules.some(rule => + (rule.type === "status" && action === "closed" && rule.targetId === "closed") + || (rule.type === "label" && action === "labeled" && idMatches(event.label?.id, rule.targetId)) + || ((rule.type === "assignee" || rule.type === "owner") && action === "assigned" && idMatches(event.assignee?.id, rule.targetId)), + ); +} diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index e57d9697..aae0f3f5 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -181,6 +181,10 @@ app.get("/api/github/installations/:id/repositories", 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/${encodeURIComponent(c.req.param("id"))}/repositories`); }); +app.get("/api/github/installations/:installationId/repositories/:repositoryId/issue-options", 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/${encodeURIComponent(c.req.param("installationId"))}/repositories/${encodeURIComponent(c.req.param("repositoryId"))}/issue-options`); +}); app.delete("/api/github/installations/:id", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); const response = await tenant(c, session.tenantId).fetch(`https://tenant/github/installations/${encodeURIComponent(c.req.param("id"))}`, { method: "DELETE" }); diff --git a/packages/app/src/tenant.ts b/packages/app/src/tenant.ts index f319bdc6..191ecf5e 100644 --- a/packages/app/src/tenant.ts +++ b/packages/app/src/tenant.ts @@ -238,6 +238,8 @@ export class TenantV2 extends DurableObject { if (request.method === "POST" && url.pathname === "/github/setup-state/consume") return this.consumeSetupState(await request.json()); const repoMatch = url.pathname.match(/^\/github\/installations\/(\d+)\/repositories$/); if (request.method === "GET" && repoMatch) return await this.githubRepositories(Number(repoMatch[1])); + const optionMatch = url.pathname.match(/^\/github\/installations\/(\d+)\/repositories\/(\d+)\/issue-options$/); + if (request.method === "GET" && optionMatch) return await this.githubIssueOptions(Number(optionMatch[1]), Number(optionMatch[2])); const stateMatch = url.pathname.match(/^\/github\/installations\/(\d+)\/state$/); if (request.method === "PATCH" && stateMatch) return this.updateGitHubInstallation(Number(stateMatch[1]), await request.json()); const installMatch = url.pathname.match(/^\/github\/installations\/(\d+)$/); @@ -1536,6 +1538,27 @@ export class TenantV2 extends DurableObject { return json(repositories.map(normalizeRepository)); } + private async githubIssueOptions(installationId: number, repositoryId: number): Promise { + const installation = this.one("SELECT state FROM github_installations WHERE installation_id=?", installationId) as Row | undefined; + if (installation?.state !== "active") return new Response("GitHub installation is unavailable", { status: 409 }); + const token = await installationToken(this.env, installationId); + const repositoryResponse = await fetch(`https://api.github.com/repositories/${repositoryId}`, { headers: githubHeaders(token) }); + if (!repositoryResponse.ok) return new Response("GitHub repository is unavailable", { status: repositoryResponse.status }); + const repository = await repositoryResponse.json() as { full_name?: string }; + if (!repository.full_name) return new Response("GitHub repository is unavailable", { status: 404 }); + const load = async (path: string) => { + const response = await fetch(`https://api.github.com/repos/${repository.full_name}/${path}?per_page=100`, { headers: githubHeaders(token) }); + if (!response.ok) throw new Error(`GitHub ${path} could not be loaded`); + return await response.json() as Array<{ id: number; name?: string; login?: string }>; + }; + const [labels, assignees] = await Promise.all([load("labels"), load("assignees")]); + return json({ + statuses: [{ id: "open", name: "Open" }, { id: "closed", name: "Closed" }], + labels: labels.map(label => ({ id: String(label.id), name: label.name ?? String(label.id) })), + users: assignees.map(user => ({ id: String(user.id), name: user.login ?? String(user.id) })), + }); + } + private async validateSource(input: PipeInput): Promise { if (!input.source || input.source.kind === "linear") { const projectId = input.source?.kind === "linear" ? input.source.projectId : input.projectId; diff --git a/packages/app/src/trigger-context.ts b/packages/app/src/trigger-context.ts index d35e52e8..5400dcdc 100644 --- a/packages/app/src/trigger-context.ts +++ b/packages/app/src/trigger-context.ts @@ -27,6 +27,12 @@ export const triggerContextCatalog: Record = { ], github: [...commonWebhook, { path: "action", type: "string", description: "GitHub webhook action." }, + { path: "issue", type: "object", description: "Complete GitHub issue payload." }, + { path: "issue.number", type: "number", description: "Issue number.", example: 42 }, + { path: "issue.title", type: "string", description: "Issue title." }, + { path: "issue.body", type: "string", description: "Issue body, when present." }, + { path: "issue.html_url", type: "string", description: "Issue URL." }, + { path: "issue.state", type: "string", description: "Current issue state." }, { path: "pull_request", type: "object", description: "Complete GitHub pull request payload." }, { path: "pull_request.number", type: "number", description: "Pull request number.", example: 42 }, { path: "pull_request.title", type: "string", description: "Pull request title." }, diff --git a/packages/app/src/ui.ts b/packages/app/src/ui.ts index 339dafcb..bd792806 100644 --- a/packages/app/src/ui.ts +++ b/packages/app/src/ui.ts @@ -70,13 +70,13 @@ 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:[],options:{statuses:[],users:[],labels:[]},githubOptions:{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',github:'GitHub Issues',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 +90,9 @@ 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(', ')} +const githubRuleOptions=type=>type==='status'?resources.githubOptions.statuses:type==='label'?resources.githubOptions.labels:resources.githubOptions.users; +const githubRuleSummary=rule=>ruleLabels[rule.type]+' is '+nameOf(githubRuleOptions(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.matchRules?.map(githubRuleSummary).join(' + ')||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,12 +112,17 @@ 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 githubRuleRows(){return [...$('#github-rules').querySelectorAll('[data-github-rule]')]} +function syncGithubRuleButtons(){const rows=githubRuleRows();rows.forEach(row=>row.querySelector('[data-remove-github-rule]').classList.toggle('invisible',rows.length===1))} +function addGithubRule(rule={type:'status',targetId:''}){const row=document.createElement('div');row.dataset.githubRule='';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=['status','label','assignee','creator'].map(value=>'').join('');type.value=rule.type==='owner'?'assignee':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(),''),...githubRuleOptions(type.value).map(item=>new Option(item.name,item.id)));value.value=type.value===(rule.type==='owner'?'assignee':rule.type)?rule.targetId:''};type.onchange=fill;fill();valueLabel.append(value);const remove=document.createElement('button');remove.type='button';remove.dataset.removeGithubRule='';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();syncGithubRuleButtons()};row.append(typeLabel,valueLabel,remove);$('#github-rules').append(row);syncGithubRuleButtons()} +function readGithubRules(){return githubRuleRows().map(row=>{const [type,target]=row.querySelectorAll('select');return {type:type.value,targetId:target.value}})} +async function syncGithubIssueOptions(){const installationId=triggerForm.elements.installationId.value,repositoryId=triggerForm.elements.repositoryId.value;resources.githubOptions={statuses:[],users:[],labels:[]};if(installationId&&repositoryId)resources.githubOptions=await request('/api/github/installations/'+encodeURIComponent(installationId)+'/repositories/'+encodeURIComponent(repositoryId)+'/issue-options');githubRuleRows().forEach(row=>{const [type,value]=row.querySelectorAll('select'),selected=value.value;value.replaceChildren(new Option('Choose '+ruleLabels[type.value].toLowerCase(),''),...githubRuleOptions(type.value).map(item=>new Option(item.name,item.id)));value.value=selected})} +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);$('#github-rules').replaceChildren();(c.matchRules?.length?c.matchRules:[{type:'status',targetId:''}]).forEach(addGithubRule);await syncGithubIssueOptions()}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()} 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==='github')return {kind:'webhook',config:{provider:'github',installationId:Number(triggerForm.elements.installationId.value),repositoryId:Number(triggerForm.elements.repositoryId.value),matchRules:readGithubRules(),...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||!candidate.config.matchRules.length||candidate.config.matchRules.some(rule=>!rule.targetId)))throw new Error('Choose a GitHub installation, repository, and a value for every matching rule.');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-github-rule').onclick=()=>addGithubRule();$('#cancel-trigger').onclick=()=>dialog.close();triggerForm.elements.installationId.onchange=async()=>{await syncRepositories();$('#github-rules').replaceChildren();addGithubRule();await syncGithubIssueOptions()};triggerForm.elements.repositoryId.onchange=()=>syncGithubIssueOptions();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}}; diff --git a/packages/app/src/webhook-trigger.ts b/packages/app/src/webhook-trigger.ts index 37fcf608..6a83a7e8 100644 --- a/packages/app/src/webhook-trigger.ts +++ b/packages/app/src/webhook-trigger.ts @@ -1,6 +1,7 @@ import { matchingIssue } from "./matcher"; import type { MatchRule } from "./types"; import { validateHandlerCode } from "./custom-handler"; +import { matchingGitHubIssue } from "./github-issue-matcher"; export type WebhookProvider = "linear" | "github" | "cloudflareTail"; export type WebhookTriggerConfig = { @@ -22,7 +23,9 @@ export function adaptWebhook(config: WebhookTriggerConfig, provider: WebhookProv } 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; + if (config.matchRules?.length) { + if (eventName !== "issues" || !matchingGitHubIssue(payload, config.matchRules)) return null; + } else if ((eventName ?? "") !== (config.event ?? "pull_request") || payload.action !== (config.action ?? "dequeued")) return null; } const normalizedProvider = provider === "cloudflareTail" ? "cloudflare" : provider; const providerAliases = provider === "linear" diff --git a/packages/app/test/github-issue-matcher.test.ts b/packages/app/test/github-issue-matcher.test.ts new file mode 100644 index 00000000..6b344141 --- /dev/null +++ b/packages/app/test/github-issue-matcher.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from "vitest"; +import { matchingGitHubIssue } from "../src/github-issue-matcher"; + +const issue = { state: "open", user: { id: 1 }, assignees: [{ id: 2 }], labels: [{ id: 3 }] }; + +describe("matchingGitHubIssue", () => { + it("matches all rules when a newly opened issue enters the set", () => { + expect(matchingGitHubIssue({ action: "opened", issue }, [ + { type: "status", targetId: "open" }, { type: "label", targetId: "3" }, { type: "assignee", targetId: "2" }, { type: "creator", targetId: "1" }, + ])).toBe(true); + }); + + it("matches a label event only when that label completes the set", () => { + const rules = [{ type: "status" as const, targetId: "open" }, { type: "label" as const, targetId: "3" }]; + expect(matchingGitHubIssue({ action: "labeled", label: { id: 3 }, issue }, rules)).toBe(true); + expect(matchingGitHubIssue({ action: "labeled", label: { id: 4 }, issue }, rules)).toBe(false); + }); + + it("does not run for unrelated changes or partial matches", () => { + expect(matchingGitHubIssue({ action: "edited", issue }, [{ type: "status", targetId: "open" }])).toBe(false); + expect(matchingGitHubIssue({ action: "opened", issue }, [{ type: "status", targetId: "closed" }])).toBe(false); + }); +}); diff --git a/packages/app/test/trigger-context.test.ts b/packages/app/test/trigger-context.test.ts index e75a86d7..2a4bd12a 100644 --- a/packages/app/test/trigger-context.test.ts +++ b/packages/app/test/trigger-context.test.ts @@ -11,6 +11,7 @@ describe("trigger context reflection", () => { } expect(triggerContextCatalog.linear).toContainEqual(expect.objectContaining({ path: "issue.title", type: "string" })); expect(triggerContextCatalog.github).toContainEqual(expect.objectContaining({ path: "pull_request.number", type: "number" })); + expect(triggerContextCatalog.github).toContainEqual(expect.objectContaining({ path: "issue.title", type: "string" })); }); it("preserves the slug and explicitly marks unknown handler output", () => { diff --git a/packages/app/test/ui.test.ts b/packages/app/test/ui.test.ts index 8711d29e..0653b508 100644 --- a/packages/app/test/ui.test.ts +++ b/packages/app/test/ui.test.ts @@ -52,6 +52,9 @@ describe("pages", () => { const html = jobPage({ email: "owner@example.com" }); expect(html).toContain('id="linear-rules"'); expect(html).toContain('id="add-linear-rule"'); + expect(html).toContain('id="github-rules"'); + expect(html).toContain('id="add-github-rule"'); + expect(html).toContain("matchRules:readGithubRules()"); expect(html).toContain("status:'Status',label:'Label',assignee:'Assignee',creator:'Creator',owner:'Owner'"); expect(html).toContain("matchRules:readLinearRules()"); expect(html).toContain("(c.matchRules?.length?c.matchRules:"); diff --git a/packages/app/test/webhook-trigger.test.ts b/packages/app/test/webhook-trigger.test.ts index 8befeb78..4ecc0b95 100644 --- a/packages/app/test/webhook-trigger.test.ts +++ b/packages/app/test/webhook-trigger.test.ts @@ -14,6 +14,13 @@ describe("webhook Job trigger adapters", () => { expect(adaptWebhook(config, "github", "github:d2", { installation: { id: 7 }, repository: { id: 10 }, action: "dequeued" }, "pull_request")).toBeNull(); }); + it("matches GitHub issue filters", () => { + const config = { provider: "github" as const, installationId: 7, repositoryId: 9, matchRules: [{ type: "label" as const, targetId: "3" }] }; + const payload = { installation: { id: 7 }, repository: { id: 9 }, action: "labeled", label: { id: 3 }, issue: { state: "open", labels: [{ id: 3 }] } }; + expect(adaptWebhook(config, "github", "github:d3", payload, "issues")).not.toBeNull(); + expect(adaptWebhook(config, "github", "github:d4", payload, "pull_request")).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 }); });