diff --git a/docs/gen-2156-validation.md b/docs/gen-2156-validation.md
new file mode 100644
index 00000000..71afa37b
--- /dev/null
+++ b/docs/gen-2156-validation.md
@@ -0,0 +1,30 @@
+# GEN-2156 validation
+
+Mutation state lives outside replaceable controls. Job/run/settings reads capture a generation and discard results if a mutation has started or completed since the read began. Requested refreshes are queued while a poll is busy and resume after visibility/focus restoration. Confirmed mutation responses acknowledge enable and stop immediately; background read errors are separate from mutation errors.
+
+Both Run paths retain the logical submission's idempotency key on retries, close the prompt dialog immediately, retain its draft, and display an explicitly unaccepted pending request. A new input creates a new logical submission. Navigation waits for the canonical run ID. Keys persist for the lifetime of the page, including polling rerenders; a full page reload does not retain an unresolved submission.
+
+Kill remains the existing stop request API. Availability is restricted to starting/running/blocked. Queued, stopping, and terminal states have no Kill control. History remains visible; stopping does not claim immediate termination.
+
+Scheduler wake remains awaited for REST and MCP. This change makes no claim of server latency improvement and introduces no asynchronous notification or recovery mechanism.
+
+## Controlled timing comparison
+
+Measured on 2026-10-09 by executing the generated job detail browser scripts from main (4afa350) and this implementation in happy-dom with Vitest fake timers. The enable POST fixture takes 200 ms before a simulated awaited wake of 400 ms; GET fixtures take 200 ms. The benchmark sampled the rendered button each millisecond. These are injected timings, not production measurements or measurements of a real Durable Object.
+
+| Metric | Main | Implementation |
+| --- | ---: | ---: |
+| Simulated mutation request duration | 600 ms | 600 ms |
+| Simulated awaited wake duration | 400 ms | 400 ms |
+| Click to visible enable feedback | 800 ms | 0 ms |
+| Click to confirmed enable state | 800 ms | 600 ms |
+
+The retained browser regression asserts immediate Starting feedback with a delayed 600 ms invocation response and navigation only after confirmation. Request and wake durations remain unchanged by design. Production request/wake timing should be measured independently before changing scheduler delivery.
+
+## Automated validation
+
+`npm run check --workspace=factorize` runs generated OpenAPI verification, API boundary checks, auth-email script tests, TypeScript, Vitest, and a Wrangler deployment dry run.
+
+Browser coverage executes generated scripts with delayed responses, changing polling snapshots, older reads resolving after mutation completion, uncertain outcomes, retries, prompt recovery, all stop-availability states, artifact-cleaning deletion, token creation/revocation, client disconnection, integration removal, and connection testing. Existing REST/MCP manual invocation replay tests exercise server idempotency.
+
+PostgreSQL integration suites require their configured test database and are skipped when it is absent. No production credentials, connections, jobs, or database contents are modified by validation.
diff --git a/packages/app/src/page-refresh.ts b/packages/app/src/page-refresh.ts
index 7f0e7c0e..c4ac37a4 100644
--- a/packages/app/src/page-refresh.ts
+++ b/packages/app/src/page-refresh.ts
@@ -1,16 +1,17 @@
/** Shared browser orchestration. Completion-based timers prevent overlapping polls. */
export const pageRefreshBrowserSource = `
function pageRefresh(load,{delay=()=>3000,onError=()=>{}}={}){
- let timer,busy=false,stopped=false,failures=0;
+ let timer,busy=false,stopped=false,failures=0,queued=false;
const clear=()=>{clearTimeout(timer);timer=undefined};
const schedule=ms=>{clear();if(!stopped&&!document.hidden&&ms!==null)timer=setTimeout(refresh,ms)};
async function refresh(){
- if(stopped||document.hidden||busy)return;
+ if(stopped||document.hidden||busy){queued=true;return}
+ queued=false;
clear();busy=true;
let next;
try{await load();failures=0;next=delay()}
catch(error){failures++;next=Math.min(30000,5000*2**(failures-1));onError(error)}
- finally{busy=false;schedule(next)}
+ finally{busy=false;if(queued&&!stopped&&!document.hidden){queued=false;refresh()}else schedule(next)}
}
const resume=()=>{clear();if(!document.hidden)refresh()};
const hide=()=>{stopped=true;clear()};
diff --git a/packages/app/src/ui.ts b/packages/app/src/ui.ts
index 6578e62f..4a4eee3c 100644
--- a/packages/app/src/ui.ts
+++ b/packages/app/src/ui.ts
@@ -94,7 +94,21 @@ const uiHelpers = `
const $=s=>document.querySelector(s),esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
${ansiToHtmlBrowserSource}
${pageRefreshBrowserSource}
-const request=async(url,options)=>{const requestUrl=String(url).startsWith('/api/v1/runs?jobId=')&&!String(url).includes('limit=')?String(url)+'&limit=20':url,r=await fetch(requestUrl,options),body=await r.json().catch(()=>({}));if(r.status===401){location.href='/auth/login';throw new Error('Unauthorized')}if(!r.ok)throw new Error(body.error?.message||body.error||'Request failed');return body};
+const request=async(url,options)=>{const requestUrl=String(url).startsWith('/api/v1/runs?jobId=')&&!String(url).includes('limit=')?String(url)+'&limit=20':url,r=await fetch(requestUrl,options),body=await r.json().catch(()=>({}));if(r.status===401){location.href='/auth/login';throw new Error('Unauthorized')}if(!r.ok){const error=new Error(body.error?.message||body.error||'Request failed');error.definitive=r.status>=400&&r.status<500;throw error;}return body};
+// State belongs to the page, not replaceable controls. Each mutation invalidates older reads.
+let mutationGeneration=0;
+const pendingMutations=new Map();
+function applyPendingMutations(){
+ document.querySelectorAll('[data-mutation-label]').forEach(button=>{if(![...pendingMutations.keys()].some(selector=>button.matches(selector))){button.disabled=false;button.textContent=button.dataset.mutationLabel;delete button.dataset.mutationLabel}});
+ for(const [selector,label] of pendingMutations){document.querySelectorAll(selector).forEach(button=>{if(button.dataset.mutationLabel===undefined)button.dataset.mutationLabel=button.textContent;button.disabled=true;if(button.textContent!==label)button.textContent=label})}
+}
+
+async function mutate(selector,label,operation){
+ if(pendingMutations.has(selector))return;
+ pendingMutations.set(selector,label);mutationGeneration++;applyPendingMutations();
+ try{return await operation()}finally{mutationGeneration++;pendingMutations.delete(selector);applyPendingMutations();if(typeof applyEnabled==='function')applyEnabled()}
+}
+const reconcile=(refresh)=>{Promise.resolve().then(refresh).catch(()=>{})};
const jobRunsPageSize=20,jobRunsState={page:1,cursors:[null],runs:null,loading:false};
const jobRunsMarkup=r=>r.items?.length?'
':'No runs yet.
';
const jobRunsControls=(r,page)=>{if(page===1&&!r.nextCursor)return'';const previous=page>1?'':' disabled aria-disabled="true"',next=r.nextCursor?'':' disabled aria-disabled="true"';return'Previous Page '+page+' Next '};
@@ -192,23 +206,30 @@ export const jobDetailPage = (viewer: { email: string }, jobId: string) => shell
`, `${uiHelpers}
const id=$('#job-detail').dataset.id,root=$('#job-detail');
const manualRunDialog=$('#manual-run-dialog'),manualRunForm=$('#manual-run-form');
- const nativeJobFetch=window.fetch.bind(window);window.fetch=async(input,init)=>{const response=await nativeJobFetch(input,init);if(!init?.method&&String(input).includes('/api/v1/jobs/'))response.clone().json().then(j=>setTimeout(()=>{const details=root.querySelector('dl');if(details&&!details.querySelector('[data-name-template]'))details.insertAdjacentHTML('beforeend','Name template '+esc(j.runNameTemplate||'Default run name')+' ')},0)).catch(()=>{});return response};
-function openManualRun(){closeRunMenu();manualRunForm.reset();$('#manual-run-error').classList.add('hidden');manualRunDialog.showModal();$('#manual-run-prompt').focus()}
+function openManualRun(){closeRunMenu();$('#manual-run-error').classList.toggle('hidden',!runError);manualRunDialog.showModal();$('#manual-run-prompt').focus()}
$('#cancel-manual-run').onclick=()=>manualRunDialog.close();manualRunDialog.onclick=e=>{if(e.target===manualRunDialog)manualRunDialog.close()};
-async function createManualRun(input){const x=await request('/api/v1/jobs/'+encodeURIComponent(id)+'/invocations',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(input)});location.href='/job-runs/'+encodeURIComponent(x.runId)}
-let manualRunPending=false;
-function setRunPending(value){manualRunPending=value;['run','run-options','run-with-prompt','submit-manual-run'].forEach(id=>{const button=$('#'+id);if(button)button.disabled=value})}
+let manualRunPending=false,manualSubmission=null,runError='';
+function setRunPending(value){manualRunPending=value;['run','run-options','run-with-prompt','submit-manual-run'].forEach(id=>{const button=$('#'+id);if(button){button.disabled=value;if(id==='run')button.textContent=value?'Starting…':'Run'}});const error=$('#run-error');if(error){error.textContent=runError;error.hidden=!runError}let indicator=$('[data-pending-run]');if(value&&!indicator){root.querySelector('[data-job-runs-section]')?.insertAdjacentHTML('afterbegin','Starting… Awaiting acceptance of your run request.
')}if(!value)indicator?.remove()}
+async function submitManualRun(input){
+ if(manualRunPending)return;
+ if(!manualSubmission||JSON.stringify(manualSubmission.input)!==JSON.stringify(input))manualSubmission={input,idempotencyKey:crypto.randomUUID()};
+ runError='';closeRunMenu();setRunPending(true);manualRunDialog.close();mutationGeneration++;
+ try{const x=await request('/api/v1/jobs/'+encodeURIComponent(id)+'/invocations',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({...input,idempotencyKey:manualSubmission.idempotencyKey})});manualSubmission=null;location.href='/job-runs/'+encodeURIComponent(x.runId)}
+ catch(e){runError=e.message+(e.definitive?'':' Outcome unknown. Retry uses the same submission key.');setRunPending(false);const error=$('#manual-run-error');error.textContent=runError;error.classList.remove('hidden');reconcile(()=>jobRefresh.refresh())}
+ finally{mutationGeneration++}
+}
function closeRunMenu(restoreFocus=false){const menu=$('#run-menu'),button=$('#run-options');if(!menu)return;menu.hidden=true;button.setAttribute('aria-expanded','false');if(restoreFocus)button.focus()}
document.addEventListener('click',e=>{if(!e.target.closest('[data-run-actions]'))closeRunMenu()});
document.addEventListener('focusin',e=>{if(!e.target.closest('[data-run-actions]'))closeRunMenu()});
document.addEventListener('keydown',e=>{if(e.key==='Escape'&&$('#run-menu')&&!$('#run-menu').hidden){e.preventDefault();closeRunMenu(true)}});
-async function runImmediately(){if(manualRunPending)return;closeRunMenu();const error=$('#run-error');error.hidden=true;setRunPending(true);try{await createManualRun({})}catch(e){error.textContent=e.message;error.hidden=false;setRunPending(false)}}
-manualRunForm.onsubmit=async e=>{e.preventDefault();if(manualRunPending)return;const error=$('#manual-run-error');setRunPending(true);error.classList.add('hidden');try{await createManualRun({prompt:manualRunForm.elements.prompt.value})}catch(e){error.textContent=e.message;error.classList.remove('hidden');setRunPending(false)}};
+async function runImmediately(){return submitManualRun({})}
+manualRunForm.onsubmit=e=>{e.preventDefault();return submitManualRun({prompt:manualRunForm.elements.prompt.value})};
const activeRunStates=['queued','starting','running','blocked','stopping'];let elapsedTimer;
function elapsedSince(value){const seconds=Math.max(0,Math.floor((Date.now()-new Date(value).getTime())/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 refreshRunElapsed(){document.querySelectorAll('[data-run-started]').forEach(label=>label.textContent=elapsedSince(label.dataset.runStarted))}
-let jobSnapshot,jobActive=false;
-async function load(){if(jobRunsState.loading)return;jobRunsState.loading=true;try{const cursor=jobRunsState.cursors[jobRunsState.page];const [j,runs]=await Promise.all([request('/api/v1/jobs/'+encodeURIComponent(id)),request('/api/v1/runs?jobId='+encodeURIComponent(id)+'&limit='+jobRunsPageSize+(cursor?'&cursor='+encodeURIComponent(cursor):''))]),triggers=j.triggers||[],status=jobStatus(j),hasActiveRuns=runs.items.some(r=>activeRunStates.includes(r.state));jobActive=j.runningCount>0||hasActiveRuns;const snapshot=JSON.stringify([j,runs,jobRunsState.page]);if(snapshot===jobSnapshot)return;jobSnapshot=snapshot;clearInterval(elapsedTimer);jobRunsState.runs=runs;replacePageContent(root,'Jobs / '+esc(j.name)+' '+esc(j.name)+' '+esc(j.runningCount)+'/'+esc(j.concurrencyLimit)+' Running '+(j.enabled?'':'Disabled ')+'
Details Triggers '+(triggers.length?triggers.map(t=>triggerBadge(t.kind)).join(' '):'None')+' Model '+esc(j.model||'Harness default')+' Prompt template '+esc(j.promptTemplate)+'
'+(j.enabled?'Disable':'Enable')+' Edit Delete
Runs '+(runs.items.length?jobRunsMarkup(runs):'No runs yet.
')+' ',refreshJobRunsPagination);if(hasActiveRuns)elapsedTimer=setInterval(refreshRunElapsed,1000);setRunPending(manualRunPending);$('#run').onclick=runImmediately;$('#run-with-prompt').onclick=openManualRun;$('#run-options').onclick=()=>{const menu=$('#run-menu');menu.hidden=!menu.hidden;$('#run-options').setAttribute('aria-expanded',String(!menu.hidden));if(!menu.hidden)$('#run-with-prompt').focus()};$('#run-options').onkeydown=e=>{if(e.key==='ArrowDown'){e.preventDefault();$('#run-menu').hidden=false;$('#run-options').setAttribute('aria-expanded','true');$('#run-with-prompt').focus()}};$('#toggle').onclick=async()=>{await request('/api/v1/jobs/'+encodeURIComponent(id)+'/'+(j.enabled?'disable':'enable'),{method:'POST'});jobRefresh.refresh()};$('#delete').onclick=async()=>{if(confirm('Delete this job and its queued history?')){await request('/api/v1/jobs/'+encodeURIComponent(id),{method:'DELETE'});location.href='/jobs'}}}finally{jobRunsState.loading=false}}
+let jobSnapshot,jobActive=false,enabledOverride;
+function applyEnabled(){const button=$('#toggle');if(button&&enabledOverride!==undefined){button.textContent=pendingMutations.has('#toggle')?(enabledOverride?'Enabling…':'Disabling…'):(enabledOverride?'Disable':'Enable');const badge=$('[data-enabled-badge]');if(badge)badge.textContent=enabledOverride?'Enabled':'Disabled'}}
+async function load(){if(jobRunsState.loading)return;jobRunsState.loading=true;try{const generation=mutationGeneration;const cursor=jobRunsState.cursors[jobRunsState.page];const [j,runs]=await Promise.all([request('/api/v1/jobs/'+encodeURIComponent(id)),request('/api/v1/runs?jobId='+encodeURIComponent(id)+'&limit='+jobRunsPageSize+(cursor?'&cursor='+encodeURIComponent(cursor):''))]);if(generation!==mutationGeneration){reconcile(()=>jobRefresh.refresh());return}if(enabledOverride!==undefined){if(!pendingMutations.has('#toggle'))enabledOverride=undefined;else j.enabled=enabledOverride}const triggers=j.triggers||[],status=jobStatus(j),hasActiveRuns=runs.items.some(r=>activeRunStates.includes(r.state));jobActive=j.runningCount>0||hasActiveRuns;const snapshot=JSON.stringify([j,runs,jobRunsState.page]);if(snapshot===jobSnapshot)return;jobSnapshot=snapshot;clearInterval(elapsedTimer);jobRunsState.runs=runs;replacePageContent(root,'Jobs / '+esc(j.name)+' '+esc(j.name)+' '+esc(j.runningCount)+'/'+esc(j.concurrencyLimit)+' Running '+''+(j.enabled?'Enabled':'Disabled')+' '+'
Details Triggers '+(triggers.length?triggers.map(t=>triggerBadge(t.kind)).join(' '):'None')+' Model '+esc(j.model||'Harness default')+' Name template '+esc(j.runNameTemplate||'Default run name')+' Prompt template '+esc(j.promptTemplate)+'
'+(j.enabled?'Disable':'Enable')+' Edit Delete
Runs '+(runs.items.length?jobRunsMarkup(runs):'No runs yet.
')+' ',refreshJobRunsPagination);if(hasActiveRuns)elapsedTimer=setInterval(refreshRunElapsed,1000);setRunPending(manualRunPending);$('#run').onclick=runImmediately;$('#run-with-prompt').onclick=openManualRun;$('#run-options').onclick=()=>{const menu=$('#run-menu');menu.hidden=!menu.hidden;$('#run-options').setAttribute('aria-expanded',String(!menu.hidden));if(!menu.hidden)$('#run-with-prompt').focus()};$('#run-options').onkeydown=e=>{if(e.key==='ArrowDown'){e.preventDefault();$('#run-menu').hidden=false;$('#run-options').setAttribute('aria-expanded','true');$('#run-with-prompt').focus()}};applyEnabled();applyPendingMutations();$('#toggle').onclick=()=>mutate('#toggle',j.enabled?'Disabling…':'Enabling…',async()=>{const prior=j.enabled;enabledOverride=!prior;applyEnabled();try{const result=await request('/api/v1/jobs/'+encodeURIComponent(id)+'/'+(prior?'disable':'enable'),{method:'POST'});enabledOverride=result.enabled;j.enabled=result.enabled}catch(e){if(e.definitive)enabledOverride=prior;runError=e.message+(e.definitive?'':' Outcome unknown; checking server state.');setRunPending(manualRunPending)}finally{applyEnabled();reconcile(()=>jobRefresh.refresh())}});$('#delete').onclick=()=>{if(confirm('Delete this job and its queued history?'))mutate('#delete','Deleting…',async()=>{try{await request('/api/v1/jobs/'+encodeURIComponent(id),{method:'DELETE'});location.href='/jobs'}catch(e){runError=e.message;setRunPending(manualRunPending);reconcile(()=>jobRefresh.refresh())}})}}finally{jobRunsState.loading=false}}
const jobRefresh=pageRefresh(load,{delay:()=>jobActive?3000:10000,onError:e=>{if(!jobSnapshot)root.innerHTML=''+esc(e.message)+'
'}});`);
export const jobRunPage = (viewer: { email: string }, runId: string) => shell("Run — Factorize", viewer, ` `, `${uiHelpers}
@@ -232,13 +253,13 @@ function updateRun(r){
root.classList.toggle('trace-running',r.state==='running');
const activity=$('[data-trace-activity]');if(activity)activity.hidden=r.state!=='running';
const state=$('[data-run-state]');if(state)state.innerHTML=stateBadge(r.state);
- if(!activeStates.includes(r.state))$('#kill-run')?.remove();
+ if(!['starting','running','blocked'].includes(r.state))$('#kill-run')?.remove();
const live=$('[data-run-live]');if(live)live.hidden=!activeStates.includes(r.state);
const artifact=$('[data-run-artifact]');if(artifact)artifact.textContent=traceSourceLabel(r)+(r.artifact_error?' · '+r.artifact_error:'');
updateElapsed(r);
}
-async function refreshOutput(){const r=await request('/api/v1/runs/'+encodeURIComponent(id));const reset=currentRun&&(r.trace_generation!==currentRun.trace_generation||JSON.stringify(r.trace_projection)!==JSON.stringify(currentRun.trace_projection)||(activeStates.includes(currentRun.state)&&!activeStates.includes(r.state)));updateRun(r);if(traceLoading)await traceLoading;traceDone=false;await loadTrace(Boolean(reset))}
-async function loadRun(){return 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=activeStates.includes(r.state),runLabel=r.name||r.run_name||r.issue_title||'Run '+r.id.slice(0,8);document.title=runLabel+' — Factorize';root.innerHTML='Jobs / '+esc(j.name)+' / '+esc(runLabel)+' '+esc(runLabel)+' '+elapsed(r)+'
'+queueTime(r)+'
'+stateBadge(r.state)+' '+(canKill?'Kill run ':'')+'
'+triggerProvenance(r)+'Prompt '+esc(r.prompt||'Prompt is not available for this run.')+' Trace '+esc(traceSourceLabel(r))+'
'+(activeStates.includes(r.state)?'
Live · refreshes automatically ':'')+'
Trace events are not available yet.
Thinking…
Load more ';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'});await runRefresh.refresh()};$('[data-trace-more]').onclick=()=>{traceDone=false;loadTrace().catch(()=>{})};updateRun(r);await loadTrace()})}
+async function refreshOutput(){const generation=mutationGeneration;const r=await request('/api/v1/runs/'+encodeURIComponent(id));if(generation!==mutationGeneration){reconcile(()=>runRefresh.refresh());return}const reset=currentRun&&(r.trace_generation!==currentRun.trace_generation||JSON.stringify(r.trace_projection)!==JSON.stringify(currentRun.trace_projection)||(activeStates.includes(currentRun.state)&&!activeStates.includes(r.state)));updateRun(r);if(traceLoading)await traceLoading;traceDone=false;await loadTrace(Boolean(reset))}
+async function loadRun(){return 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=['starting','running','blocked'].includes(r.state),runLabel=r.name||r.run_name||r.issue_title||'Run '+r.id.slice(0,8);document.title=runLabel+' — Factorize';root.innerHTML='Jobs / '+esc(j.name)+' / '+esc(runLabel)+' '+esc(runLabel)+' '+elapsed(r)+'
'+queueTime(r)+'
'+stateBadge(r.state)+' '+(canKill?'Kill run ':'')+'
'+triggerProvenance(r)+'Prompt '+esc(r.prompt||'Prompt is not available for this run.')+' Trace '+esc(traceSourceLabel(r))+'
'+(activeStates.includes(r.state)?'
Live · refreshes automatically ':'')+'
Trace events are not available yet.
Thinking…
Load more ';if(canKill)$('#kill-run').onclick=()=>{if(!confirm('Request this run to stop? It remains visible until the backend confirms termination.'))return;mutate('#kill-run','Stopping…',async()=>{try{const result=await request('/api/v1/runs/'+encodeURIComponent(id)+'/kill',{method:'POST'});updateRun({...currentRun,state:result.state})}catch(e){let error=$('[data-stop-error]');if(!error){root.insertAdjacentHTML('afterbegin','
');error=$('[data-stop-error]')}error.textContent=e.message+(e.definitive?'':' Outcome unknown; checking server state.')}reconcile(()=>runRefresh.refresh())})};$('[data-trace-more]').onclick=()=>{traceDone=false;loadTrace().catch(()=>{})};updateRun(r);await loadTrace()})}
const runRefresh=pageRefresh(async()=>{if(!currentRun)await loadRun();else await refreshOutput()},{delay:()=>activeStates.includes(currentRun.state)?3000:['pending','collecting'].includes(currentRun.artifact_state)?10000:null,onError:e=>{if(!currentRun)root.innerHTML=''+esc(e.message)+'
'}});`);
const settingsLayout = (active: "integrations" | "api-keys", content: string) => `
@@ -270,20 +291,27 @@ const badge=(id,label,tone)=>{const el=$(id);el.textContent=label;el.className='
const integrationIcons=${JSON.stringify(integrationIcons)};
const testButton=(kind,id)=>'Test Remove ';
const installedRow=(name,description,status,tone,actions)=>''+integrationIcons[name==='Cloudflare Tail'?'tail':name==='Exe.dev'?'exe':name.toLowerCase()]+'
'+esc(name)+' Actions '+actions+'
'+description+'
'+esc(status)+' ';
-async function disconnectGitHub(id){if(!confirm('Disconnect this GitHub installation from Factorize?'))return;await request('/api/v1/providers/github/installations/'+encodeURIComponent(id),{method:'DELETE'});await load()}
-async function load(){const loading=$('#installed-loading'),list=$('#installed-integrations'),table=$('#installed-table'),empty=$('#installed-empty');loading.classList.remove('hidden');table.classList.add('hidden');empty.classList.add('hidden');$('#integration-error').classList.add('hidden');try{const [s,gh,tails]=await Promise.all([request('/api/v1/integrations'),fetch('/api/v1/providers/github/installations'),request('/api/v1/integrations/cloudflare-tail')]),rows=[];const exe=s.exeConnections||[],amps=s.ampConnections||[];badge('#linear-available-status',(s.linear?1:0)+' installed','neutral');badge('#clickup-available-status',(s.clickup?1:0)+' installed','neutral');badge('#exe-available-status',exe.length+' installed','neutral');badge('#amp-available-status',amps.length+' installed','neutral');badge('#tail-available-status',tails.length+' installed','neutral');$('#linear-action').textContent=s.linear?'Reconnect Linear':'Continue to Linear';if(s.linear)rows.push(installedRow('Linear',esc(s.linear.organizationName||'Linear workspace')+(s.linear.viewerEmail?' · '+esc(s.linear.viewerEmail):''),'Connected','ok','Reconnect '));if(s.clickup)rows.push(installedRow('ClickUp',esc(s.clickup.teamName||'ClickUp workspace'),'Connected','ok','Reconnect '));exe.forEach(c=>rows.push(installedRow('Exe.dev',esc(c.agentKind)+(c.models?.length?' · '+c.models.length+' models':'')+(c.tags?.length?' · tags: '+esc(c.tags.join(', ')):' · no VM tags'),'Connected','ok',testButton('exe',c.connectionId)+'Add another ')));amps.forEach(c=>rows.push(installedRow('Amp',esc(c.project),'Connected','ok',testButton('amp',c.connectionId)+'Add another ')));tails.forEach(c=>rows.push(installedRow('Cloudflare Tail',esc(c.name)+(c.referencedJobCount?' · '+c.referencedJobCount+' jobs':''),'Connected','ok','Test Configure Disconnect ')));if(gh.status===404){badge('#github-available-status','Unavailable','neutral');$('#github-install').classList.add('hidden')}else if(!gh.ok){badge('#github-available-status','Action required','warn');rows.push(installedRow('GitHub','Installation status could not be loaded.','Action required','warn','Reconnect '))}else{const installs=await gh.json(),active=installs.filter(x=>x.state==='active');badge('#github-available-status',active.length+' installed',installs.length&&!active.length?'warn':'neutral');$('#github-install').textContent=active.length?'Add another installation':'Continue to GitHub';installs.forEach(x=>rows.push(installedRow('GitHub',esc(x.accountLogin||'Installation '+x.installationId)+' · '+esc(x.accountType||'GitHub'),x.state==='active'?'Connected':x.state,'active'===x.state?'ok':'warn','Configure ↗ Disconnect ')))}list.innerHTML=rows.join('');loading.classList.add('hidden');table.classList.toggle('hidden',!rows.length);empty.classList.toggle('hidden',rows.length>0);bindActions()}catch(e){loading.classList.add('hidden');empty.classList.remove('hidden');const error=$('#integration-error');error.textContent=e.message||'Could not load integration status. Try again.';error.classList.remove('hidden');['linear','clickup','github','exe','amp','tail'].forEach(id=>badge('#'+id+'-available-status','Unavailable','neutral'))}}
+async function disconnectGitHub(id){if(!confirm('Disconnect this GitHub installation from Factorize?'))return;await mutate('[data-disconnect-github="'+id+'"]','Disconnecting…',async()=>{await request('/api/v1/providers/github/installations/'+encodeURIComponent(id),{method:'DELETE'});reconcile(load)})}
+async function load(){const generation=mutationGeneration;const loading=$('#installed-loading'),list=$('#installed-integrations'),table=$('#installed-table'),empty=$('#installed-empty');loading.classList.remove('hidden');table.classList.add('hidden');empty.classList.add('hidden');$('#integration-error').classList.add('hidden');try{const [s,gh,tails]=await Promise.all([request('/api/v1/integrations'),fetch('/api/v1/providers/github/installations'),request('/api/v1/integrations/cloudflare-tail')]),rows=[];const exe=s.exeConnections||[],amps=s.ampConnections||[];badge('#linear-available-status',(s.linear?1:0)+' installed','neutral');badge('#clickup-available-status',(s.clickup?1:0)+' installed','neutral');badge('#exe-available-status',exe.length+' installed','neutral');badge('#amp-available-status',amps.length+' installed','neutral');badge('#tail-available-status',tails.length+' installed','neutral');$('#linear-action').textContent=s.linear?'Reconnect Linear':'Continue to Linear';if(s.linear)rows.push(installedRow('Linear',esc(s.linear.organizationName||'Linear workspace')+(s.linear.viewerEmail?' · '+esc(s.linear.viewerEmail):''),'Connected','ok','Reconnect '));if(s.clickup)rows.push(installedRow('ClickUp',esc(s.clickup.teamName||'ClickUp workspace'),'Connected','ok','Reconnect '));exe.forEach(c=>rows.push(installedRow('Exe.dev',esc(c.agentKind)+(c.models?.length?' · '+c.models.length+' models':'')+(c.tags?.length?' · tags: '+esc(c.tags.join(', ')):' · no VM tags'),'Connected','ok',testButton('exe',c.connectionId)+'Add another ')));amps.forEach(c=>rows.push(installedRow('Amp',esc(c.project),'Connected','ok',testButton('amp',c.connectionId)+'Add another ')));tails.forEach(c=>rows.push(installedRow('Cloudflare Tail',esc(c.name)+(c.referencedJobCount?' · '+c.referencedJobCount+' jobs':''),'Connected','ok','Test Configure Disconnect ')));if(gh.status===404){badge('#github-available-status','Unavailable','neutral');$('#github-install').classList.add('hidden')}else if(!gh.ok){badge('#github-available-status','Action required','warn');rows.push(installedRow('GitHub','Installation status could not be loaded.','Action required','warn','Reconnect '))}else{const installs=await gh.json(),active=installs.filter(x=>x.state==='active');badge('#github-available-status',active.length+' installed',installs.length&&!active.length?'warn':'neutral');$('#github-install').textContent=active.length?'Add another installation':'Continue to GitHub';installs.forEach(x=>rows.push(installedRow('GitHub',esc(x.accountLogin||'Installation '+x.installationId)+' · '+esc(x.accountType||'GitHub'),x.state==='active'?'Connected':x.state,'active'===x.state?'ok':'warn','Configure ↗ Disconnect ')))}if(generation!==mutationGeneration){reconcile(load);return}list.innerHTML=rows.join('');loading.classList.add('hidden');table.classList.toggle('hidden',!rows.length);empty.classList.toggle('hidden',rows.length>0);bindActions();applyPendingMutations()}catch(e){loading.classList.add('hidden');empty.classList.remove('hidden');const error=$('#integration-error');error.textContent=e.message||'Could not load integration status. Try again.';error.classList.remove('hidden');['linear','clickup','github','exe','amp','tail'].forEach(id=>badge('#'+id+'-available-status','Unavailable','neutral'))}}
function openSetup(kind){const dialog=$('#'+kind+'-setup');if(!dialog.open)dialog.showModal()}
function closeSetup(kind){const dialog=$('#'+kind+'-setup');if(dialog.open)dialog.close()}
-async function tailAction(id,method){await request('/api/v1/integrations/cloudflare-tail/'+encodeURIComponent(id),{method});await load()}
-function bindActions(){bindTests();document.querySelectorAll('[data-open-setup]').forEach(button=>button.onclick=()=>{if(button.dataset.openSetup==='tail'){delete $('#tail-connection').dataset.id;$('#tail-connection').reset()}openSetup(button.dataset.openSetup)});document.querySelectorAll('[data-close-setup]').forEach(button=>button.onclick=()=>closeSetup(button.dataset.closeSetup));document.querySelectorAll('dialog').forEach(dialog=>dialog.onclick=e=>{if(e.target===dialog)dialog.close()});document.querySelectorAll('[data-disconnect-github]').forEach(button=>button.onclick=()=>disconnectGitHub(button.dataset.disconnectGithub).catch(showError));document.querySelectorAll('[data-disconnect-tail]').forEach(button=>button.onclick=()=>{if(confirm('Disconnect this Tail installation? Jobs using it will need another installation.'))tailAction(button.dataset.disconnectTail,'DELETE').catch(showError)});document.querySelectorAll('[data-test-tail]').forEach(button=>button.onclick=async()=>{button.disabled=true;try{await request('/api/v1/integrations/cloudflare-tail/'+encodeURIComponent(button.dataset.testTail)+'/test',{method:'POST'});button.textContent='Connected'}catch(e){button.textContent='Action required'}finally{button.disabled=false}});document.querySelectorAll('[data-configure-tail]').forEach(button=>button.onclick=()=>{const form=$('#tail-connection');form.dataset.id=button.dataset.configureTail;form.elements.name.value=button.dataset.name;openSetup('tail')})}
-function showError(e){const error=$('#integration-error');error.textContent=e.message||'The integration action failed.';error.classList.remove('hidden')}
-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/v1/integrations/'+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)}})}
-document.addEventListener('click',async event=>{const button=event.target.closest('[data-remove-integration]');if(!button||!confirm('Remove this integration?'))return;button.disabled=true;try{await request('/api/v1/integrations/'+button.dataset.removeIntegration+'/'+encodeURIComponent(button.dataset.id),{method:'DELETE'});await load()}catch(error){button.disabled=false;showError(error)}});
+async function tailAction(id,method){await mutate('[data-disconnect-tail="'+id+'"]','Disconnecting…',async()=>{await request('/api/v1/integrations/cloudflare-tail/'+encodeURIComponent(id),{method});reconcile(load)})}
+function bindActions(){bindTests();document.querySelectorAll('[data-open-setup]').forEach(button=>button.onclick=()=>{if(button.dataset.openSetup==='tail'){delete $('#tail-connection').dataset.id;$('#tail-connection').reset()}openSetup(button.dataset.openSetup)});document.querySelectorAll('[data-close-setup]').forEach(button=>button.onclick=()=>closeSetup(button.dataset.closeSetup));document.querySelectorAll('dialog').forEach(dialog=>dialog.onclick=e=>{if(e.target===dialog)dialog.close()});document.querySelectorAll('[data-disconnect-github]').forEach(button=>button.onclick=()=>disconnectGitHub(button.dataset.disconnectGithub).catch(showError));document.querySelectorAll('[data-disconnect-tail]').forEach(button=>button.onclick=()=>{if(confirm('Disconnect this Tail installation? Jobs using it will need another installation.'))tailAction(button.dataset.disconnectTail,'DELETE').catch(showError)});document.querySelectorAll('[data-test-tail]').forEach(button=>button.onclick=async()=>{if(button.disabled)return;button.disabled=true;button.textContent='Testing…';try{await request('/api/v1/integrations/cloudflare-tail/'+encodeURIComponent(button.dataset.testTail)+'/test',{method:'POST'});button.textContent='Connected'}catch(e){button.textContent='Action required'}finally{button.disabled=false}});document.querySelectorAll('[data-configure-tail]').forEach(button=>button.onclick=()=>{const form=$('#tail-connection');form.dataset.id=button.dataset.configureTail;form.elements.name.value=button.dataset.name;openSetup('tail')})}
+function showError(e){const error=$('#integration-error');error.textContent=(e.message||'The integration action failed.')+(e.definitive?'':' Check server state before retrying.');error.classList.remove('hidden')}
+function bindTests(){document.querySelectorAll('[data-test]').forEach(button=>button.onclick=async()=>{
+ const kind=button.dataset.test,id=button.dataset.id,selector='[data-test="'+kind+'"][data-id="'+id+'"]';
+ if(pendingMutations.has(selector))return;
+ let label='Action required';
+ await mutate(selector,'Testing…',async()=>{try{const result=await request('/api/v1/integrations/'+kind+'/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({connectionId:id})});label=result.ok?'Connected':'Action required'}catch(e){showError(e)}});
+ document.querySelectorAll(selector).forEach(current=>current.textContent=label);
+})}
+
+document.addEventListener('click',async event=>{const button=event.target.closest('[data-remove-integration]');if(!button||!confirm('Remove this integration?'))return;if(button.disabled)return;return mutate('[data-remove-integration="'+button.dataset.removeIntegration+'"][data-id="'+button.dataset.id+'"]','Removing…',async()=>{try{await request('/api/v1/integrations/'+button.dataset.removeIntegration+'/'+encodeURIComponent(button.dataset.id),{method:'DELETE'});button.closest('article')?.remove();reconcile(load)}catch(error){showError(error);reconcile(load)}})});
const exePayload=()=>{const form=$('#connection');return {apiToken:form.elements.apiToken.value,agentKind:form.elements.agentKind.value,tags:[...form.elements.tags.selectedOptions].map(option=>option.value)}};
let exeTokenTimer=0,exeTokenRequest=0,verifiedExeToken='';async function testExeToken(){const form=$('#connection'),m=$('#settings-message'),status=$('#exe-token-status'),valid=$('#exe-token-valid'),button=$('#test-exe-token'),token=form.elements.apiToken.value.trim(),requestId=++exeTokenRequest;if(!token)return;button.disabled=true;status.textContent='Testing token and loading tags…';try{const result=await request('/api/v1/integrations/exe/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({apiToken:token})});if(requestId!==exeTokenRequest||token!==form.elements.apiToken.value.trim())return;if(!result.ok){verifiedExeToken='';valid.classList.add('hidden');valid.classList.remove('flex');status.textContent=result.missingPermissions.length?'Missing required permissions: '+result.missingPermissions.join(', '):'The token could not be verified. Check that it is valid and try again.';return}verifiedExeToken=token;valid.classList.remove('hidden');valid.classList.add('flex');form.elements.tags.replaceChildren(...result.tags.map(tag=>new Option(tag,tag)));form.elements.tags.disabled=false;status.textContent=result.tags.length?'Token verified. Select the VM tags to attach.':'Token verified. No integration tags were found.';m.textContent=''}catch(error){if(requestId===exeTokenRequest){verifiedExeToken='';valid.classList.add('hidden');valid.classList.remove('flex');status.textContent=error.message}}finally{if(requestId===exeTokenRequest)button.disabled=false}}$('#test-exe-token').onclick=testExeToken;$('#connection').elements.apiToken.addEventListener('input',event=>{clearTimeout(exeTokenTimer);exeTokenRequest++;verifiedExeToken='';const form=$('#connection'),valid=$('#exe-token-valid'),status=$('#exe-token-status'),token=event.target.value.trim();valid.classList.add('hidden');valid.classList.remove('flex');form.elements.tags.disabled=true;status.textContent=token?'Waiting for you to finish typing…':'Token testing starts automatically after you finish typing.';if(token.length>=16)exeTokenTimer=setTimeout(testExeToken,500)});
-$('#connection').onsubmit=async e=>{e.preventDefault();const form=e.currentTarget,m=$('#settings-message');try{m.textContent='Creating a temporary VM to validate the agent and load models…';await request('/api/v1/integrations/exe',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify(exePayload())});form.reset();verifiedExeToken='';$('#exe-token-valid').classList.add('hidden');$('#exe-token-valid').classList.remove('flex');$('#exe-token-status').textContent='Token testing starts automatically after you finish typing.';form.elements.tags.disabled=true;m.textContent='VM connection saved.';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/v1/integrations/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 form=e.currentTarget,m=$('#amp-message');try{await request('/api/v1/integrations/amp',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify(ampPayload())});form.reset();m.textContent='Amp connection saved. The token remains write-only.';await load()}catch(x){m.textContent=x.message}};
-$('#tail-connection').onsubmit=async e=>{e.preventDefault();const form=e.currentTarget,d=new FormData(form),m=$('#tail-message'),id=form.dataset.id,url='/api/v1/integrations/cloudflare-tail'+(id?'/'+encodeURIComponent(id):'');try{const x=await request(url,{method:id?'PUT':'POST',headers:{'content-type':'application/json'},body:JSON.stringify({name:d.get('name'),signingSecret:d.get('signingSecret')||undefined,generateSecret:d.get('generateSecret')==='on'})});if(x.generatedSecret){$('#tail-generated-value').textContent=x.generatedSecret;$('#tail-generated').classList.remove('hidden')}form.reset();delete form.dataset.id;m.textContent='Tail installation saved. Its secret remains write-only.';await load()}catch(x){m.textContent=x.message}};$('#copy-tail-secret').onclick=async()=>{await navigator.clipboard.writeText($('#tail-generated-value').textContent);$('#copy-tail-secret').textContent='Copied'};bindActions();load();`);
+$('#connection').onsubmit=async e=>{e.preventDefault();return mutate('#connection button[type=submit]','Creating…',async()=>{const form=e.currentTarget,m=$('#settings-message');try{m.textContent='Creating a temporary VM to validate the agent and load models…';await request('/api/v1/integrations/exe',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify(exePayload())});form.reset();verifiedExeToken='';$('#exe-token-valid').classList.add('hidden');$('#exe-token-valid').classList.remove('flex');$('#exe-token-status').textContent='Token testing starts automatically after you finish typing.';form.elements.tags.disabled=true;m.textContent='VM connection saved.';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=()=>mutate('#test-amp','Testing…',async()=>{const m=$('#amp-message');try{const x=await request('/api/v1/integrations/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();return mutate('#amp-connection button[type=submit]','Creating…',async()=>{const form=e.currentTarget,m=$('#amp-message');try{await request('/api/v1/integrations/amp',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify(ampPayload())});form.reset();m.textContent='Amp connection saved. The token remains write-only.';await load()}catch(x){m.textContent=x.message}})};
+$('#tail-connection').onsubmit=async e=>{e.preventDefault();return mutate('#tail-connection button[type=submit]','Creating…',async()=>{const form=e.currentTarget,d=new FormData(form),m=$('#tail-message'),id=form.dataset.id,url='/api/v1/integrations/cloudflare-tail'+(id?'/'+encodeURIComponent(id):'');try{const x=await request(url,{method:id?'PUT':'POST',headers:{'content-type':'application/json'},body:JSON.stringify({name:d.get('name'),signingSecret:d.get('signingSecret')||undefined,generateSecret:d.get('generateSecret')==='on'})});if(x.generatedSecret){$('#tail-generated-value').textContent=x.generatedSecret;$('#tail-generated').classList.remove('hidden')}form.reset();delete form.dataset.id;m.textContent='Tail installation saved. Its secret remains write-only.';await load()}catch(x){m.textContent=x.message}})};$('#copy-tail-secret').onclick=async()=>{await navigator.clipboard.writeText($('#tail-generated-value').textContent);$('#copy-tail-secret').textContent='Copied'};bindActions();load();`);
export const apiKeysSettingsPage = (viewer: { email: string }) => shell("API Keys — Factorize", viewer, settingsLayout("api-keys", `${dashboardHead("API Keys", "Manage API keys for programmatic access to Factorize.")}
@@ -298,12 +326,12 @@ const scopes=value=>(value||[]).map(scope=>''+esc(client.clientName)+' Client '+esc(client.clientId)+'
'+scopes(client.scopes)+'
Authorized '+date(client.authorizationDate)+'
Last used '+date(client.lastUsedAt)+'
Authorization expires '+date(client.expiresAt)+' Disconnect ';
const tokenRow=token=>''+esc(token.name)+' '+scopes(token.scopes)+'
Expires '+date(token.expires_at)+'
Created '+date(token.created_at)+'
Last used '+date(token.last_used_at)+' Revoke ';
-async function loadClients(){const loading=$('#clients-loading'),root=$('#authorized-clients'),empty=$('#clients-empty');loading.classList.remove('hidden');try{const clients=await request('/api/v1/access/authorized-clients');root.innerHTML=clients.map(clientRow).join('');root.classList.toggle('hidden',!clients.length);empty.classList.toggle('hidden',clients.length>0);bindClientActions()}catch(error){empty.classList.remove('hidden');accessError(error.message)}finally{loading.classList.add('hidden')}}
-async function loadTokens(){const loading=$('#tokens-loading'),root=$('#access-tokens'),empty=$('#tokens-empty');loading.classList.remove('hidden');try{const tokens=(await request('/api/v1/access-tokens')).filter(token=>!token.revoked_at);root.innerHTML=tokens.map(tokenRow).join('');root.classList.toggle('hidden',!tokens.length);empty.classList.toggle('hidden',tokens.length>0);bindTokenActions()}catch(error){empty.classList.remove('hidden');accessError(error.message)}finally{loading.classList.add('hidden')}}
-function bindClientActions(){document.querySelectorAll('[data-disconnect-client]').forEach(button=>button.onclick=async()=>{if(!confirm('Disconnect '+button.dataset.clientName+'? All of its tokens will stop working immediately.'))return;button.disabled=true;try{await request('/api/v1/access/authorized-clients/'+encodeURIComponent(button.dataset.disconnectClient),{method:'DELETE'});await loadClients()}catch(error){button.disabled=false;accessError(error.message)}})}
-function bindTokenActions(){document.querySelectorAll('[data-revoke-token]').forEach(button=>button.onclick=async()=>{if(!confirm('Revoke the access token “'+button.dataset.tokenName+'”? It will stop working immediately.'))return;button.disabled=true;try{await request('/api/v1/access-tokens/'+encodeURIComponent(button.dataset.revokeToken),{method:'DELETE'});await loadTokens()}catch(error){button.disabled=false;accessError(error.message)}})}
+async function loadClients(){const generation=mutationGeneration;const loading=$('#clients-loading'),root=$('#authorized-clients'),empty=$('#clients-empty');loading.classList.remove('hidden');try{const clients=await request('/api/v1/access/authorized-clients');if(generation!==mutationGeneration){reconcile(loadClients);return}root.innerHTML=clients.map(clientRow).join('');root.classList.toggle('hidden',!clients.length);empty.classList.toggle('hidden',clients.length>0);bindClientActions();applyPendingMutations()}catch(error){empty.classList.remove('hidden');accessError(error.message)}finally{loading.classList.add('hidden')}}
+async function loadTokens(){const generation=mutationGeneration;const loading=$('#tokens-loading'),root=$('#access-tokens'),empty=$('#tokens-empty');loading.classList.remove('hidden');try{const tokens=(await request('/api/v1/access-tokens')).filter(token=>!token.revoked_at);if(generation!==mutationGeneration){reconcile(loadTokens);return}root.innerHTML=tokens.map(tokenRow).join('');root.classList.toggle('hidden',!tokens.length);empty.classList.toggle('hidden',tokens.length>0);bindTokenActions();applyPendingMutations()}catch(error){empty.classList.remove('hidden');accessError(error.message)}finally{loading.classList.add('hidden')}}
+function bindClientActions(){document.querySelectorAll('[data-disconnect-client]').forEach(button=>button.onclick=async()=>{if(!confirm('Disconnect '+button.dataset.clientName+'? All of its tokens will stop working immediately.'))return;return mutate('[data-disconnect-client="'+button.dataset.disconnectClient+'"]','Disconnecting…',async()=>{try{await request('/api/v1/access/authorized-clients/'+encodeURIComponent(button.dataset.disconnectClient),{method:'DELETE'});button.closest('article')?.remove();reconcile(loadClients)}catch(error){accessError(error.message+(error.definitive?'':' Outcome unknown; checking server state.'));reconcile(loadClients)}})})}
+function bindTokenActions(){document.querySelectorAll('[data-revoke-token]').forEach(button=>button.onclick=async()=>{if(!confirm('Revoke the access token “'+button.dataset.tokenName+'”? It will stop working immediately.'))return;return mutate('[data-revoke-token="'+button.dataset.revokeToken+'"]','Revoking…',async()=>{try{await request('/api/v1/access-tokens/'+encodeURIComponent(button.dataset.revokeToken),{method:'DELETE'});button.closest('article')?.remove();reconcile(loadTokens)}catch(error){accessError(error.message+(error.definitive?'':' Outcome unknown; checking server state.'));reconcile(loadTokens)}})})}
const form=$('#token-form');$('#open-token-form').onclick=()=>{form.classList.remove('hidden');$('#open-token-form').classList.add('hidden');form.elements.name.focus()};$('#cancel-token-form').onclick=()=>{form.reset();form.classList.add('hidden');$('#open-token-form').classList.remove('hidden');$('#token-form-error').classList.add('hidden')};
document.querySelectorAll('[data-scope-preset]').forEach(button=>button.onclick=()=>{const read=button.dataset.scopePreset==='read';form.querySelectorAll('[name=scope]').forEach(input=>input.checked=!read||input.value.endsWith(':read'))});
-form.onsubmit=async event=>{event.preventDefault();const error=$('#token-form-error'),submit=form.querySelector('button[type="submit"]');error.classList.add('hidden');if(!submit){error.textContent='The create-token action is unavailable. Refresh and try again.';error.classList.remove('hidden');return}const selected=[...form.querySelectorAll('[name=scope]:checked')].map(input=>input.value);if(!selected.length){error.textContent='Select at least one scope.';error.classList.remove('hidden');return}submit.disabled=true;try{const result=await request('/api/v1/access-tokens',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({name:form.elements.name.value,expiryDays:Number(form.elements.expiryDays.value),scopes:selected})});$('#new-token-value').textContent=result.token;const reveal=$('#new-token');reveal.classList.remove('hidden');reveal.focus();form.reset();form.classList.add('hidden');$('#open-token-form').classList.remove('hidden');await loadTokens()}catch(x){error.textContent=x.message||'Could not create the access token. Try again.';error.classList.remove('hidden')}finally{submit.disabled=false}};
+form.onsubmit=async event=>{event.preventDefault();const error=$('#token-form-error'),submit=form.querySelector('button[type="submit"]');error.classList.add('hidden');if(!submit){error.textContent='The create-token action is unavailable. Refresh and try again.';error.classList.remove('hidden');return}const selected=[...form.querySelectorAll('[name=scope]:checked')].map(input=>input.value);if(!selected.length){error.textContent='Select at least one scope.';error.classList.remove('hidden');return}if(submit.disabled)return;submit.disabled=true;submit.textContent='Creating…';try{const result=await request('/api/v1/access-tokens',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({name:form.elements.name.value,expiryDays:Number(form.elements.expiryDays.value),scopes:selected})});$('#new-token-value').textContent=result.token;const reveal=$('#new-token');reveal.classList.remove('hidden');reveal.focus();form.reset();form.classList.add('hidden');$('#open-token-form').classList.remove('hidden');await loadTokens()}catch(x){error.textContent=(x.message||'Could not create the access token.')+(x.definitive?'':' Outcome unknown. Check the token list before creating another token.');error.classList.remove('hidden')}finally{submit.disabled=false;submit.textContent='Create token'}};
$('#copy-token').onclick=async()=>{const button=$('#copy-token');try{await navigator.clipboard.writeText($('#new-token-value').textContent);button.textContent='Copied'}catch{button.textContent='Select and copy the token'}setTimeout(()=>button.textContent='Copy',2000)};
Promise.all([loadClients(),loadTokens()]);`);
diff --git a/packages/app/test/api-keys.browser.test.ts b/packages/app/test/api-keys.browser.test.ts
index df9a3618..454d96ae 100644
--- a/packages/app/test/api-keys.browser.test.ts
+++ b/packages/app/test/api-keys.browser.test.ts
@@ -48,6 +48,8 @@ describe("rendered access token form", () => {
form.dispatchEvent(new SubmitEvent("submit", { bubbles: true, cancelable: true, submitter: submit }));
expect(submit.disabled).toBe(true);
+ expect(submit.textContent).toBe('Creating…');
+ form.dispatchEvent(new SubmitEvent('submit',{cancelable:true}));
expect(fetchMock.mock.calls.filter(([url, init]) => url === "/api/v1/access-tokens" && init?.method === "POST")).toHaveLength(1);
finishCreate(json({ token: "fact_once_only" }, 201));
@@ -82,3 +84,41 @@ describe("rendered access token form", () => {
expect(submit.disabled).toBe(false);
});
});
+
+it.each(["token","client"])("retains a pending %s and removes it only after confirmation, even if reconciliation fails", async kind=>{
+ let finish!: (response: Response)=>void,failRead=false;
+ vi.stubGlobal("confirm",()=>true);
+ const fetcher=vi.fn(async (input: unknown,init?: RequestInit)=>{
+ const url=String(input);
+ if(init?.method==="DELETE")return new Promise(resolve=>{finish=resolve});
+ if(failRead)return json({error:"Read unavailable"},503);
+ return json(url.includes("authorized-clients")?
+ [{clientId:"client-1",clientName:"Editor",scopes:[]}]:[{id:"token-1",name:"Deploy",scopes:[]}]);
+ });
+ renderPage(fetcher);await flush();
+ const button=document.querySelector(kind==="token"?"[data-revoke-token]":"[data-disconnect-client]");
+ const article=button.closest("article");
+ button.click();button.click();
+ expect(button.disabled).toBe(true);
+ expect(button.textContent).toBe(kind==="token"?"Revoking…":"Disconnecting…");
+ expect(article.isConnected).toBe(true);
+ expect(fetcher.mock.calls.filter(([,init])=>init?.method==="DELETE")).toHaveLength(1);
+ failRead=true;finish(json({deleted:true}));await flush();await flush();
+ expect(article.isConnected).toBe(false);
+ expect(document.querySelector("#access-error").textContent).toBe("Read unavailable");
+});
+
+it("keeps the server-created secret visible when list reconciliation fails",async()=>{
+ let created=false;
+ const fetcher=vi.fn(async(input: unknown,init?: RequestInit)=>{
+ if(init?.method==="POST"){created=true;return json({token:"fact_confirmed"})}
+ if(created)return json({error:"Read unavailable"},503);
+ return json([]);
+ });
+ const form=renderPage(fetcher);completeForm(form);
+ form.dispatchEvent(new SubmitEvent("submit",{cancelable:true}));
+ await flush();await flush();
+ expect(document.querySelector("#new-token-value").textContent).toBe("fact_confirmed");
+ expect(document.querySelector("#token-form-error").classList.contains("hidden")).toBe(true);
+ expect(document.querySelector("#access-error").textContent).toBe("Read unavailable");
+});
diff --git a/packages/app/test/page-refresh.browser.test.ts b/packages/app/test/page-refresh.browser.test.ts
index c0157650..698a8de0 100644
--- a/packages/app/test/page-refresh.browser.test.ts
+++ b/packages/app/test/page-refresh.browser.test.ts
@@ -58,7 +58,7 @@ describe("job split Run button", () => {
const posts = fetcher.mock.calls.filter(([, init]) => init?.method === 'POST');
expect(posts).toHaveLength(1);
expect(posts[0]).toEqual(['/api/v1/jobs/job-1/invocations', {
- method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}',
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: expect.any(String),
}]);
expect(document.querySelector('#run-options').disabled).toBe(true);
finish(json({ runId: 'created-run' })); await flush();
@@ -80,7 +80,7 @@ describe("job split Run button", () => {
document.querySelector('#manual-run-prompt').value = 'Review the release';
document.querySelector('#manual-run-form').dispatchEvent(new Event('submit', { cancelable: true }));
await flush();
- expect(JSON.parse(fetcher.mock.calls.find(([, init]) => init?.method === 'POST')![1].body)).toEqual({ prompt: 'Review the release' });
+ expect(JSON.parse(fetcher.mock.calls.find(([, init]) => init?.method === 'POST')![1].body)).toEqual({ prompt: 'Review the release', idempotencyKey: expect.any(String) });
});
it("supports keyboard opening, Escape focus restoration, and outside dismissal", async () => {
@@ -111,6 +111,138 @@ describe("job split Run button", () => {
});
});
+describe("mutation reconciliation", () => {
+ it("gives immediate feedback during a controlled 600ms response and navigates only on confirmation",async()=>{
+ const fetcher=vi.fn(async(url: string,init: any)=>{
+ if(init?.method)return new Promise(resolve=>setTimeout(()=>resolve(json({runId:'timed-run'})),600));
+ return json(url.startsWith('/api/v1/jobs/')?job:{items:[],nextCursor:null});
+ });
+ render(jobDetailPage(viewer,job.id),fetcher);await flush();
+ const start=Date.now();document.querySelector('#run').click();
+ expect(Date.now()-start).toBe(0);
+ expect(document.querySelector('#run').textContent).toBe('Starting…');
+ await vi.advanceTimersByTimeAsync(599);
+ expect(document.querySelector('#run').disabled).toBe(true);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(Date.now()-start).toBe(600);
+ expect(window.location.pathname).toBe('/job-runs/timed-run');
+ });
+ it("closes the prompt modal immediately and recovers the draft after rejection",async()=>{
+ let finish!: (response: Response)=>void;
+ const fetcher=vi.fn(async(url: string,init: any)=>{
+ if(init?.method)return new Promise(resolve=>{finish=resolve});
+ return json(url.startsWith('/api/v1/jobs/')?job:{items:[],nextCursor:null});
+ });
+ render(jobDetailPage(viewer,job.id),fetcher);await flush();
+ const dialog=document.querySelector('#manual-run-dialog');dialog.showModal=()=>{dialog.open=true};
+ document.querySelector('#run-options').click();document.querySelector('#run-with-prompt').click();
+ document.querySelector('#manual-run-prompt').value='Keep my input';
+ document.querySelector('#manual-run-form').dispatchEvent(new Event('submit',{cancelable:true}));
+ expect(dialog.open).toBe(false);
+ finish(json({error:'Queue full'},409));await flush();
+ document.querySelector('#run-options').click();document.querySelector('#run-with-prompt').click();
+ expect(document.querySelector('#manual-run-prompt').value).toBe('Keep my input');
+ expect(document.querySelector('#manual-run-error').textContent).toContain('Queue full');
+ });
+ it("keeps deletion pending through artifact cleanup and only navigates after confirmation",async()=>{
+ let finish!: (response: Response)=>void;vi.stubGlobal('confirm',()=>true);
+ const fetcher=vi.fn(async(url: string,init: any)=>{
+ if(init?.method)return new Promise(resolve=>{finish=resolve});
+ return json(url.startsWith('/api/v1/jobs/')?job:{items:[],nextCursor:null});
+ });
+ render(jobDetailPage(viewer,job.id),fetcher);await flush();
+ const before=window.location.pathname;
+ document.querySelector('#delete').click();document.querySelector('#delete').click();
+ expect(document.querySelector('#delete').textContent).toBe('Deleting…');
+ expect(window.location.pathname).toBe(before);
+ expect(fetcher.mock.calls.filter(([,init])=>init?.method)).toHaveLength(1);
+ finish(json({deleted:true}));await flush();
+ expect(window.location.pathname).toBe('/jobs');
+ });
+
+ it("retains Starting feedback across a changed poll and reuses the key after a lost response", async () => {
+ let count=0, finish!: (response: Response) => void;
+ const fetcher=vi.fn(async (url: string, init: any) => {
+ if(init?.method) return new Promise(resolve=>{finish=resolve});
+ return json(url.startsWith('/api/v1/jobs/')?{...job,runningCount:count}:{items:[],nextCursor:null});
+ });
+ render(jobDetailPage(viewer,job.id),fetcher);await flush();
+ document.querySelector('#run').click();
+ expect(document.querySelector('#run').textContent).toBe('Starting…');
+ expect(document.querySelector('[data-pending-run]').textContent).toContain('Awaiting acceptance');
+ const key=JSON.parse(fetcher.mock.calls.find(([,init])=>init?.method)![1].body).idempotencyKey;
+ count=1;await vi.advanceTimersByTimeAsync(10000);
+ expect(document.querySelector('#run').disabled).toBe(true);
+ expect(document.querySelector('#run').textContent).toBe('Starting…');
+ document.querySelector('#manual-run-form').dispatchEvent(new Event('submit',{cancelable:true}));
+ expect(fetcher.mock.calls.filter(([,init])=>init?.method)).toHaveLength(1);
+ finish(json({error:'Wake failed'},500));await flush();
+ expect(document.querySelector('#run-error').textContent).toContain('Outcome unknown');
+ document.querySelector('#run').click();
+ expect(JSON.parse(fetcher.mock.calls.filter(([,init])=>init?.method).at(-1)![1].body).idempotencyKey).toBe(key);
+ finish(json({runId:'recovered'}));await flush();
+ expect(window.location.pathname).toBe('/job-runs/recovered');
+ });
+
+ it.each([409,500])("reconciles an enable rejection (%s) without stale reads undoing the action",async status=>{
+ let serverEnabled=true,finishMutation!: (response: Response)=>void,finishRead!: (response: Response)=>void,hold=false;
+ const fetcher=vi.fn(async(url: string,init: any)=>{
+ if(init?.method)return new Promise(resolve=>{finishMutation=resolve});
+ if(url.startsWith('/api/v1/jobs/')){
+ if(hold){hold=false;return new Promise(resolve=>{finishRead=resolve})}
+ return json({...job,enabled:serverEnabled});
+ }
+ return json({items:[],nextCursor:null});
+ });
+ render(jobDetailPage(viewer,job.id),fetcher);await flush();
+ hold=true;await vi.advanceTimersByTimeAsync(10000);
+ document.querySelector('#toggle').click();
+ expect(document.querySelector('[data-enabled-badge]').textContent).toBe('Disabled');
+ expect(document.querySelector('#toggle').textContent).toBe('Disabling…');
+ serverEnabled=status===409;
+ finishMutation(json({error:'Rejected'},status));await flush();
+ expect(document.querySelector('[data-enabled-badge]').textContent).toBe(status===409?'Enabled':'Disabled');
+ finishRead(json(job));await flush();
+ expect(document.querySelector('[data-enabled-badge]').textContent).toBe(serverEnabled?'Enabled':'Disabled');
+ expect(fetcher.mock.calls.filter(([url,init])=>url.startsWith('/api/v1/jobs/')&&!init?.method).length).toBeGreaterThanOrEqual(3);
+ });
+
+ it("confirms enable directly from the mutation response before reconciliation",async()=>{
+ let finish!: (response: Response)=>void,hold=false;
+ const fetcher=vi.fn(async(url: string,init: any)=>{
+ if(init?.method)return new Promise(resolve=>{finish=resolve});
+ if(hold)return new Promise(()=>{});
+ return json(url.startsWith('/api/v1/jobs/')?job:{items:[],nextCursor:null});
+ });
+ render(jobDetailPage(viewer,job.id),fetcher);await flush();
+ document.querySelector('#toggle').click();hold=true;
+ finish(json({id:job.id,enabled:false}));await flush();
+ expect(document.querySelector('[data-enabled-badge]').textContent).toBe('Disabled');
+ expect(document.querySelector('#toggle').textContent).toBe('Enable');
+ });
+
+ it.each(['queued','starting','running','blocked','stopping','succeeded','failed','stopped'])("offers stop only for API-supported %s state",async state=>{
+ let finish!: (response: Response)=>void;
+ vi.stubGlobal('confirm',()=>true);
+ const fetcher=vi.fn(async(url: string,init: any)=>{
+ if(init?.method)return new Promise(resolve=>{finish=resolve});
+ if(url.includes('/trace?'))return json({items:[],nextCursor:null});
+ return json(url.startsWith('/api/v1/jobs/')?job:{...run,state});
+ });
+ render(jobRunPage(viewer,run.id),fetcher);await flush();
+ const button=document.querySelector('#kill-run');
+ expect(Boolean(button)).toBe(['starting','running','blocked'].includes(state));
+ if(button){
+ button.click();button.click();
+ expect(button.textContent).toBe('Stopping…');
+ expect(fetcher.mock.calls.filter(([,init])=>init?.method)).toHaveLength(1);
+ expect(document.querySelector('[data-run-state]').textContent).toBe(state);
+ finish(json({id:run.id,state:'stopping'}));await flush();
+ expect(document.querySelector('#run-detail h1')).not.toBeNull();
+ }
+ });
+});
+
describe("lifecycle page refresh", () => {
it("discovers jobs while idle, updates running counts, and preserves unchanged DOM", async () => {
let jobs: any[] = [];
@@ -136,18 +268,20 @@ describe("lifecycle page refresh", () => {
await vi.advanceTimersByTimeAsync(30000);
expect(fetcher).toHaveBeenCalledTimes(1);
resolve(json([job])); await flush();
+ expect(fetcher).toHaveBeenCalledTimes(2);
+ resolve(json([job])); await flush();
Object.defineProperty(document, 'hidden', { configurable: true, value: true });
document.dispatchEvent(new Event('visibilitychange'));
await vi.advanceTimersByTimeAsync(30000);
- expect(fetcher).toHaveBeenCalledTimes(1);
+ expect(fetcher).toHaveBeenCalledTimes(2);
Object.defineProperty(document, 'hidden', { configurable: true, value: false });
document.dispatchEvent(new Event('visibilitychange'));
- expect(fetcher).toHaveBeenCalledTimes(2);
+ expect(fetcher).toHaveBeenCalledTimes(3);
window.dispatchEvent(new Event('pagehide'));
resolve(json([job])); await flush(); await vi.advanceTimersByTimeAsync(30000);
- expect(fetcher).toHaveBeenCalledTimes(2);
- window.dispatchEvent(new Event('pageshow'));
expect(fetcher).toHaveBeenCalledTimes(3);
+ window.dispatchEvent(new Event('pageshow'));
+ expect(fetcher).toHaveBeenCalledTimes(4);
resolve(json([job])); await flush();
});
diff --git a/packages/app/test/settings-mutations.browser.test.ts b/packages/app/test/settings-mutations.browser.test.ts
new file mode 100644
index 00000000..18cca619
--- /dev/null
+++ b/packages/app/test/settings-mutations.browser.test.ts
@@ -0,0 +1,52 @@
+// @vitest-environment happy-dom
+import { afterEach, expect, it, vi } from "vitest";
+import { settingsPage } from "../src/ui";
+declare const document: any;
+const flush=async()=>{for(let i=0;i<60;i++)await Promise.resolve()};
+const json=(body: unknown)=>Response.json(body);
+afterEach(()=>{vi.unstubAllGlobals();document.body.innerHTML=""});
+it.each(["github","tail","exe"])("retains a %s connection while removal is pending and blocks repeated actions",async kind=>{
+ let finish!: (response: Response)=>void,removed=false;
+ vi.stubGlobal("confirm",()=>true);
+ const fetcher=vi.fn(async(input: unknown,init?: RequestInit)=>{
+ const url=String(input);
+ if(init?.method==="DELETE")return new Promise(resolve=>{finish=resolve});
+ if(url.includes("github/installations"))return json(removed&&kind==="github"?[]:[{installationId:1,state:"active",accountLogin:"owner"}]);
+ if(url.includes("cloudflare-tail"))return json(removed&&kind==="tail"?[]:[{integrationId:"tail-1",name:"Tail"}]);
+ return json({exeConnections:removed&&kind==="exe"?[]:[{connectionId:"exe-1",agentKind:"codex"}]});
+ });
+ vi.stubGlobal("fetch",fetcher);
+ const html=settingsPage({email:"owner@example.com"});
+ document.body.innerHTML=html.match(/]*>([\s\S]*?)<\/body>/)![1];
+ new Function([...html.matchAll(/