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/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ app.get("/auth/linear/callback", async (c) => {
const memberResponse = await stub.fetch("https://tenant/members", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ userId: viewer.id, email: viewer.email }) });
const member = await memberResponse.json() as { role: string; session_version: number };
if (member.role !== "owner") return c.text("This Factorize tenant requires an owner invitation.", 403);
await stub.fetch("https://tenant/connections/linear", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ accessToken: tokens.access_token, refreshToken: tokens.refresh_token, organizationId: organization.id, organizationName: organization.name }) });
await stub.fetch("https://tenant/connections/linear", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ accessToken: tokens.access_token, refreshToken: tokens.refresh_token, organizationId: organization.id, organizationName: organization.name, viewerId: viewer.id, viewerEmail: viewer.email }) });
const lifetime = 60 * 60 * 24 * 7;
setCookie(c, "factorize_session", await signSession({ tenantId: organization.id, userId: viewer.id, email: viewer.email, exp: Math.floor(Date.now() / 1000) + lifetime, sessionVersion: member.session_version }, c.env.SESSION_SIGNING_SECRET), { httpOnly: true, secure: new URL(c.env.APP_ORIGIN).protocol === "https:", sameSite: "Lax", path: "/", maxAge: lifetime });
const oauthReturn = getCookie(c, "factorize_oauth_return");
Expand Down
6 changes: 3 additions & 3 deletions packages/app/src/tenant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ export class Tenant extends DurableObject<Env> {
}

private async saveLinear(input: unknown): Promise<Response> {
const value = input as { accessToken?: string; refreshToken?: string; organizationId?: string; organizationName?: string };
const value = input as { accessToken?: string; refreshToken?: string; organizationId?: string; organizationName?: string; viewerId?: string; viewerEmail?: string };
if (!value.accessToken || !value.refreshToken || !value.organizationId) throw new Error("Linear tokens and organization are required");
await this.putConnection("linear", value);
return json({ ok: true });
Expand Down Expand Up @@ -352,12 +352,12 @@ export class Tenant extends DurableObject<Env> {
}

private async connectionStatus(): Promise<Response> {
const linear = await this.connection<{ organizationName?: string }>("linear");
const linear = await this.connection<{ organizationName?: string; viewerEmail?: string }>("linear");
const connections = await this.exeConnections();
const exe = await this.connection<ExeConnectionInput>("exe");
const ampConnections = await this.ampConnections();
return json({
linear: linear ? { organizationName: linear.organizationName ?? null } : null,
linear: linear ? { organizationName: linear.organizationName ?? null, viewerEmail: linear.viewerEmail ?? null } : null,
exe: exe ? { vmName: exe.vmName, agentKind: exe.agentKind, cwd: exe.cwd, herdrCommand: exe.herdrCommand ?? "herdr", agentCommand: exe.agentCommand ?? defaultAgentCommand(exe.agentKind) } : null,
exeConnections: connections.map(({ apiToken, ...connection }) => connection),
ampConnections: ampConnections.map(({ accessToken, ...connection }) => connection),
Expand Down
14 changes: 12 additions & 2 deletions packages/app/src/ui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,5 +260,15 @@ async function load(){const [j,runs]=await Promise.all([request('/api/jobs/'+enc
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>');`);

export const settingsPage = (viewer: { email: string }) => shell("Settings — Factorize", viewer, `<main class="mx-auto max-w-4xl px-5 py-12 lg:px-8">${dashboardHead("Settings", "Create and rotate provider connections here. Credential values never appear in Jobs or MCP.")}<section class="${card} mt-8 p-6"><h2 class="text-lg font-semibold">Exe.dev execution connections</h2><div id="connections" class="mt-4 text-sm text-slate-500">Loading…</div><form id="connection" class="mt-6 grid gap-4 border-t border-stone-200 pt-6 sm:grid-cols-2 dark:border-slate-800"><label class="label">SSH destination<input class="field" name="vmName" required placeholder="exedev@workbox"></label><label class="label">Restricted HTTPS token<input class="field" type="password" name="apiToken" required autocomplete="new-password"></label><label class="label sm:col-span-2">Working directory<input class="field" name="cwd" required placeholder="/home/exedev/project"></label><label class="label">Agent<select class="field" name="agentKind"><option value="codex">Codex</option><option value="claude">Claude</option></select></label><div class="flex items-end"><button class="rounded-xl bg-slate-950 px-4 py-3 text-sm font-semibold text-white dark:bg-white dark:text-slate-950">Save / rotate connection</button></div></form><p id="settings-message" class="mt-4 text-sm"></p></section><section class="${card} mt-8 p-6"><h2 class="text-lg font-semibold">Amp cloud execution</h2><div id="amp-connections" class="mt-4 text-sm text-slate-500">Loading…</div><form id="amp-connection" class="mt-6 grid gap-4 border-t border-stone-200 pt-6 sm:grid-cols-2 dark:border-slate-800"><label class="label">Amp project<input class="field" name="project" required placeholder="owner/repository"></label><label class="label">Amp access token<input class="field" type="password" name="accessToken" required autocomplete="new-password" placeholder="sgamp_…"></label><label class="label sm:col-span-2">Cloud API base URL<input class="field" type="url" name="apiBaseUrl" value="https://ampcode.com/api/cloud/v1" required></label><div><button type="button" id="test-amp" class="rounded-xl border border-stone-300 px-4 py-3 text-sm font-semibold">Test connection</button></div><div><button class="rounded-xl bg-slate-950 px-4 py-3 text-sm font-semibold text-white dark:bg-white dark:text-slate-950">Save / rotate Amp</button></div></form><p id="amp-message" class="mt-4 text-sm"></p></section></main>`, `${uiHelpers}
async function load(){const s=await request('/api/connections/status');$('#connections').innerHTML=s.exeConnections?.length?'<ul class="space-y-2">'+s.exeConnections.map(c=>'<li class="rounded-lg bg-stone-50 p-3 dark:bg-slate-950"><strong>'+esc(c.vmName)+'</strong> · '+esc(c.agentKind)+' · '+esc(c.cwd)+'</li>').join('')+'</ul>':'No execution connections yet.';$('#amp-connections').innerHTML=s.ampConnections?.length?s.ampConnections.map(c=>'<div class="rounded-lg bg-stone-50 p-3 dark:bg-slate-950"><strong>'+esc(c.project)+'</strong> · Amp cloud</div>').join(''):'No Amp connections yet.'}$('#connection').onsubmit=async e=>{e.preventDefault();const d=new FormData(e.currentTarget),m=$('#settings-message');try{await request('/api/connections/exe',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify({vmName:d.get('vmName'),apiToken:d.get('apiToken'),cwd:d.get('cwd'),agentKind:d.get('agentKind'),herdrCommand:'herdr',agentCommand:''})});e.currentTarget.reset();m.textContent='Connection saved. The credential is stored securely and will not be displayed.';load()}catch(x){m.textContent=x.message}};const ampPayload=()=>{const d=new FormData($('#amp-connection'));return {project:d.get('project'),accessToken:d.get('accessToken'),apiBaseUrl:d.get('apiBaseUrl')}};$('#test-amp').onclick=async()=>{const m=$('#amp-message');try{const x=await request('/api/connections/amp/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(ampPayload())});m.textContent=x.ok?'Amp connection succeeded.':'Amp connection failed.'}catch(x){m.textContent=x.message}};$('#amp-connection').onsubmit=async e=>{e.preventDefault();const m=$('#amp-message');try{await request('/api/connections/amp',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify(ampPayload())});e.currentTarget.reset();m.textContent='Amp connection saved. The token will not be displayed.';load()}catch(x){m.textContent=x.message}};load();`);
export const settingsPage = (viewer: { email: string }) => shell("Integrations — Factorize", viewer, `<main class="mx-auto max-w-4xl px-5 py-12 lg:px-8">${dashboardHead("Integrations", "Connect every provider used by your Jobs. Stored credentials are write-only and are never displayed.")}
<div id="integration-error" role="alert" class="mt-6 hidden rounded-xl bg-red-50 p-4 text-sm text-red-800 dark:bg-red-950/40 dark:text-red-200"></div>
<section class="${card} mt-8 p-6" aria-labelledby="linear-title"><div class="flex items-start justify-between gap-4"><div><h2 id="linear-title" class="text-lg font-semibold">Linear</h2><p class="mt-1 text-sm text-slate-500">Issues, projects, and trigger resources.</p></div><span id="linear-status" class="rounded-full bg-stone-100 px-3 py-1 text-xs font-semibold text-slate-600">Loading…</span></div><div id="linear-details" class="mt-4 text-sm text-slate-500">Checking your workspace…</div><a id="linear-action" href="/auth/linear" class="mt-5 inline-flex rounded-xl border border-stone-300 px-4 py-2.5 text-sm font-semibold">Reconnect Linear</a></section>
<section class="${card} mt-6 p-6" aria-labelledby="github-title"><div class="flex items-start justify-between gap-4"><div><h2 id="github-title" class="text-lg font-semibold">GitHub App</h2><p class="mt-1 text-sm text-slate-500">Repositories and supported GitHub triggers.</p></div><span id="github-status" class="rounded-full bg-stone-100 px-3 py-1 text-xs font-semibold text-slate-600">Loading…</span></div><div id="github-installations" class="mt-4 text-sm text-slate-500">Loading installations…</div><div class="mt-5 flex flex-wrap gap-3"><a id="github-install" href="/auth/github/install" class="rounded-xl bg-slate-950 px-4 py-2.5 text-sm font-semibold text-white dark:bg-white dark:text-slate-950">Install GitHub App</a><a id="github-manage" href="https://github.com/settings/installations" target="_blank" rel="noreferrer" class="rounded-xl border border-stone-300 px-4 py-2.5 text-sm font-semibold">Manage on GitHub ↗</a></div></section>
<section class="${card} mt-6 p-6" aria-labelledby="exe-title"><div class="flex items-start justify-between gap-4"><div><h2 id="exe-title" class="text-lg font-semibold">Exe.dev execution</h2><p class="mt-1 text-sm text-slate-500">VM destinations and working directories.</p></div><span id="exe-status" class="rounded-full bg-stone-100 px-3 py-1 text-xs font-semibold text-slate-600">Loading…</span></div><div id="connections" class="mt-4 text-sm text-slate-500">Loading connections…</div><form id="connection" class="mt-6 grid gap-4 border-t border-stone-200 pt-6 sm:grid-cols-2 dark:border-slate-800"><label class="label">SSH destination<input class="field" name="vmName" required placeholder="exedev@workbox"></label><label class="label">Restricted HTTPS token<input class="field" type="password" name="apiToken" required autocomplete="new-password" placeholder="Enter a new token"></label><label class="label sm:col-span-2">Working directory<input class="field" name="cwd" required placeholder="/home/exedev/project"></label><label class="label">Agent<select class="field" name="agentKind"><option value="codex">Codex</option><option value="claude">Claude</option></select></label><div class="flex items-end"><button class="rounded-xl bg-slate-950 px-4 py-3 text-sm font-semibold text-white dark:bg-white dark:text-slate-950">Save connection</button></div></form><p id="settings-message" role="status" class="mt-4 text-sm"></p></section>
<section class="${card} mt-6 p-6" aria-labelledby="amp-title"><div class="flex items-start justify-between gap-4"><div><h2 id="amp-title" class="text-lg font-semibold">Amp cloud execution</h2><p class="mt-1 text-sm text-slate-500">Cloud projects used as execution targets.</p></div><span id="amp-status" class="rounded-full bg-stone-100 px-3 py-1 text-xs font-semibold text-slate-600">Loading…</span></div><div id="amp-connections" class="mt-4 text-sm text-slate-500">Loading connections…</div><form id="amp-connection" class="mt-6 grid gap-4 border-t border-stone-200 pt-6 sm:grid-cols-2 dark:border-slate-800"><label class="label">Amp project<input class="field" name="project" required placeholder="owner/repository"></label><label class="label">Amp access token<input class="field" type="password" name="accessToken" required autocomplete="new-password" placeholder="Enter a new token"></label><label class="label sm:col-span-2">Cloud API base URL<input class="field" type="url" name="apiBaseUrl" value="https://ampcode.com/api/cloud/v1" required></label><div><button type="button" id="test-amp" class="rounded-xl border border-stone-300 px-4 py-3 text-sm font-semibold">Test new connection</button></div><div><button class="rounded-xl bg-slate-950 px-4 py-3 text-sm font-semibold text-white dark:bg-white dark:text-slate-950">Save connection</button></div></form><p id="amp-message" role="status" class="mt-4 text-sm"></p></section></main>`, `${uiHelpers}
const badge=(id,label,tone)=>{const el=$(id);el.textContent=label;el.className='rounded-full px-3 py-1 text-xs font-semibold '+(tone==='ok'?'bg-green-100 text-green-800 dark:bg-green-950 dark:text-green-200':tone==='warn'?'bg-amber-100 text-amber-800 dark:bg-amber-950 dark:text-amber-200':'bg-stone-100 text-slate-600 dark:bg-slate-800 dark:text-slate-300')};
const testButton=(kind,id)=>'<button type="button" data-test="'+kind+'" data-id="'+esc(id)+'" class="rounded-lg border border-stone-300 px-3 py-1.5 text-xs font-semibold">Test</button>';
async function load(){try{const [s,gh]=await Promise.all([request('/api/connections/status'),fetch('/api/github/installations')]);if(s.linear){badge('#linear-status','Connected','ok');$('#linear-details').innerHTML='<strong>'+esc(s.linear.organizationName||'Linear workspace')+'</strong>'+(s.linear.viewerEmail?' · '+esc(s.linear.viewerEmail):'');$('#linear-action').textContent='Reconnect Linear'}else{badge('#linear-status','Not connected','warn');$('#linear-details').textContent='Connect a Linear workspace to load issue and project resources.';$('#linear-action').textContent='Connect Linear'}const exe=s.exeConnections||[];badge('#exe-status',exe.length?'Connected':'Not connected',exe.length?'ok':'warn');$('#connections').innerHTML=exe.length?'<ul class="space-y-2">'+exe.map(c=>'<li class="flex flex-wrap items-center justify-between gap-3 rounded-lg bg-stone-50 p-3 dark:bg-slate-950"><span><strong>'+esc(c.vmName)+'</strong><span class="block text-xs text-slate-500">'+esc(c.cwd)+' · '+esc(c.agentKind)+'</span></span>'+testButton('exe',c.connectionId)+'</li>').join('')+'</ul>':'No exe.dev connections yet.';const amps=s.ampConnections||[];badge('#amp-status',amps.length?'Connected':'Not connected',amps.length?'ok':'warn');$('#amp-connections').innerHTML=amps.length?'<ul class="space-y-2">'+amps.map(c=>'<li class="flex items-center justify-between gap-3 rounded-lg bg-stone-50 p-3 dark:bg-slate-950"><strong>'+esc(c.project)+'</strong>'+testButton('amp',c.connectionId)+'</li>').join('')+'</ul>':'No Amp connections yet.';if(gh.status===404){badge('#github-status','Unavailable','neutral');$('#github-installations').textContent='GitHub integration is not enabled for this Factorize deployment.';$('#github-install').classList.add('hidden');$('#github-manage').classList.add('hidden')}else if(!gh.ok){badge('#github-status','Action required','warn');$('#github-installations').textContent='GitHub installation status could not be loaded.'}else{const installs=await gh.json(),active=installs.filter(x=>x.state==='active');badge('#github-status',active.length?'Connected':installs.length?'Action required':'Not connected',active.length?'ok':'warn');$('#github-installations').innerHTML=installs.length?'<ul class="space-y-2">'+installs.map(x=>'<li class="rounded-lg bg-stone-50 p-3 dark:bg-slate-950"><strong>'+esc(x.accountLogin||'Installation '+x.installationId)+'</strong> · '+esc(x.accountType||'GitHub')+' · '+esc(x.state)+'</li>').join('')+'</ul>':'No GitHub App installations yet.'}bindTests()}catch(e){const error=$('#integration-error');error.textContent=e.message||'Could not load integration status.';error.classList.remove('hidden');['#linear-status','#github-status','#exe-status','#amp-status'].forEach(id=>badge(id,'Unavailable','neutral'))}}
function bindTests(){document.querySelectorAll('[data-test]').forEach(button=>button.onclick=async()=>{const original=button.textContent;button.disabled=true;button.textContent='Testing…';try{const kind=button.dataset.test,result=await request('/api/connections/'+kind+'/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({connectionId:button.dataset.id})});button.textContent=result.ok?'Connected':'Action required'}catch(e){button.textContent='Action required'}finally{setTimeout(()=>{button.disabled=false;button.textContent=original},1500)}})}
$('#connection').onsubmit=async e=>{e.preventDefault();const d=new FormData(e.currentTarget),m=$('#settings-message');try{await request('/api/connections/exe',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify({vmName:d.get('vmName'),apiToken:d.get('apiToken'),cwd:d.get('cwd'),agentKind:d.get('agentKind'),herdrCommand:'herdr',agentCommand:''})});e.currentTarget.reset();m.textContent='Connection saved. The token remains write-only.';await load()}catch(x){m.textContent=x.message}};
const ampPayload=()=>{const d=new FormData($('#amp-connection'));return {project:d.get('project'),accessToken:d.get('accessToken'),apiBaseUrl:d.get('apiBaseUrl')}};$('#test-amp').onclick=async()=>{const m=$('#amp-message');try{const x=await request('/api/connections/amp/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(ampPayload())});m.textContent=x.ok?'Amp connection succeeded.':'Amp connection needs attention.'}catch(x){m.textContent=x.message}};$('#amp-connection').onsubmit=async e=>{e.preventDefault();const m=$('#amp-message');try{await request('/api/connections/amp',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify(ampPayload())});e.currentTarget.reset();m.textContent='Amp connection saved. The token remains write-only.';await load()}catch(x){m.textContent=x.message}};load();`);
Loading