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
2 changes: 1 addition & 1 deletion packages/app/public/styles.css

Large diffs are not rendered by default.

73 changes: 73 additions & 0 deletions packages/app/src/ansi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/** Convert terminal SGR styling to safe HTML. All emitted markup is generated here. */
export function ansiToHtml(input: unknown): string {
const palette = ["#0f172a", "#ef4444", "#22c55e", "#eab308", "#3b82f6", "#d946ef", "#06b6d4", "#e2e8f0", "#64748b", "#f87171", "#4ade80", "#facc15", "#60a5fa", "#e879f9", "#22d3ee", "#f8fafc"];
const escape = (value: string) => value.replace(/[&<>"']/g, char => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[char]!);
const color = (value: number) => {
if (value < 16) return palette[value];
if (value < 232) {
const offset = value - 16, levels = [0, 95, 135, 175, 215, 255];
return `rgb(${levels[Math.floor(offset / 36)]},${levels[Math.floor(offset / 6) % 6]},${levels[offset % 6]})`;
}
const gray = 8 + (value - 232) * 10;
return `rgb(${gray},${gray},${gray})`;
};
type Style = { fg?: string; bg?: string; bold?: boolean; dim?: boolean; italic?: boolean; underline?: boolean; inverse?: boolean; hidden?: boolean; strike?: boolean };
let style: Style = {}, text = "", html = "";
const flush = () => {
if (!text) return;
let fg = style.fg, bg = style.bg;
if (style.inverse) { const originalFg = fg ?? "#e2e8f0"; fg = bg ?? "#020617"; bg = originalFg; }
const css = [fg && `color:${fg}`, bg && `background-color:${bg}`, style.bold && "font-weight:700", style.dim && "opacity:.65", style.italic && "font-style:italic", style.underline && "text-decoration:underline", style.strike && "text-decoration:line-through", style.hidden && "visibility:hidden"].filter(Boolean).join(";");
html += css ? `<span style="${css}">${escape(text)}</span>` : escape(text);
text = "";
};
const apply = (parameters: string) => {
const codes = (parameters === "" ? [0] : parameters.split(";").map(value => /^\d+$/.test(value) ? Number(value) : -1));
for (let index = 0; index < codes.length; index++) {
const code = codes[index];
if (code === 0) style = {};
else if (code === 1) style.bold = true;
else if (code === 2) style.dim = true;
else if (code === 3) style.italic = true;
else if (code === 4) style.underline = true;
else if (code === 7) style.inverse = true;
else if (code === 8) style.hidden = true;
else if (code === 9) style.strike = true;
else if (code === 22) { style.bold = false; style.dim = false; }
else if (code === 23) style.italic = false;
else if (code === 24) style.underline = false;
else if (code === 27) style.inverse = false;
else if (code === 28) style.hidden = false;
else if (code === 29) style.strike = false;
else if (code >= 30 && code <= 37) style.fg = color(code - 30);
else if (code >= 40 && code <= 47) style.bg = color(code - 40);
else if (code >= 90 && code <= 97) style.fg = color(code - 90 + 8);
else if (code >= 100 && code <= 107) style.bg = color(code - 100 + 8);
else if (code === 39) delete style.fg;
else if (code === 49) delete style.bg;
else if ((code === 38 || code === 48) && codes[index + 1] === 5 && codes[index + 2] >= 0 && codes[index + 2] <= 255) {
style[code === 38 ? "fg" : "bg"] = color(codes[index + 2]); index += 2;
} else if ((code === 38 || code === 48) && codes[index + 1] === 2 && codes.slice(index + 2, index + 5).every(value => value >= 0 && value <= 255)) {
style[code === 38 ? "fg" : "bg"] = `rgb(${codes[index + 2]},${codes[index + 3]},${codes[index + 4]})`; index += 4;
}
}
};
const value = String(input ?? "");
for (let index = 0; index < value.length;) {
if (value[index] !== "\u001b") { text += value[index++]; continue; }
flush();
if (value[index + 1] === "[") {
let end = index + 2;
while (end < value.length && !/[\x40-\x7e]/.test(value[end])) end++;
if (end >= value.length) break;
if (value[end] === "m" && /^[\d;]*$/.test(value.slice(index + 2, end))) apply(value.slice(index + 2, end));
index = end + 1;
} else if (value[index + 1] === "]") {
let end = index + 2;
while (end < value.length && value[end] !== "\u0007" && !(value[end] === "\u001b" && value[end + 1] === "\\")) end++;
index = end < value.length ? end + (value[end] === "\u001b" ? 2 : 1) : value.length;
} else index += Math.min(2, value.length - index);
}
flush();
return html;
}
4 changes: 3 additions & 1 deletion packages/app/src/ui.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/** Framework-light pages; Tailwind is compiled locally into public/styles.css. */
import { triggerContextCatalog } from "./trigger-context";
import { ansiToHtml } from "./ansi";
type Viewer = { email: string } | null;
const escapeHtml = (value: string) => value.replace(/[&<>"']/g, (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[char]!);

Expand Down Expand Up @@ -47,6 +48,7 @@ const dashboardHead = (title: string, description: string, action = "") => `<div
const card = "rounded-2xl border border-stone-200 bg-white shadow-sm dark:border-slate-800 dark:bg-slate-900";
const uiHelpers = `
const $=s=>document.querySelector(s),esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
${ansiToHtml.toString()}
const request=async(url,options)=>{const r=await fetch(url,options),body=await r.json().catch(()=>({}));if(r.status===401){location.href='/auth/linear';throw new Error('Unauthorized')}if(!r.ok)throw new Error(body.error?.message||body.error||'Request failed');return body};
const pairs=v=>Object.entries(v||{}).map(([k,x])=>k+'='+x).join('\\n');
const record=v=>Object.fromEntries(String(v||'').split(/\\n/).map(x=>x.trim()).filter(Boolean).map(x=>{const i=x.indexOf('=');if(i<1)throw new Error('Parameters must use name=value, one per line.');return[x.slice(0,i).trim(),x.slice(i+1)]}));
Expand Down Expand Up @@ -124,7 +126,7 @@ async function runNow(job){const value=prompt('Prompt for this manual run:','');
async function load(){const [j,runs]=await Promise.all([request('/api/jobs/'+encodeURIComponent(id)),request('/api/job-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=()=>runNow(j).catch(alert);$('#toggle').onclick=async()=>{await request('/api/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/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/job-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://');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>'+(canOutput?'<section class="${card} mt-6 p-6"><h2 class="font-semibold">Output</h2><pre class="mt-4 overflow-x-auto whitespace-pre-wrap rounded-xl bg-slate-950 p-4 text-sm text-slate-100">'+esc(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/job-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;request('/api/job-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://');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>'+(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/job-runs/'+encodeURIComponent(id)+'/stop',{method:'POST'});location.reload()}}).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
35 changes: 35 additions & 0 deletions packages/app/test/ansi.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { describe, expect, it } from "vitest";
import { ansiToHtml } from "../src/ansi";

describe("ansiToHtml", () => {
it("renders standard, bright, indexed, and true-color SGR colors", () => {
const html = ansiToHtml("\u001b[31mred\u001b[44m on blue\u001b[0m plain \u001b[92mbright\u001b[38;5;208m indexed\u001b[38;2;1;2;3m rgb");
expect(html).toContain('color:#ef4444');
expect(html).toContain('background-color:#3b82f6');
expect(html).toContain('color:#4ade80');
expect(html).toContain('color:rgb(255,135,0)');
expect(html).toContain('color:rgb(1,2,3)');
expect(html).toContain(" plain ");
});

it("handles resets, bold, and dim independently", () => {
const html = ansiToHtml("\u001b[1;2mboth\u001b[22mnormal\u001b[31mred\u001b[39mdefault");
expect(html).toContain("font-weight:700;opacity:.65");
expect(html).not.toMatch(/>normal<\/span>/);
expect(html).toContain('color:#ef4444');
expect(html).toContain("default");
});

it("escapes HTML and strips malformed, partial, and unsupported control sequences", () => {
const html = ansiToHtml('<script>alert("x")</script>\u001b[999mtext\u001b[31');
expect(html).toContain('&lt;script&gt;alert(&quot;x&quot;)&lt;/script&gt;');
expect(html).toContain("text");
expect(html).not.toContain("<script>");
expect(html).not.toContain("\u001b");
expect(html).not.toContain("[999m");
});

it("leaves plain text unchanged apart from required HTML escaping", () => {
expect(ansiToHtml("plain\n output & more")).toBe("plain\n output &amp; more");
});
});
3 changes: 3 additions & 0 deletions packages/app/test/ui.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,9 @@ describe("pages", () => {
expect(detail).toContain("Run now");
expect(run).toContain("destination_url");
expect(run).toContain("caps.includes('output')");
expect(run).toContain('data-run-output');
expect(run).toContain('font-mono text-xs leading-5');
expect(run).toContain("ansiToHtml(r.result");
expect(settings).toContain("Connect every provider used by your Jobs");
expect(settings).toContain("Linear");
expect(settings).toContain("GitHub App");
Expand Down