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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { equalHmac, hmac } from "./crypto";
import { Tenant } from "./tenant";
import { GitHubInstallationRegistry } from "./github-registry";
import { createAppJwt, githubHeaders, readSetupState, signSetupState } from "./github";
import { flowDetailPage, flowPage, flowsPage, landingPage, runDetailPage } from "./ui";
import { flowDetailPage, flowPage, flowWebhooksPage, flowsPage, landingPage, runDetailPage } from "./ui";
import type { Env } from "./types";
import type { CustomSource, PipeInput } from "./types";
import { invokeCustomHandler, prepareCustomHandler, validateCustomHandler } from "./custom-handler";
Expand Down Expand Up @@ -103,7 +103,9 @@ app.get("/api/pipes", async (c) => {
});
app.get("/api/pipes/:id", async (c) => {
const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401);
return tenant(c, session.tenantId).fetch(`https://tenant/pipes/${encodeURIComponent(c.req.param("id"))}`);
const url = new URL(`https://tenant/pipes/${encodeURIComponent(c.req.param("id"))}`);
for (const key of ["view", "page"]) { const value = c.req.query(key); if (value) url.searchParams.set(key, value); }
return tenant(c, session.tenantId).fetch(url);
});
app.get("/api/runs", async (c) => {
const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401);
Expand Down Expand Up @@ -298,6 +300,11 @@ app.get("/flows/:id/edit", async (c) => {
if (!session) return c.redirect("/auth/linear");
return c.html(render(flowPage({ email: session.email }, c.req.param("id")), c.get("cspNonce")));
});
app.get("/flows/:id/webhooks", async (c) => {
const session = await owner(c);
if (!session) return c.redirect("/auth/linear");
return c.html(render(flowWebhooksPage({ email: session.email }, c.req.param("id")), c.get("cspNonce")));
});
app.get("/runs/:id", async (c) => {
const session = await owner(c);
if (!session) return c.redirect("/auth/linear");
Expand Down
16 changes: 11 additions & 5 deletions src/tenant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ export class Tenant extends DurableObject<Env> {
(SELECT count(*) FROM runs WHERE runs.pipe_id = pipes.id AND runs.state IN ('starting','running','blocked','recovering')) AS active_agents,
(SELECT state FROM runs WHERE runs.pipe_id = pipes.id ORDER BY updated_at DESC, id DESC LIMIT 1) AS latest_run_state
FROM pipes ORDER BY created_at DESC`));
if (request.method === "GET" && url.pathname.startsWith("/pipes/")) return await this.flowDetail(url.pathname.split("/")[2] ?? "");
if (request.method === "GET" && url.pathname.startsWith("/pipes/")) return await this.flowDetail(url.pathname.split("/")[2] ?? "", url);
if (request.method === "GET" && url.pathname === "/runs") return json(this.rows("SELECT id, pipe_id, issue_id, agent_name, state, created_at, updated_at FROM runs ORDER BY created_at DESC LIMIT 100"));
if (request.method === "GET" && /^\/runs\/[^/]+$/.test(url.pathname)) return await this.runDetail(decodeURIComponent(url.pathname.split("/")[2] ?? ""));
if (request.method === "GET" && url.pathname === "/v1/runs") return this.listRuns(url);
Expand Down Expand Up @@ -288,11 +288,17 @@ export class Tenant extends DurableObject<Env> {
return json({ ok: true });
}

private async flowDetail(flowId: string): Promise<Response> {
private async flowDetail(flowId: string, url: URL): Promise<Response> {
const flow = this.one("SELECT id, name, project_id, filter_type, filter_target_id, match_rules, source_kind, source_config, trigger_kind, trigger_config, max_concurrency, workspace_name, agent_kind, exe_connection_id, cwd, COALESCE(NULLIF(context_template, ''), ?) AS context_template, enabled, created_at FROM pipes WHERE id = ?", DEFAULT_CONTEXT_TEMPLATE, flowId);
if (!flow) return new Response("Not found", { status: 404 });
const events = this.rows("SELECT id, delivery_id, issue_id, issue_url, event_type, event_action, outcome, detail, provider, received_at FROM flow_events WHERE flow_id = ? ORDER BY received_at DESC LIMIT 100", flowId);
const runs = this.rows("SELECT id, issue_id, issue_title, issue_url, claim_key, agent_name, workspace_name, agent_kind, state, provider, prompt, result, created_at, updated_at, exec_request, exec_response, exec_status, exec_exit_code, recovery_reason, recovery_attempt, recovery_last_action, recovery_started_at FROM runs WHERE pipe_id = ? ORDER BY created_at DESC LIMIT 100", flowId);
const view = url.searchParams.get("view") === "events" ? "events" : "runs";
const page = Math.max(1, Math.min(10000, Number.parseInt(url.searchParams.get("page") ?? "1", 10) || 1));
const offset = (page - 1) * 10;
const events = view === "events" ? this.rows("SELECT id, delivery_id, issue_id, issue_url, event_type, event_action, outcome, detail, provider, received_at FROM flow_events WHERE flow_id = ? ORDER BY received_at DESC, id DESC LIMIT 11 OFFSET ?", flowId, offset) : [];
const runs = view === "runs" ? this.rows("SELECT id, issue_id, issue_title, issue_url, claim_key, agent_name, workspace_name, agent_kind, state, provider, prompt, result, created_at, updated_at, exec_request, exec_response, exec_status, exec_exit_code, recovery_reason, recovery_attempt, recovery_last_action, recovery_started_at FROM runs WHERE pipe_id = ? AND state != 'ignored' ORDER BY created_at DESC, id DESC LIMIT 11 OFFSET ?", flowId, offset) : [];
const hasNext = (view === "events" ? events : runs).length > 10;
if (events.length > 10) events.pop();
if (runs.length > 10) runs.pop();
await Promise.all(runs.map(async (run) => {
if (run.state !== "ignored" && typeof run.prompt === "string" && run.prompt) run.prompt = await decrypt(run.prompt, this.env.CREDENTIAL_ENCRYPTION_KEY);
if (typeof run.exec_request === "string" && run.exec_request) run.exec_request = await decrypt(run.exec_request, this.env.CREDENTIAL_ENCRYPTION_KEY);
Expand All @@ -301,7 +307,7 @@ export class Tenant extends DurableObject<Env> {
// a plain-text explanation. Only completed/failed agent output is encrypted.
if (run.state !== "ignored" && typeof run.result === "string" && run.result) run.result = await decrypt(run.result, this.env.CREDENTIAL_ENCRYPTION_KEY);
}));
return json({ flow, events, runs });
return json({ flow, events, runs, pagination: { page, hasNext } });
}

private async runDetail(runId: string): Promise<Response> {
Expand Down
18 changes: 17 additions & 1 deletion src/ui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ $('#test-handler').onclick=async()=>{const values=data($('#flow')),result=$('#ha
$('#flow').onsubmit=async e=>{e.preventDefault();$('#error').classList.add('hidden');const values=data(e.currentTarget),button=$('#submit'),editing=!!editFlowId;button.disabled=true;button.textContent=editing?'Saving…':'Creating…';try{const matchRules=readRules(),isGitHub=values.sourceKind==='github',isCustom=values.sourceKind==='custom';if(!isGitHub&&!isCustom&&matchRules.some(rule=>!rule.targetId))throw new Error('Choose a target for every matching rule.');if(!values.cwd)throw new Error('Choose a working directory.');if(isGitHub&&(!values.githubInstallation||!values.githubRepository))throw new Error('Choose an active GitHub installation and repository.');if(isCustom&&(!values.handlerName||!values.handlerCode))throw new Error('Provide a handler name and complete function.');let connectionId=values.exeConnection;if(!exeConnected){if(!values.vmName||!values.apiToken)throw new Error('Complete the new Exe.dev connection.');const r=await fetch('/api/connections/exe',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify({vmName:values.vmName,agentKind:values.agentKind,cwd:values.cwd,herdrCommand:values.herdrCommand,agentCommand:values.agentCommand,apiToken:values.apiToken})});const result=await r.json().catch(()=>({}));if(!r.ok)throw new Error(result.error||'Could not connect to Herdr.');connectionId=result.connectionId}const source=isGitHub?{kind:'github',installationId:Number(values.githubInstallation),repositoryId:Number(values.githubRepository),baseRef:'main',trigger:'merge_queue_conflict'}:isCustom?{kind:'custom',origin:values.customOrigin,handlerName:values.handlerName,handlerCode:values.handlerCode}:{kind:'linear',projectId:values.projectId,matchRules};const r=await fetch('/api/pipes'+(editing?'/'+encodeURIComponent(editFlowId):''),{method:editing?'PUT':'POST',headers:{'content-type':'application/json'},body:JSON.stringify({name:values.name,flowId:values.flowId,projectId:values.projectId,matchRules,source,contextTemplate:values.contextTemplate,maxConcurrency:Number(values.maxConcurrency),exeConnectionId:connectionId,cwd:values.cwd})});const result=await r.json().catch(()=>({}));if(!r.ok)throw new Error(result.error||'Could not save the flow.');location.href=editing?'/flows/'+encodeURIComponent(editFlowId):'/flows'}catch(err){showError(err.message||'Something went wrong.');button.disabled=false;button.textContent=editing?'Save Changes':'Create Flow'}};syncMaxConcurrency();init().then(syncMaxConcurrency);
`) : shell("Create Flow — Factorize", null, `<main class="mx-auto max-w-xl px-5 py-24 text-center"><h1 class="text-4xl font-bold tracking-tight">Start with Linear</h1><p class="mt-4 text-lg leading-8 text-slate-600 dark:text-slate-400">Connect your workspace to create your first flow.</p><a href="/auth/linear" class="mt-8 inline-flex rounded-xl bg-slate-950 px-6 py-3.5 text-sm font-semibold text-white hover:bg-slate-800 dark:bg-white dark:text-slate-950 dark:hover:bg-slate-200">Connect Linear</a></main>`);

export const flowDetailPage = (viewer: { email: string }, flowId: string) => shell("Flow activity — Factorize", viewer, `
const legacyFlowDetailPage = (viewer: { email: string }, flowId: string) => shell("Flow activity — Factorize", viewer, `
<main class="mx-auto max-w-5xl px-5 py-12 lg:px-8">
<a href="/flows" class="text-sm font-medium text-slate-500 hover:text-slate-950 dark:text-slate-400 dark:hover:text-white">← My Flows</a>
<div id="flow-detail" data-flow-id="${escapeHtml(flowId)}" class="mt-6"><p class="text-sm text-slate-500 dark:text-slate-400">Loading flow activity…</p></div>
Expand All @@ -149,6 +149,22 @@ load=async()=>{await renderActivity();const response=await fetch('/api/pipes/'+e
load();
`);

export const flowDetailPage = (viewer: { email: string }, flowId: string) => shell("Flow activity — Factorize", viewer, `
<main class="mx-auto max-w-5xl px-5 py-12 lg:px-8"><a href="/flows" class="text-sm font-medium text-slate-500 hover:text-slate-950">← My Flows</a><div id="flow-detail" data-flow-id="${escapeHtml(flowId)}" class="mt-6"><p class="text-sm text-slate-500">Loading agent runs…</p></div></main>`, `
const root=document.querySelector('#flow-detail'),flowId=root.dataset.flowId,esc=v=>{const d=document.createElement('div');d.textContent=v??'';return d.innerHTML},time=v=>new Date(v).toLocaleString(),badge=value=>'<span class="rounded-full bg-stone-100 px-2.5 py-1 text-xs font-medium text-slate-600 dark:bg-slate-800 dark:text-slate-300">'+esc(value)+'</span>';
const issueLink=(id,url)=>{if(!id)return '—';const trusted=typeof url==='string'&&(url.startsWith('https://linear.app/')||/^https:\\/\\/github\\.com\\/[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+\\/pull\\/\\d+$/.test(url)),href=trusted?url:'https://linear.app/issue/'+encodeURIComponent(id);return '<a class="font-medium text-factorize-700 hover:underline dark:text-factorize-500" href="'+href+'" target="_blank" rel="noreferrer">'+esc(id)+' ↗</a>'};
const detail=(title,value)=>value?'<div class="mt-4"><p class="mb-1 text-xs font-semibold uppercase tracking-wide text-slate-500">'+title+'</p><pre class="max-h-[32rem] overflow-auto whitespace-pre-wrap rounded-lg bg-slate-950 p-3 text-xs text-slate-100" tabindex="0">'+esc(value)+'</pre></div>':'';
const pager=p=>p.page===1&&!p.hasNext?'':'<nav class="flex items-center justify-between border-t border-stone-200 px-6 py-4 text-sm dark:border-slate-800"><span class="text-slate-500">Page '+p.page+'</span><span class="flex gap-3">'+(p.page>1?'<a class="font-semibold text-factorize-700" href="?page='+(p.page-1)+'">← Previous</a>':'')+(p.hasNext?'<a class="font-semibold text-factorize-700" href="?page='+(p.page+1)+'">Next →</a>':'')+'</span></nav>';
async function load(){const page=Math.max(1,parseInt(new URLSearchParams(location.search).get('page')||'1',10)||1),response=await fetch('/api/pipes/'+encodeURIComponent(flowId)+'?view=runs&page='+page);if(response.status===401)return location.href='/auth/linear';if(!response.ok){root.innerHTML='<p class="rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700">Could not load this flow.</p>';return}const data=await response.json(),flow=data.flow,pagination=data.pagination||{page:1,hasNext:false},panels=(data.runs||[]).map(run=>'<details class="border-t border-stone-200 first:border-t-0 dark:border-slate-800"><summary class="flex cursor-pointer list-none flex-wrap items-center justify-between gap-3 px-6 py-4 hover:bg-stone-50 dark:hover:bg-slate-800/60"><span class="min-w-0"><a href="/runs/'+encodeURIComponent(run.id)+'" class="block truncate font-semibold hover:text-factorize-700 hover:underline">'+esc(run.issue_title||run.issue_id)+'</a><span class="text-xs">'+issueLink(run.issue_id,run.issue_url)+'</span><span class="ml-3 text-sm text-slate-500">'+esc(run.agent_kind||flow.agent_kind||'Herdr agent')+' · '+esc(run.agent_name)+'</span></span><span class="flex items-center gap-3">'+badge(run.state)+'<span class="text-xs text-slate-500">'+time(run.updated_at)+'</span></span></summary><div class="border-t border-stone-200 px-6 pb-5 dark:border-slate-800">'+detail('Prompt sent to agent',run.prompt)+detail('Exact command submitted to exe.dev',run.exec_request)+detail('Actual exe.dev response',run.exec_response)+detail('Full agent output',run.result)+'</div></details>').join('')||'<p class="px-6 py-8 text-sm text-slate-500">No agent runs yet.</p>';root.innerHTML='<div class="flex flex-wrap items-start justify-between gap-4"><div><h1 class="text-3xl font-bold tracking-tight">'+esc(flow.name)+'</h1><p class="mt-2 text-slate-600 dark:text-slate-400">'+esc(flow.filter_type)+' trigger · '+esc(flow.max_concurrency)+' concurrent agents · '+esc(flow.agent_kind||'Herdr agent')+' · workspace '+esc(flow.workspace_name||'—')+'</p></div><span class="flex gap-3"><a href="/flows/'+encodeURIComponent(flow.id)+'/webhooks" class="rounded-xl border border-stone-300 px-4 py-2.5 text-sm font-semibold dark:border-slate-700">Webhook activity</a><a href="/flows/'+encodeURIComponent(flow.id)+'/edit" class="rounded-xl bg-slate-950 px-4 py-2.5 text-sm font-semibold text-white dark:bg-white dark:text-slate-950">Edit Flow</a></span></div><section class="mt-9 overflow-hidden rounded-2xl border border-stone-200 bg-white shadow-sm dark:border-slate-800 dark:bg-slate-900"><div class="border-b border-stone-200 px-6 py-5 dark:border-slate-800"><h2 class="font-semibold">Agent runs</h2><p class="mt-1 text-sm text-slate-500">Open a run page or expand a row to inspect its output.</p></div>'+panels+pager(pagination)+'</section>'}load();
`);

export const flowWebhooksPage = (viewer: { email: string }, flowId: string) => shell("Webhook activity — Factorize", viewer, `
<main class="mx-auto max-w-5xl px-5 py-12 lg:px-8"><div id="webhook-activity" data-flow-id="${escapeHtml(flowId)}"><p class="text-sm text-slate-500">Loading webhook activity…</p></div></main>`, `
const root=document.querySelector('#webhook-activity'),flowId=root.dataset.flowId,esc=v=>{const d=document.createElement('div');d.textContent=v??'';return d.innerHTML},time=v=>new Date(v).toLocaleString();
const issueLink=(id,url)=>{if(!id)return '—';const trusted=typeof url==='string'&&(url.startsWith('https://linear.app/')||/^https:\\/\\/github\\.com\\/[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+\\/pull\\/\\d+$/.test(url)),href=trusted?url:'https://linear.app/issue/'+encodeURIComponent(id);return '<a class="font-medium text-factorize-700 hover:underline" href="'+href+'" target="_blank" rel="noreferrer">'+esc(id)+' ↗</a>'};
async function load(){const page=Math.max(1,parseInt(new URLSearchParams(location.search).get('page')||'1',10)||1),response=await fetch('/api/pipes/'+encodeURIComponent(flowId)+'?view=events&page='+page);if(response.status===401)return location.href='/auth/linear';if(!response.ok){root.innerHTML='<p class="rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700">Could not load webhook activity.</p>';return}const data=await response.json(),p=data.pagination||{page:1,hasNext:false},rows=(data.events||[]).map(event=>'<tr class="border-t border-stone-200 dark:border-slate-800"><td class="py-3 pr-4 text-slate-500">'+time(event.received_at)+'</td><td class="py-3 pr-4">'+issueLink(event.issue_id,event.issue_url)+'</td><td class="py-3 pr-4">'+esc(event.event_type)+' · '+esc(event.event_action)+'</td><td class="py-3 pr-4">'+esc(event.outcome)+'</td><td class="py-3 text-slate-500">'+esc(event.detail)+'</td></tr>').join('')||'<tr><td colspan="5" class="py-8 text-slate-500">No relevant webhooks yet.</td></tr>',pager=p.page===1&&!p.hasNext?'':'<nav class="flex items-center justify-between border-t border-stone-200 px-6 py-4 text-sm"><span class="text-slate-500">Page '+p.page+'</span><span class="flex gap-3">'+(p.page>1?'<a class="font-semibold text-factorize-700" href="?page='+(p.page-1)+'">← Previous</a>':'')+(p.hasNext?'<a class="font-semibold text-factorize-700" href="?page='+(p.page+1)+'">Next →</a>':'')+'</span></nav>';root.innerHTML='<a href="/flows/'+encodeURIComponent(flowId)+'" class="text-sm font-medium text-slate-500 hover:text-slate-950">← '+esc(data.flow.name)+'</a><div class="mt-6"><h1 class="text-3xl font-bold tracking-tight">Webhook activity</h1><p class="mt-2 text-slate-600">Relevant webhooks and whether they queued an agent.</p></div><section class="mt-9 overflow-hidden rounded-2xl border border-stone-200 bg-white shadow-sm dark:border-slate-800 dark:bg-slate-900"><div class="overflow-x-auto px-6"><table class="w-full text-left text-sm"><thead class="text-xs uppercase tracking-wide text-slate-500"><tr><th class="py-3 pr-4">Received</th><th class="py-3 pr-4">Issue</th><th class="py-3 pr-4">Event</th><th class="py-3 pr-4">Result</th><th class="py-3">Details</th></tr></thead><tbody>'+rows+'</tbody></table></div>'+pager+'</section>'}load();
`);

export const runDetailPage = (viewer: { email: string }, runId: string) => shell("Agent run — Factorize", viewer, `
<main class="mx-auto max-w-5xl px-5 py-12 lg:px-8">
<div id="run-detail" data-run-id="${escapeHtml(runId)}"><p class="text-sm text-slate-500 dark:text-slate-400">Loading agent run…</p></div>
Expand Down
Loading