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
9 changes: 8 additions & 1 deletion packages/app/src/ui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,14 +182,21 @@ async function load(){clearInterval(elapsedTimer);const [j,runs]=await Promise.a

export const jobRunPage = (viewer: { email: string }, runId: string) => shell("Run — Factorize", viewer, `<main class="mx-auto w-full max-w-6xl min-w-0 px-4 py-8 sm:px-5 sm:py-12 lg:px-8"><div id="run-detail" class="min-w-0" 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,activeStates=['queued','starting','running','blocked','stopping'];let refreshTimer,elapsedTimer,traceCursor=0,traceDone=false;
function triggerProvenance(r){
const invocation=r.invocation;
if(!invocation)return '<section data-run-trigger class="${card} mt-6 min-w-0 p-6"><h2 class="font-semibold">Trigger</h2><p class="mt-2 text-sm text-slate-500">Trigger information is not available for this run.</p></section>';
const labels={manual:'Manual',schedule:'Schedule',webhook:'Webhook',jobLifecycle:'Job lifecycle'},context=invocation.context||{},slugs=Object.keys(context),source=Object.hasOwn(labels,invocation.source)?labels[invocation.source]:(invocation.source||'Unknown');
const row=(label,value)=>value?'<div class="min-w-0"><dt class="text-slate-500">'+label+'</dt><dd class="break-words">'+esc(value)+'</dd></div>':'';
return '<section data-run-trigger class="${card} mt-6 min-w-0 overflow-hidden p-6"><h2 class="font-semibold">Trigger</h2><dl class="mt-3 grid gap-3 text-sm sm:grid-cols-2">'+row('Type',source)+row('Trigger',slugs.join(', '))+row('Trigger ID',invocation.trigger_id)+row('Invoked at',invocation.created_at)+'</dl><details class="mt-4"><summary class="cursor-pointer text-sm font-semibold">Trigger details</summary><pre class="mt-3 max-h-96 overflow-auto whitespace-pre-wrap break-words font-mono text-xs leading-5">'+esc(JSON.stringify({context,...(invocation.occurrence?{occurrence:invocation.occurrence}:{})},null,2))+'</pre></details></section>';
}
const traceStyle={user_message:'border-amber-300 bg-amber-50 dark:border-amber-900 dark:bg-amber-950/30',assistant_message:'border-emerald-300 bg-emerald-50 dark:border-emerald-900 dark:bg-emerald-950/30',reasoning:'border-violet-300 bg-violet-50 dark:border-violet-900 dark:bg-violet-950/30',tool_call:'border-sky-300 bg-sky-50 dark:border-sky-900 dark:bg-sky-950/30',tool_result:'border-cyan-300 bg-cyan-50 dark:border-cyan-900 dark:bg-cyan-950/30',command:'border-slate-400 bg-slate-950 text-slate-100',error:'border-red-400 bg-red-50 dark:bg-red-950/30',warning:'border-orange-300 bg-orange-50 dark:bg-orange-950/30'};
function traceCard(e){return '<article class="rounded-xl border p-4 '+(traceStyle[e.type]||'border-stone-200 bg-stone-50 dark:border-slate-700 dark:bg-slate-800/50')+'"><div class="flex flex-wrap items-center justify-between gap-2"><h3 class="text-sm font-semibold">'+esc(e.title)+'</h3><span class="rounded-full border border-current/20 px-2 py-0.5 text-[.68rem] font-semibold uppercase tracking-wide opacity-70">'+esc(e.type.replaceAll('_',' '))+'</span></div><pre class="mt-3 max-h-96 overflow-auto whitespace-pre-wrap break-words font-mono text-xs leading-5">'+esc(e.preview||'')+'</pre></article>'}
async function loadTrace(reset=false){if(reset){traceCursor=0;traceDone=false;const list=$('[data-run-trace]');if(list)list.innerHTML=''}if(traceDone)return;const page=await request('/api/v1/runs/'+encodeURIComponent(id)+'/trace?after='+traceCursor+'&limit=100'),list=$('[data-run-trace]');if(!list)return;list.insertAdjacentHTML('beforeend',page.items.map(traceCard).join(''));if(page.items.length)traceCursor=page.items.at(-1).sequence;traceDone=!page.nextCursor;const more=$('[data-trace-more]');if(more)more.classList.toggle('hidden',traceDone);const empty=$('[data-trace-empty]');if(empty)empty.classList.toggle('hidden',Boolean(list.children.length))}
function elapsed(r){const start=new Date(r.created_at).getTime(),end=activeStates.includes(r.state)?Date.now():new Date(r.updated_at||r.created_at).getTime(),seconds=Math.max(0,Math.floor((end-start)/1000)),hours=Math.floor(seconds/3600),minutes=Math.floor(seconds%3600/60),remainder=seconds%60;return(hours?hours+'h ':'')+(minutes||hours?minutes+'m ':'')+remainder+'s elapsed'}
function updateElapsed(r){const label=$('[data-run-elapsed]');if(label)label.textContent=elapsed(r);clearInterval(elapsedTimer);if(activeStates.includes(r.state))elapsedTimer=setInterval(()=>{const current=$('[data-run-elapsed]');if(current)current.textContent=elapsed(r)},1000)}
function scheduleRefresh(r){clearTimeout(refreshTimer);if(activeStates.includes(r.state))refreshTimer=setTimeout(refreshOutput,3000)}
async function refreshOutput(){try{const r=await request('/api/v1/runs/'+encodeURIComponent(id)),state=$('[data-run-state]');if(state)state.innerHTML=stateBadge(r.state);traceDone=false;await loadTrace();updateElapsed(r);scheduleRefresh(r)}catch{refreshTimer=setTimeout(refreshOutput,5000)}}
request('/api/v1/runs/'+encodeURIComponent(id)).then(async r=>({r,j:await request('/api/v1/jobs/'+encodeURIComponent(r.job_id))})).then(async({r,j})=>{const canKill=!['done','failed','stopped','succeeded'].includes(r.state),runLabel=r.name||r.run_name||r.issue_title||'Run '+r.id.slice(0,8);document.title=runLabel+' — Factorize';root.innerHTML='<nav aria-label="Breadcrumb"><ol class="flex min-w-0 flex-wrap items-center gap-2 text-sm text-slate-500"><li><a href="/jobs" class="font-medium hover:text-slate-950 dark:hover:text-white">Jobs</a></li><li aria-hidden="true">/</li><li class="min-w-0 max-w-full"><a href="/jobs/'+encodeURIComponent(r.job_id)+'" class="block truncate font-medium hover:text-slate-950 dark:hover:text-white">'+esc(j.name)+'</a></li><li aria-hidden="true">/</li><li aria-current="page" class="min-w-0 max-w-full truncate font-medium text-slate-950 dark:text-white">'+esc(runLabel)+'</li></ol></nav><div class="mt-6 flex min-w-0 flex-wrap items-start justify-between gap-4"><div class="min-w-0"><h1 class="break-words text-3xl font-bold">'+esc(runLabel)+'</h1><p data-run-elapsed class="mt-2 text-slate-500">'+elapsed(r)+'</p></div><div class="flex min-w-0 flex-wrap items-center gap-3"><span data-run-state>'+stateBadge(r.state)+'</span>'+(canKill?'<button id="kill-run" class="rounded-xl border border-red-200 px-4 py-2 text-sm font-semibold text-red-700">Kill run</button>':'')+'</div></div><details data-run-prompt-details class="${card} mt-8 min-w-0 overflow-hidden p-6"><summary class="cursor-pointer font-semibold">Prompt</summary><pre data-run-prompt class="mt-4 min-w-0 max-w-full overflow-x-auto whitespace-pre-wrap break-words rounded-xl bg-slate-950 p-4 font-mono text-xs leading-5 text-slate-100">'+esc(r.prompt||'Prompt is not available for this run.')+'</pre></details><section class="${card} mt-6 min-w-0 overflow-hidden p-6"><div class="flex flex-wrap items-center justify-between gap-3"><div><h2 class="font-semibold">Trace</h2><p class="mt-1 text-xs text-slate-500">Native '+esc(r.agent_kind||'agent')+' session · '+esc(r.artifact_state||'pending')+'</p></div>'+(activeStates.includes(r.state)?'<span class="text-xs text-slate-500" aria-live="polite">Live · refreshes automatically</span>':'')+'</div><p data-trace-empty class="mt-6 text-sm text-slate-500">Trace events are not available yet.</p><div data-run-trace class="mt-5 grid gap-3"></div><button data-trace-more class="mt-5 hidden rounded-xl border border-stone-300 px-4 py-2 text-sm font-semibold">Load more</button></section>';if(canKill)$('#kill-run').onclick=async()=>{if(!confirm('Kill this run and release its concurrency slot?'))return;await request('/api/v1/runs/'+encodeURIComponent(id)+'/kill',{method:'POST'});location.reload()};$('[data-trace-more]').onclick=()=>{traceDone=false;loadTrace()};await loadTrace();updateElapsed(r);scheduleRefresh(r)}).catch(e=>root.innerHTML='<p class="text-red-700">'+esc(e.message)+'</p>');`);
request('/api/v1/runs/'+encodeURIComponent(id)).then(async r=>({r,j:await request('/api/v1/jobs/'+encodeURIComponent(r.job_id))})).then(async({r,j})=>{const canKill=!['done','failed','stopped','succeeded'].includes(r.state),runLabel=r.name||r.run_name||r.issue_title||'Run '+r.id.slice(0,8);document.title=runLabel+' — Factorize';root.innerHTML='<nav aria-label="Breadcrumb"><ol class="flex min-w-0 flex-wrap items-center gap-2 text-sm text-slate-500"><li><a href="/jobs" class="font-medium hover:text-slate-950 dark:hover:text-white">Jobs</a></li><li aria-hidden="true">/</li><li class="min-w-0 max-w-full"><a href="/jobs/'+encodeURIComponent(r.job_id)+'" class="block truncate font-medium hover:text-slate-950 dark:hover:text-white">'+esc(j.name)+'</a></li><li aria-hidden="true">/</li><li aria-current="page" class="min-w-0 max-w-full truncate font-medium text-slate-950 dark:text-white">'+esc(runLabel)+'</li></ol></nav><div class="mt-6 flex min-w-0 flex-wrap items-start justify-between gap-4"><div class="min-w-0"><h1 class="break-words text-3xl font-bold">'+esc(runLabel)+'</h1><p data-run-elapsed class="mt-2 text-slate-500">'+elapsed(r)+'</p></div><div class="flex min-w-0 flex-wrap items-center gap-3"><span data-run-state>'+stateBadge(r.state)+'</span>'+(canKill?'<button id="kill-run" class="rounded-xl border border-red-200 px-4 py-2 text-sm font-semibold text-red-700">Kill run</button>':'')+'</div></div>'+triggerProvenance(r)+'<details data-run-prompt-details class="${card} mt-8 min-w-0 overflow-hidden p-6"><summary class="cursor-pointer font-semibold">Prompt</summary><pre data-run-prompt class="mt-4 min-w-0 max-w-full overflow-x-auto whitespace-pre-wrap break-words rounded-xl bg-slate-950 p-4 font-mono text-xs leading-5 text-slate-100">'+esc(r.prompt||'Prompt is not available for this run.')+'</pre></details><section class="${card} mt-6 min-w-0 overflow-hidden p-6"><div class="flex flex-wrap items-center justify-between gap-3"><div><h2 class="font-semibold">Trace</h2><p class="mt-1 text-xs text-slate-500">Native '+esc(r.agent_kind||'agent')+' session · '+esc(r.artifact_state||'pending')+'</p></div>'+(activeStates.includes(r.state)?'<span class="text-xs text-slate-500" aria-live="polite">Live · refreshes automatically</span>':'')+'</div><p data-trace-empty class="mt-6 text-sm text-slate-500">Trace events are not available yet.</p><div data-run-trace class="mt-5 grid gap-3"></div><button data-trace-more class="mt-5 hidden rounded-xl border border-stone-300 px-4 py-2 text-sm font-semibold">Load more</button></section>';if(canKill)$('#kill-run').onclick=async()=>{if(!confirm('Kill this run and release its concurrency slot?'))return;await request('/api/v1/runs/'+encodeURIComponent(id)+'/kill',{method:'POST'});location.reload()};$('[data-trace-more]').onclick=()=>{traceDone=false;loadTrace()};await loadTrace();updateElapsed(r);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 w-full max-w-6xl min-w-0 px-4 py-8 sm:px-5 sm:py-12 lg:px-8"><div class="grid min-w-0 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
68 changes: 68 additions & 0 deletions packages/app/test/run-trigger.browser.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// @vitest-environment happy-dom
import { afterEach, expect, it, vi } from "vitest";
import { jobRunPage } from "../src/ui";

declare const document: any;

afterEach(() => {
vi.unstubAllGlobals();
document.body.innerHTML = "";
});

async function render(invocation?: Record<string, unknown>, name?: string) {
vi.stubGlobal("fetch", vi.fn(async (url: string) => {
const body = url.includes("/trace?")
? { items: [], nextCursor: null }
: url.startsWith("/api/v1/jobs/")
? { name: "Job", triggers: [{ id: "trigger-1", slug: "renamed-trigger" }] }
: { id: "run-1", job_id: "job-1", state: "succeeded", name, created_at: "2026-09-18T12:00:00Z", invocation };
return new Response(JSON.stringify(body), { headers: { "content-type": "application/json" } });
}));
const html = jobRunPage({ email: "owner@example.com" }, "run-1");
document.body.innerHTML = html.match(/<body[^>]*>([\s\S]*?)<\/body>/)?.[1] ?? "";
const script = [...html.matchAll(/<script>([\s\S]*?)<\/script>/g)].at(-1)![1];
new Function(script)();
await vi.waitFor(() => expect(document.querySelector("[data-run-trigger]")).not.toBeNull());
return document.querySelector("[data-run-trigger]");
}

it.each([
["manual", "Manual", { prompt: "Review this issue" }],
["schedule", "Schedule", { cron: "0 9 * * *", timezone: "UTC" }],
["webhook", "Webhook", { provider: "linear", event: "Issue", issue: { identifier: "GEN-2112" } }],
["jobLifecycle", "Job lifecycle", { source_run_id: "previous-run", final_state: "succeeded" }],
])("shows recorded %s provenance independently of current trigger configuration", async (source, label, data) => {
const context = { "original-trigger": data };
const occurrence = { occurredAt: "2026-09-18T11:59:00Z", externalId: "event-1" };
const section = await render({ source, trigger_id: "trigger-1", context, occurrence, created_at: "2026-09-18T12:00:00Z" });
expect(section.textContent).toContain(label);
expect(section.textContent).toContain("original-trigger");
expect(section.textContent).not.toContain("renamed-trigger");
expect(section.textContent).toContain("trigger-1");
expect(section.textContent).toContain("2026-09-18T12:00:00Z");
expect(section.querySelector("details").open).toBe(false);
expect(JSON.parse(section.querySelector("pre").textContent)).toEqual({ context, occurrence });
});

it("escapes untrusted trigger names, source, and event payloads", async () => {
const value = '<img src=x onerror="alert(1)">';
const section = await render({ source: value, trigger_id: value, context: { [value]: { prompt: value } } });
expect(section.querySelector("img")).toBeNull();
expect(section.textContent).toContain(value);
});

it("handles missing provenance without breaking the run page", async () => {
const section = await render();
expect(section.textContent).toContain("Trigger information is not available for this run.");
expect(document.querySelector("[data-run-prompt-details]")).not.toBeNull();
});

it("shows the run name and browser title alongside trigger provenance", async () => {
const name = "Review GEN-2112";
const section = await render({ source: "manual", trigger_id: "trigger-1" }, name);
expect(document.querySelector("h1").textContent).toBe(name);
expect(document.querySelector('[aria-current="page"]').textContent).toBe(name);
expect(document.title).toBe(name + " — Factorize");
expect(section.textContent).toContain("Manual");
expect(section.textContent).toContain("trigger-1");
});
Loading