diff --git a/src/index.ts b/src/index.ts index c3993512..be2c439a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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"; @@ -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); @@ -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"); diff --git a/src/tenant.ts b/src/tenant.ts index 2863a995..78886385 100644 --- a/src/tenant.ts +++ b/src/tenant.ts @@ -126,7 +126,7 @@ export class Tenant extends DurableObject { (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); @@ -288,11 +288,17 @@ export class Tenant extends DurableObject { return json({ ok: true }); } - private async flowDetail(flowId: string): Promise { + private async flowDetail(flowId: string, url: URL): Promise { 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); @@ -301,7 +307,7 @@ export class Tenant extends DurableObject { // 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 { diff --git a/src/ui.ts b/src/ui.ts index e13c91fd..987e6471 100644 --- a/src/ui.ts +++ b/src/ui.ts @@ -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, `

Start with Linear

Connect your workspace to create your first flow.

Connect Linear
`); -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, `
← My Flows

Loading flow activity…

@@ -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, ` +
← My Flows

Loading agent runs…

`, ` +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=>''+esc(value)+''; +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 ''+esc(id)+' ↗'}; +const detail=(title,value)=>value?'

'+title+'

'+esc(value)+'
':''; +const pager=p=>p.page===1&&!p.hasNext?'':''; +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='

Could not load this flow.

';return}const data=await response.json(),flow=data.flow,pagination=data.pagination||{page:1,hasNext:false},panels=(data.runs||[]).map(run=>'
'+esc(run.issue_title||run.issue_id)+''+issueLink(run.issue_id,run.issue_url)+''+esc(run.agent_kind||flow.agent_kind||'Herdr agent')+' · '+esc(run.agent_name)+''+badge(run.state)+''+time(run.updated_at)+'
'+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)+'
').join('')||'

No agent runs yet.

';root.innerHTML='

'+esc(flow.name)+'

'+esc(flow.filter_type)+' trigger · '+esc(flow.max_concurrency)+' concurrent agents · '+esc(flow.agent_kind||'Herdr agent')+' · workspace '+esc(flow.workspace_name||'—')+'

Webhook activityEdit Flow

Agent runs

Open a run page or expand a row to inspect its output.

'+panels+pager(pagination)+'
'}load(); +`); + +export const flowWebhooksPage = (viewer: { email: string }, flowId: string) => shell("Webhook activity — Factorize", viewer, ` +

Loading webhook activity…

`, ` +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 ''+esc(id)+' ↗'}; +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='

Could not load webhook activity.

';return}const data=await response.json(),p=data.pagination||{page:1,hasNext:false},rows=(data.events||[]).map(event=>''+time(event.received_at)+''+issueLink(event.issue_id,event.issue_url)+''+esc(event.event_type)+' · '+esc(event.event_action)+''+esc(event.outcome)+''+esc(event.detail)+'').join('')||'No relevant webhooks yet.',pager=p.page===1&&!p.hasNext?'':'';root.innerHTML='← '+esc(data.flow.name)+'

Webhook activity

Relevant webhooks and whether they queued an agent.

'+rows+'
ReceivedIssueEventResultDetails
'+pager+'
'}load(); +`); + export const runDetailPage = (viewer: { email: string }, runId: string) => shell("Agent run — Factorize", viewer, `

Loading agent run…

diff --git a/test/ui.test.ts b/test/ui.test.ts index d06d9066..3e2fa430 100644 --- a/test/ui.test.ts +++ b/test/ui.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { flowDetailPage, flowPage, flowsPage, landingPage, runDetailPage } from "../src/ui"; +import { flowDetailPage, flowPage, flowWebhooksPage, flowsPage, landingPage, runDetailPage } from "../src/ui"; describe("pages", () => { const expectInlineScriptsToParse = (html: string) => { @@ -57,22 +57,29 @@ describe("pages", () => { expect(html).toContain("r.ok&&body.ok"); }); - it("renders flow-level webhook and agent-run activity", () => { + it("renders paginated agent runs with links to run and webhook pages", () => { const html = flowDetailPage({ email: "owner@example.com" }, "flow-1"); - expect(html).toContain("Webhook activity"); expect(html).toContain("Agent runs"); - expect(html).toContain("/api/pipes/"); - expect(html).toContain("whether they queued an agent"); + expect(html).toContain("?view=runs&page="); + expect(html).toContain("/webhooks"); + expect(html).toContain("/runs/"); expect(html).toContain("Edit Flow"); expect(html).toContain("issueLink"); expect(html).toContain("Prompt sent to agent"); expect(html).toContain("Full agent output"); expect(html).toContain("issue_title"); - expect(html).toContain("data-run-href"); expect(html).toContain('max-h-[32rem] overflow-auto'); expectInlineScriptsToParse(html); }); + it("renders webhook activity on its own paginated page", () => { + const html = flowWebhooksPage({ email: "owner@example.com" }, "flow-1"); + expect(html).toContain("Webhook activity"); + expect(html).toContain("?view=events&page="); + expect(html).toContain("whether they queued an agent"); + expectInlineScriptsToParse(html); + }); + it("renders an agent run page", () => { const html = runDetailPage({ email: "owner@example.com" }, "run-1"); expect(html).toContain("/api/runs/"); diff --git a/test/worker.test.ts b/test/worker.test.ts index 74ea5a26..392c69e0 100644 --- a/test/worker.test.ts +++ b/test/worker.test.ts @@ -88,6 +88,19 @@ describe("Worker routes", () => { await expect(response.json()).resolves.toEqual(activity); }); + it("forwards flow activity pagination to the Durable Object", async () => { + let forwarded: URL | undefined; + const response = await app.request("https://factorize.test/api/pipes/flow-1?view=events&page=3", { + headers: { cookie: await sessionCookie() }, + }, testEnv(request => { + if (new URL(request.url).pathname === "/members/user-1") return Response.json({ role: "owner", session_version: 1 }); + forwarded = new URL(request.url); + return Response.json({ flow: {}, events: [], runs: [], pagination: { page: 3, hasNext: false } }); + })); + expect(response.status).toBe(200); + expect(forwarded?.search).toBe("?view=events&page=3"); + }); + it("returns an agent run through the authenticated Durable Object boundary", async () => { const run = { id: "run-1", issue_title: "Fix the thing" }; const response = await app.request("https://factorize.test/api/runs/run-1", {