diff --git a/src/index.ts b/src/index.ts index 4ed9c26b..c3993512 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 } from "./ui"; +import { flowDetailPage, flowPage, flowsPage, landingPage, runDetailPage } from "./ui"; import type { Env } from "./types"; import type { CustomSource, PipeInput } from "./types"; import { invokeCustomHandler, prepareCustomHandler, validateCustomHandler } from "./custom-handler"; @@ -109,6 +109,10 @@ app.get("/api/runs", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); return tenant(c, session.tenantId).fetch("https://tenant/runs"); }); +app.get("/api/runs/:id", async (c) => { + const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); + return tenant(c, session.tenantId).fetch(`https://tenant/runs/${encodeURIComponent(c.req.param("id"))}`); +}); 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"); @@ -294,6 +298,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("/runs/:id", async (c) => { + const session = await owner(c); + if (!session) return c.redirect("/auth/linear"); + return c.html(render(runDetailPage({ email: session.email }, c.req.param("id")), c.get("cspNonce"))); +}); export { Tenant, GitHubInstallationRegistry }; export default app; diff --git a/src/tenant.ts b/src/tenant.ts index b0163188..2863a995 100644 --- a/src/tenant.ts +++ b/src/tenant.ts @@ -102,6 +102,7 @@ export class Tenant extends DurableObject { this.ensureColumn("pipes", "cwd", "TEXT NOT NULL DEFAULT ''"); this.ensureColumn("flow_events", "issue_url", "TEXT"); this.ensureColumn("runs", "issue_url", "TEXT"); + this.ensureColumn("runs", "issue_title", "TEXT NOT NULL DEFAULT ''"); this.ensureColumn("runs", "workspace_name", "TEXT NOT NULL DEFAULT ''"); this.ensureColumn("runs", "agent_kind", "TEXT NOT NULL DEFAULT ''"); this.ensureColumn("runs", "exec_request", "TEXT"); @@ -127,6 +128,7 @@ export class Tenant extends DurableObject { 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 === "/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); if (request.method === "GET" && /^\/v1\/runs\/[^/]+$/.test(url.pathname)) return await this.getRun(decodeURIComponent(url.pathname.split("/")[3] ?? "")); if (request.method === "POST" && /^\/v1\/runs\/[^/]+\/stop$/.test(url.pathname)) return await this.stopRun(decodeURIComponent(url.pathname.split("/")[3] ?? "")); @@ -290,7 +292,7 @@ export class Tenant extends DurableObject { 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_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 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); 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); @@ -302,6 +304,15 @@ export class Tenant extends DurableObject { return json({ flow, events, runs }); } + private async runDetail(runId: string): Promise { + const run = this.one("SELECT runs.*, pipes.name AS flow_name FROM runs JOIN pipes ON pipes.id = runs.pipe_id WHERE runs.id = ?", runId); + if (!run) return new Response("Not found", { status: 404 }); + for (const field of ["prompt", "exec_request", "exec_response", "result"] as const) { + if (run.state !== "ignored" && typeof run[field] === "string" && run[field]) run[field] = await decrypt(String(run[field]), this.env.CREDENTIAL_ENCRYPTION_KEY); + } + return json(run); + } + private getFlow(flowId: string): Response { const flow = this.one("SELECT id, name, project_id, match_rules, source_kind, source_config, max_concurrency, workspace_name, agent_kind, cwd, COALESCE(NULLIF(context_template, ''), ?) AS context_template, enabled, created_at FROM pipes WHERE id = ?", DEFAULT_CONTEXT_TEMPLATE, flowId); return flow ? json(flow) : new Response("Not found", { status: 404 }); @@ -497,7 +508,7 @@ export class Tenant extends DurableObject { try { this.ctx.storage.sql.exec("INSERT INTO active_claims (pipe_id,issue_id,run_id) VALUES (?,?,?)", pipe.id, workItem.claimKey, runId); } catch { this.recordFlowEvent(pipe, deliveryId, workItem.identifier, workItem.url, workItem.event as any, "duplicate", "An active or queued run already owns this work item.", workItem.provider); return; } const prompt = await encrypt(plaintextPrompt, this.env.CREDENTIAL_ENCRYPTION_KEY); - this.ctx.storage.sql.exec("INSERT INTO runs (id,pipe_id,issue_id,issue_url,claim_key,agent_name,workspace_name,agent_kind,state,prompt,provider,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", runId, pipe.id, workItem.identifier, workItem.url, workItem.claimKey, `factorize-${runId}`, String(pipe.workspace_name ?? ""), String(pipe.agent_kind ?? ""), "queued", prompt, workItem.provider, now(), now()); + this.ctx.storage.sql.exec("INSERT INTO runs (id,pipe_id,issue_id,issue_title,issue_url,claim_key,agent_name,workspace_name,agent_kind,state,prompt,provider,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)", runId, pipe.id, workItem.identifier, workItem.title, workItem.url, workItem.claimKey, `factorize-${runId}`, String(pipe.workspace_name ?? ""), String(pipe.agent_kind ?? ""), "queued", prompt, workItem.provider, now(), now()); const active = this.one("SELECT count(*) AS count FROM runs WHERE pipe_id=? AND state IN ('starting','running','blocked','recovering')", pipe.id) as Row; this.recordFlowEvent(pipe, deliveryId, workItem.identifier, workItem.url, workItem.event as any, Number(active.count) < Number(pipe.max_concurrency) ? "accepted" : "queued_capacity", Number(active.count) < Number(pipe.max_concurrency) ? "Handler accepted delivery; agent queued to start." : "Handler accepted delivery; queued for capacity.", workItem.provider); } diff --git a/src/ui.ts b/src/ui.ts index edac66a7..e13c91fd 100644 --- a/src/ui.ts +++ b/src/ui.ts @@ -140,7 +140,7 @@ const esc=v=>{const d=document.createElement('div');d.textContent=v??'';return d const time=v=>new Date(v).toLocaleString(); const badge=(value,good)=>''+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));const href=trusted?url:'https://linear.app/issue/'+encodeURIComponent(id);return ''+esc(id)+' ↗'}; -async function load(){const response=await fetch('/api/pipes/'+encodeURIComponent(flowId));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,events=data.events||[],runs=data.runs||[];const eventRows=events.map(event=>''+time(event.received_at)+''+issueLink(event.issue_id,event.issue_url)+''+esc(event.event_type)+' · '+esc(event.event_action)+''+badge(event.outcome,event.outcome==='triggered')+''+esc(event.detail)+'').join('')||'No relevant webhooks yet. Update an issue in this flow’s Linear project to see it here.';const runRows=runs.map(run=>''+issueLink(run.issue_id,run.issue_url)+''+esc(run.agent_kind||flow.agent_kind||'Herdr agent')+''+esc(run.agent_name)+''+esc(run.workspace_name||flow.workspace_name||'—')+''+badge(run.state,['queued','starting','running','recovering','done'].includes(run.state))+''+time(run.updated_at)+'').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||'—')+'

Edit Flow

Webhook activity

Relevant Linear webhooks and whether they queued an agent.

'+eventRows+'
ReceivedIssueEventResultDetails

Agent runs

'+runRows+'
IssueHerdr agentWorkspaceStateUpdated
'} +async function load(){const response=await fetch('/api/pipes/'+encodeURIComponent(flowId));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,events=data.events||[],runs=data.runs||[];const eventRows=events.map(event=>''+time(event.received_at)+''+issueLink(event.issue_id,event.issue_url)+''+esc(event.event_type)+' · '+esc(event.event_action)+''+badge(event.outcome,event.outcome==='triggered')+''+esc(event.detail)+'').join('')||'No relevant webhooks yet. Update an issue in this flow’s Linear project to see it here.';const runRows=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)+''+esc(run.workspace_name||flow.workspace_name||'—')+''+badge(run.state,['queued','starting','running','recovering','done'].includes(run.state))+''+time(run.updated_at)+'').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||'—')+'

Edit Flow

Webhook activity

Relevant Linear webhooks and whether they queued an agent.

'+eventRows+'
ReceivedIssueEventResultDetails

Agent runs

'+runRows+'
IssueHerdr agentWorkspaceStateUpdated
';root.querySelectorAll('[data-run-href]').forEach(row=>{row.onclick=e=>{if(!e.target.closest('a'))location.href=row.dataset.runHref};row.onkeydown=e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();location.href=row.dataset.runHref}}})} const renderActivity=load; load=async()=>{await renderActivity();const response=await fetch('/api/pipes/'+encodeURIComponent(flowId));if(!response.ok)return;const data=await response.json(),runs=(data.runs||[]).filter(run=>run.state!=='ignored');if(!runs.length)return;const diagnostics=runs.map(run=>'
'+esc(run.agent_name)+''+(run.exec_status!=null?'HTTP '+esc(String(run.exec_status))+(run.exec_exit_code!=null?' · VM exit '+esc(String(run.exec_exit_code)):'' ):esc(run.state))+'
'+(run.exec_status!=null?'

Exact command submitted to exe.dev

'+esc(run.exec_request)+'

Actual exe.dev response

'+esc(run.exec_response)+'
':'

No exe.dev request or response was recorded for this run. It did not reach the VM-command step.

')+(run.result?'

Herdr agent output

'+esc(run.result)+'
':'')+'
').join('');root.insertAdjacentHTML('beforeend','

Actual exe.dev command results

Only real agent runs appear here. The bearer token is never shown.

'+diagnostics+'
')}; // Keep run details with the run they belong to. The native disclosure control @@ -149,6 +149,17 @@ load=async()=>{await renderActivity();const response=await fetch('/api/pipes/'+e load(); `); +export const runDetailPage = (viewer: { email: string }, runId: string) => shell("Agent run — Factorize", viewer, ` +
+

Loading agent run…

+
`, ` +const root=document.querySelector('#run-detail'),runId=root.dataset.runId; +const esc=v=>{const d=document.createElement('div');d.textContent=v??'';return d.innerHTML}; +const time=v=>new Date(v).toLocaleString(); +const section=(title,value)=>value?'

'+title+'

'+esc(value)+'
':''; +async function load(){const response=await fetch('/api/runs/'+encodeURIComponent(runId));if(response.status===401)return location.href='/auth/linear';if(!response.ok){root.innerHTML='← My Flows

This agent run could not be found.

';return}const run=await response.json(),trusted=typeof run.issue_url==='string'&&(run.issue_url.startsWith('https://linear.app/')||/^https:\\/\\/github\\.com\\/[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+\\/pull\\/\\d+$/.test(run.issue_url)),issueHref=trusted?run.issue_url:'https://linear.app/issue/'+encodeURIComponent(run.issue_id);root.innerHTML='← '+esc(run.flow_name||'Flow')+'

'+esc(run.issue_id)+' ↗

'+esc(run.issue_title||run.issue_id)+'

'+esc(run.agent_kind||'Herdr agent')+' · '+esc(run.agent_name)+'

'+esc(run.state)+'
Workspace
'+esc(run.workspace_name||'—')+'
Created
'+time(run.created_at)+'
Updated
'+time(run.updated_at)+'
Exit status
'+(run.exec_status!=null?'HTTP '+esc(String(run.exec_status))+(run.exec_exit_code!=null?' · VM '+esc(String(run.exec_exit_code)):''):'—')+'
'+section('Prompt sent to agent',run.prompt)+section('Exact command submitted to exe.dev',run.exec_request)+section('Actual exe.dev response',run.exec_response)+section('Full agent output',run.result)}load(); +`); + export const flowsPage = (viewer: { email: string }) => shell("My Flows — Factorize", viewer, `

My Flows

Your source-to-Herdr automations.

Create Flow
diff --git a/test/ui.test.ts b/test/ui.test.ts index 367f0045..d06d9066 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 } from "../src/ui"; +import { flowDetailPage, flowPage, flowsPage, landingPage, runDetailPage } from "../src/ui"; describe("pages", () => { const expectInlineScriptsToParse = (html: string) => { @@ -67,10 +67,21 @@ describe("pages", () => { 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 an agent run page", () => { + const html = runDetailPage({ email: "owner@example.com" }, "run-1"); + expect(html).toContain("/api/runs/"); + expect(html).toContain("Prompt sent to agent"); + expect(html).toContain("Exact command submitted to exe.dev"); + expect(html).toContain("Full agent output"); + expectInlineScriptsToParse(html); + }); + it("renders flow status and active agent capacity without trigger details", () => { const html = flowsPage({ email: "owner@example.com" }); expect(html).toContain("active_agents"); diff --git a/test/worker.test.ts b/test/worker.test.ts index e87b90da..74ea5a26 100644 --- a/test/worker.test.ts +++ b/test/worker.test.ts @@ -88,6 +88,15 @@ describe("Worker routes", () => { await expect(response.json()).resolves.toEqual(activity); }); + 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", { + headers: { cookie: await sessionCookie() }, + }, testEnv(ownerHandler({ "/runs/run-1": Response.json(run) }))); + expect(response.status).toBe(200); + await expect(response.json()).resolves.toEqual(run); + }); + it("preserves a useful upstream GraphQL error instead of turning it into a 500", async () => { const response = await app.request("https://factorize.test/api/linear/projects", { headers: { cookie: await sessionCookie() },