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
30 changes: 30 additions & 0 deletions docs/gen-2156-validation.md
Original file line number Diff line number Diff line change
@@ -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.
7 changes: 4 additions & 3 deletions packages/app/src/page-refresh.ts
Original file line number Diff line number Diff line change
@@ -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()};
Expand Down
84 changes: 56 additions & 28 deletions packages/app/src/ui.ts

Large diffs are not rendered by default.

40 changes: 40 additions & 0 deletions packages/app/test/api-keys.browser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down Expand Up @@ -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<Response>(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");
});
146 changes: 140 additions & 6 deletions packages/app/test/page-refresh.browser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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 () => {
Expand Down Expand Up @@ -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<Response>(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<Response>(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<Response>(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<Response>(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<Response>(resolve=>{finishMutation=resolve});
if(url.startsWith('/api/v1/jobs/')){
if(hold){hold=false;return new Promise<Response>(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<Response>(resolve=>{finish=resolve});
if(hold)return new Promise<Response>(()=>{});
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<Response>(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[] = [];
Expand All @@ -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();
});

Expand Down
Loading
Loading