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
17 changes: 16 additions & 1 deletion packages/app/src/tenant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -876,7 +876,7 @@ export class TenantV2 extends DurableObject<Env> {
}

private async getRun(runId: string): Promise<Response> {
const run = this.one(`SELECT r.id, r.pipe_id AS job_id, r.issue_id, r.issue_url, r.agent_name, r.workspace_name, r.agent_kind, r.state, r.provider, r.execution_backend_kind AS backend_kind, r.execution_capabilities AS capabilities, r.destination_url, r.result, r.exec_status, r.exec_exit_code, r.recovery_last_action, r.created_at, r.updated_at,
const run = this.one(`SELECT r.id, r.pipe_id AS job_id, r.issue_id, r.issue_url, r.agent_name, r.workspace_name, r.agent_kind, r.state, r.provider, r.execution_backend_kind AS backend_kind, r.execution_handle, r.execution_capabilities AS capabilities, r.destination_url, r.result, r.exec_status, r.exec_exit_code, r.recovery_last_action, r.created_at, r.updated_at,
i.id AS invocation_id, i.job_id AS invocation_job_id, i.source AS invocation_source, i.claim_key AS invocation_claim_key, i.trigger_id AS invocation_trigger_id, i.context, i.occurrence AS invocation_occurrence, i.created_at AS invocation_created_at
FROM runs r LEFT JOIN job_runs jr ON jr.id = r.id LEFT JOIN invocations i ON i.id = jr.invocation_id WHERE r.id = ?`, runId);
if (!run) return new Response("Not found", { status: 404 });
Expand All @@ -897,6 +897,21 @@ export class TenantV2 extends DurableObject<Env> {
if (run.state !== "ignored" && typeof run.result === "string" && run.result) run.result = await decrypt(run.result, this.env.CREDENTIAL_ENCRYPTION_KEY);
run.activity = this.rows("SELECT action, detail, created_at FROM run_activity WHERE run_id = ? ORDER BY created_at, id", runId);
this.presentExecution(run);
if (["starting", "running", "blocked", "stopping"].includes(String(run.state)) && (run.capabilities as unknown[]).includes("output")) {
const pipe = this.executionConfig(run.job_id);
if (pipe && String(run.backend_kind) === "exe-herdr") {
const connection = await this.connectionForPipe(pipe);
if (connection) {
try {
const output = await new ExeHerdrBackend(connection).readOutput(this.executionHandle(run, "exe-herdr"));
if (output !== null) run.live_output = output;
} catch {
// Run inspection remains available when live output is temporarily unreachable.
}
}
}
}
delete run.execution_handle;
return json(run);
}

Expand Down
6 changes: 5 additions & 1 deletion packages/app/src/ui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,11 @@ manualRunForm.onsubmit=async e=>{e.preventDefault();const button=$('#submit-manu
async function load(){const [j,runs]=await Promise.all([request('/api/v1/jobs/'+encodeURIComponent(id)),request('/api/v1/runs?jobId='+encodeURIComponent(id))]),triggers=j.triggers||[];const triggerDetail=triggers.map(t=>esc(t.slug)+' · '+esc(t.kind)).join(' · ');root.innerHTML='<div class="flex flex-wrap items-start justify-between gap-4"><div><div class="flex items-center gap-3"><h1 class="text-3xl font-bold tracking-tight">'+esc(j.name)+'</h1>'+triggers.map(t=>triggerBadge(t.kind)).join('')+(j.enabled?'':'<span class="text-sm text-slate-500">Disabled</span>')+'</div><p class="mt-2 text-slate-500">'+triggerDetail+' · '+j.concurrencyLimit+' concurrent</p></div><div class="flex flex-wrap gap-2"><button id="run" class="rounded-xl bg-factorize-500 px-4 py-2.5 text-sm font-semibold text-slate-950">Run now</button><button id="toggle" class="rounded-xl border border-stone-300 px-4 py-2.5 text-sm font-semibold">'+(j.enabled?'Disable':'Enable')+'</button><a href="/jobs/'+encodeURIComponent(id)+'/edit" class="rounded-xl border border-stone-300 px-4 py-2.5 text-sm font-semibold">Edit</a><button id="delete" class="rounded-xl border border-red-200 px-4 py-2.5 text-sm font-semibold text-red-700">Delete</button></div></div><section class="${card} mt-8 p-6"><h2 class="font-semibold">Prompt template</h2><pre class="mt-4 overflow-x-auto whitespace-pre-wrap rounded-xl bg-slate-950 p-4 text-sm text-slate-100">'+esc(j.promptTemplate)+'</pre></section><section class="${card} mt-6 overflow-hidden"><div class="border-b border-stone-200 p-6 dark:border-slate-800"><h2 class="font-semibold">Runs</h2></div>'+(runs.items.length?'<ul class="divide-y divide-stone-200 dark:divide-slate-800">'+runs.items.map(r=>'<li><a class="flex items-center justify-between gap-4 p-5 hover:bg-stone-50 dark:hover:bg-slate-800" href="/job-runs/'+encodeURIComponent(r.id)+'"><span><span class="font-medium">'+esc(r.provider||r.agent_kind||'Factorize')+'</span><span class="mt-1 block text-xs text-slate-500">'+new Date(r.created_at).toLocaleString()+'</span></span>'+stateBadge(r.state)+'</a></li>').join('')+'</ul>':'<p class="p-8 text-sm text-slate-500">No runs yet.</p>')+'</section>';$('#run').onclick=openManualRun;$('#toggle').onclick=async()=>{await request('/api/v1/jobs/'+encodeURIComponent(id)+'/'+(j.enabled?'disable':'enable'),{method:'POST'});load()};$('#delete').onclick=async()=>{if(confirm('Delete this job and its queued history?')){await request('/api/v1/jobs/'+encodeURIComponent(id),{method:'DELETE'});location.href='/jobs'}}}load().catch(e=>root.innerHTML='<p class="text-red-700">'+esc(e.message)+'</p>');`);

export const jobRunPage = (viewer: { email: string }, runId: string) => shell("Run — Factorize", viewer, `<main class="mx-auto max-w-5xl px-5 py-12 lg:px-8"><div id="run-detail" data-id="${escapeHtml(runId)}"><p class="text-sm text-slate-500">Loading run…</p></div></main>`, `${uiHelpers}
const root=$('#run-detail'),id=root.dataset.id;request('/api/v1/runs/'+encodeURIComponent(id)).then(r=>{const caps=r.capabilities||[],canOutput=caps.includes('output'),canStop=caps.includes('stop')&&['starting','running','blocked'].includes(r.state),trusted=typeof r.destination_url==='string'&&r.destination_url.startsWith('https://'),context=r.context===null?'<p class="mt-3 text-sm text-slate-500">Context is not available for this legacy run.</p>':'<pre data-run-context class="mt-4 overflow-x-auto whitespace-pre-wrap rounded-xl bg-slate-950 p-4 font-mono text-xs leading-5 text-slate-100">'+esc(JSON.stringify(r.context,null,2))+'</pre>';root.innerHTML='<a href="/jobs/'+encodeURIComponent(r.job_id)+'" class="text-sm font-medium text-slate-500">← Job</a><div class="mt-6 flex flex-wrap items-start justify-between gap-4"><div><h1 class="text-3xl font-bold">Run '+esc(r.id.slice(0,8))+'</h1><p class="mt-2 text-slate-500">'+esc(r.backend_kind)+' · '+new Date(r.created_at).toLocaleString()+'</p></div><div class="flex items-center gap-3">'+stateBadge(r.state)+(canStop?'<button id="stop-run" class="rounded-xl border border-red-200 px-4 py-2 text-sm font-semibold text-red-700">Stop run</button>':'')+'</div></div><section class="${card} mt-8 p-6"><h2 class="font-semibold">Observation</h2>'+(trusted?'<a class="mt-3 inline-flex font-semibold text-factorize-700 underline" target="_blank" rel="noreferrer" href="'+esc(r.destination_url)+'">Open '+esc(r.backend_kind)+' destination ↗</a>':'<p class="mt-3 text-sm text-slate-500">This backend has no external observation link.</p>')+'</section><section class="${card} mt-6 p-6"><h2 class="font-semibold">Context sent to agent</h2>'+context+'</section>'+(canOutput?'<section class="${card} mt-6 p-6"><h2 class="font-semibold">Output</h2><pre data-run-output class="mt-4 overflow-x-auto whitespace-pre-wrap rounded-xl bg-slate-950 p-4 font-mono text-xs leading-5 text-slate-100">'+ansiToHtml(r.result||'Output is not available yet.')+'</pre></section>':'<section class="${card} mt-6 p-6 text-sm text-slate-500">Output is available only in the backend observation experience.</section>');if(canStop)$('#stop-run').onclick=async()=>{await request('/api/v1/runs/'+encodeURIComponent(id)+'/stop',{method:'POST'});location.reload()}}).catch(e=>root.innerHTML='<p class="text-red-700">'+esc(e.message)+'</p>');`);
const root=$('#run-detail'),id=root.dataset.id,activeStates=['starting','running','blocked','stopping'];let refreshTimer;
function outputText(r){return r.live_output??r.result??'Output is not available yet.'}
function scheduleRefresh(r){clearTimeout(refreshTimer);if(activeStates.includes(r.state)&&(r.capabilities||[]).includes('output'))refreshTimer=setTimeout(refreshOutput,3000)}
async function refreshOutput(){try{const r=await request('/api/v1/runs/'+encodeURIComponent(id)),output=$('[data-run-output]'),state=$('[data-run-state]');if(output)output.innerHTML=ansiToHtml(outputText(r));if(state)state.innerHTML=stateBadge(r.state);scheduleRefresh(r)}catch{refreshTimer=setTimeout(refreshOutput,5000)}}
request('/api/v1/runs/'+encodeURIComponent(id)).then(r=>{const caps=r.capabilities||[],canOutput=caps.includes('output'),canStop=caps.includes('stop')&&['starting','running','blocked'].includes(r.state),trusted=typeof r.destination_url==='string'&&r.destination_url.startsWith('https://'),context=r.context===null?'<p class="mt-3 text-sm text-slate-500">Context is not available for this legacy run.</p>':'<pre data-run-context class="mt-4 overflow-x-auto whitespace-pre-wrap rounded-xl bg-slate-950 p-4 font-mono text-xs leading-5 text-slate-100">'+esc(JSON.stringify(r.context,null,2))+'</pre>';root.innerHTML='<a href="/jobs/'+encodeURIComponent(r.job_id)+'" class="text-sm font-medium text-slate-500">← Job</a><div class="mt-6 flex flex-wrap items-start justify-between gap-4"><div><h1 class="text-3xl font-bold">Run '+esc(r.id.slice(0,8))+'</h1><p class="mt-2 text-slate-500">'+esc(r.backend_kind)+' · '+new Date(r.created_at).toLocaleString()+'</p></div><div class="flex items-center gap-3"><span data-run-state>'+stateBadge(r.state)+'</span>'+(canStop?'<button id="stop-run" class="rounded-xl border border-red-200 px-4 py-2 text-sm font-semibold text-red-700">Stop run</button>':'')+'</div></div><section class="${card} mt-8 p-6"><h2 class="font-semibold">Observation</h2>'+(trusted?'<a class="mt-3 inline-flex font-semibold text-factorize-700 underline" target="_blank" rel="noreferrer" href="'+esc(r.destination_url)+'">Open '+esc(r.backend_kind)+' destination ↗</a>':'<p class="mt-3 text-sm text-slate-500">This backend has no external observation link.</p>')+'</section><section class="${card} mt-6 p-6"><h2 class="font-semibold">Context sent to agent</h2>'+context+'</section>'+(canOutput?'<section class="${card} mt-6 p-6"><div class="flex items-center justify-between gap-4"><h2 class="font-semibold">Output</h2>'+(activeStates.includes(r.state)?'<span class="text-xs text-slate-500" aria-live="polite">Live · refreshes automatically</span>':'')+'</div><pre data-run-output class="mt-4 overflow-x-auto whitespace-pre-wrap rounded-xl bg-slate-950 p-4 font-mono text-xs leading-5 text-slate-100" aria-live="polite">'+ansiToHtml(outputText(r))+'</pre></section>':'<section class="${card} mt-6 p-6 text-sm text-slate-500">Output is available only in the backend observation experience.</section>');if(canStop)$('#stop-run').onclick=async()=>{await request('/api/v1/runs/'+encodeURIComponent(id)+'/stop',{method:'POST'});location.reload()};scheduleRefresh(r)}).catch(e=>root.innerHTML='<p class="text-red-700">'+esc(e.message)+'</p>');`);

const settingsLayout = (active: "integrations" | "api-keys", content: string) => `<main class="mx-auto max-w-6xl px-5 py-12 lg:px-8"><div class="grid gap-8 md:grid-cols-[13rem_minmax(0,1fr)] md:gap-10"><nav aria-label="Settings" class="flex gap-2 overflow-x-auto border-b border-stone-200 pb-3 md:block md:border-b-0 md:pb-0 dark:border-slate-800">
${[["integrations", "Integrations"], ["api-keys", "API Keys"]].map(([id, label]) => `<a href="/settings/${id}"${active === id ? ` aria-current="page"` : ""} class="flex min-h-11 shrink-0 items-center rounded-lg px-3 py-2 text-sm text-slate-600 hover:bg-stone-100 hover:text-slate-950 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-factorize-600 aria-[current=page]:bg-stone-100 aria-[current=page]:font-semibold aria-[current=page]:text-slate-950 md:mb-1 dark:text-slate-300 dark:hover:bg-slate-800 dark:hover:text-white dark:aria-[current=page]:bg-slate-800 dark:aria-[current=page]:text-white">${label}</a>`).join("")}
Expand Down
19 changes: 19 additions & 0 deletions packages/app/test/run-inspection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest";
vi.mock("cloudflare:workers", () => ({ DurableObject: class {} }));

import { TenantV2 } from "../src/tenant";
import { ExeHerdrBackend } from "../src/exe-herdr-backend";

function tenantWithRows(rows: (query: string, ...params: unknown[]) => Record<string, unknown>[]): TenantV2 {
const tenant = Object.create(TenantV2.prototype) as TenantV2;
Expand Down Expand Up @@ -83,6 +84,24 @@ describe("run invocation inspection", () => {
});
});

it("reads current backend output while an output-capable run is active", async () => {
const tenant = tenantWithRows((query) => query.includes("FROM runs r") ? [{
id: "run-1", job_id: "job-1", state: "running", backend_kind: "exe-herdr",
execution_handle: '{"backendKind":"exe-herdr","id":"agent-1"}', capabilities: '["output"]', result: null,
created_at: "2026-09-16T12:00:00Z", updated_at: "2026-09-16T12:01:00Z",
}] : []);
(tenant as any).executionConfig = () => ({ id: "job-1" });
(tenant as any).connectionForPipe = async () => ({ vmName: "vm", apiToken: "secret", agentKind: "codex", cwd: "/repo" });
const output = vi.spyOn(ExeHerdrBackend.prototype, "readOutput").mockResolvedValue("work in progress");

const body = await ((tenant as any).getRun("run-1") as Promise<Response>).then((response: Response) => response.json()) as any;

expect(output).toHaveBeenCalledWith({ backendKind: "exe-herdr", id: "agent-1" });
expect(body.live_output).toBe("work in progress");
expect(body).not.toHaveProperty("execution_handle");
output.mockRestore();
});

it("rejects an internal manual claim key before creating an invocation", async () => {
const tenant = Object.create(TenantV2.prototype) as TenantV2;
const response = await (tenant as any).invokeJob("job-1", { idempotencyKey: "manual:dev-dispatch-gen-2032" }) as Response;
Expand Down
5 changes: 4 additions & 1 deletion packages/app/test/ui.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,10 @@ describe("pages", () => {
expect(run).toContain("JSON.stringify(r.context,null,2)");
expect(run).toContain("Context is not available for this legacy run.");
expect(run).toContain('font-mono text-xs leading-5');
expect(run).toContain("ansiToHtml(r.result");
expect(run).toContain("ansiToHtml(outputText(r))");
expect(run).toContain("r.live_output??r.result");
expect(run).toContain("setTimeout(refreshOutput,3000)");
expect(run).toContain("Live · refreshes automatically");
expect(run).not.toContain("__name");
expect(settings).toContain("Connect every provider used by your Jobs");
expect(settings).toContain("Linear");
Expand Down