rig-review 0.15.1 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/docs/DESIGN.md CHANGED
@@ -107,7 +107,7 @@ Published Play1.14.0 supplies a frozen `slotIdentity()` snapshot coherent with `
107
107
 
108
108
  Selecting the selected row again (click, Space or Enter) clears the selection, the same as **Whole rig**; the control value is then `null`.
109
109
 
110
- Each row shows a 24×24 CSS-pixel thumbnail (2× backing store) of the attachment the held identity snapshot says is active: the region the compiled model's `pages[].regions[]` declares under that attachment's path (or name), cut from the loaded page image by its page UVs. It is drawn when the row scrolls into view and cached per skin/attachment key. A row whose attachment has no such region (no active attachment, a non-image kind, no or several regions of that name, a rotated packing, a page that did not load) shows the type icon, and its tooltip names the reason. A whole atlas page is never a part's thumbnail. Row text and the slot count are unchanged; the compare page registers no thumbnail source and keeps its icons.
110
+ Each row shows a 24×24 CSS-pixel thumbnail (2× backing store) of the attachment the held identity snapshot says is active: the region the compiled model's `pages[].regions[]` declares under that attachment's path (or name), cut from the loaded page image by its page UVs. It is drawn when the row scrolls into view and cached per skin/attachment key. A row whose attachment has no such region (no active attachment, a non-image kind, no or several regions of that name, a rotated packing, a page that did not load) shows the type icon, and its tooltip names the reason. A whole atlas page is never a part's thumbnail. Row text and the slot count are unchanged; on the compare page each side registers its own thumbnail source from that side's compiled model and loaded page images. Both pages keep the Parts heading, search input, Whole rig button, Solo toggle and result count in a fixed tool area above a scrolling list of single-line ellipsized rows with uniform height, preserving full row text in `title` and `aria-label`.
111
111
 
112
112
  Live selection follows a slot. A source-bound bookmark captures its exact identity tuple at that pose; restore validates it after applying time/animation/set and drawing, with transactional rollback on a named mismatch. Old slot-only bookmarks resolve through current public identity. Generation belongs to current readback/feedback, not a stable source target. Named weights and original part alpha remain unavailable without an exact original-source mapping. A conservative bounds box and counts are not source-faithfulness or physics validation.
113
113
 
package/docs/WORKFLOWS.md CHANGED
@@ -160,10 +160,17 @@ rig-review strip /absolute/output --reference-video /absolute/original.mp4 --ani
160
160
  Only tool-owned instances with matching content, canonical input locations, tool
161
161
  fingerprint and a private capability handshake are reused. The URL hash is
162
162
  checked before serving the app; a stale link never selects another instance's
163
- package. Input hashes are freshly computed, not trusted from mtime caches. Idle
164
- open-managed workers stop after 30 minutes. Their private registry, requests and
165
- logs live beside feedback under `~/.local/state/rig-c-review/open/`; nothing is
166
- written into supplied folders. `RIG_REVIEW_STATE_DIR` selects another state root
163
+ package. Input hashes are freshly computed, not trusted from mtime caches. In both
164
+ `open` and foreground `review` / `review compare`, each open window holds a live
165
+ WebSocket connection (`/api/live`); once the last window closes and stays at zero connections
166
+ for the 3-second grace period, or if no window ever connects within 30 minutes
167
+ (reusing a windowless worker via `open` gives it a fresh 30-minute unopened window),
168
+ the server finishes any in-flight request or Apply, flushes state, prints one line
169
+ stating why it exited, and exits `0`. A browser that unloads a background tab to
170
+ save memory looks the same as a closed tab, so the server stops; saved feedback
171
+ survives and `open` brings it back. Their
172
+ private registry, requests and logs live beside feedback under
173
+ `~/.local/state/rig-c-review/open/`; nothing is written into supplied folders. `RIG_REVIEW_STATE_DIR` selects another state root
167
174
  outside all input packages, judged by its canonical location (symlinks in the path
168
175
  and its existing ancestors resolved). Existing foreground review commands still work.
169
176
 
@@ -216,7 +223,7 @@ request, and refuses an unknown, expired or replaced instance by name
216
223
  (`FRONT_INSTANCE_UNKNOWN`, `FRONT_INSTANCE_EXPIRED`, `FRONT_INSTANCE_REPLACED`).
217
224
  Worker error text is not passed through; failures become named `FRONT_*` codes.
218
225
  Package assets keep their `sandbox` CSP through the front. It never reads packages.
219
- Idle fronts exit after 30 minutes once no live instance remains.
226
+ Idle fronts exit after the 3-second grace period once no live instance remains.
220
227
 
221
228
  If another listener holds the front port, `open` fails with
222
229
  `FRONT_PORT_BUSY: 127.0.0.1:4318 is held by another listener; use --direct` and
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rig-review",
3
- "version": "0.15.1",
3
+ "version": "0.17.0",
4
4
  "type": "module",
5
5
  "description": "Local human rig inspection and structured feedback export",
6
6
  "license": "MIT",
@@ -89,7 +89,7 @@ export function createBonesCheck(p: ReviewPackage, options: { stateDir: string;
89
89
  await rm(dir, { recursive: true, force: true }).catch(() => {});
90
90
  }
91
91
  }
92
- return { run };
92
+ return { run, running: () => running };
93
93
  }
94
94
 
95
95
  /** `propose --from-config` on the scratch config, or the line naming the missing source painting. */
package/src/cli.ts CHANGED
@@ -112,7 +112,9 @@ export async function main(args:string[],options:{stateDir?:string}={}){
112
112
  const p=await loadCompare({a,b,reference,animation});
113
113
  if(command==='feedback'){printFeedback(await readFeedbackCompareSession(p,options.stateDir));return;}
114
114
  if(command==='check'){console.log(`Comparison valid: ${p.response.title}\nSource SHA-256: ${p.response.sourceHash}\nAnimation: ${animation}\nReference SHA-256: ${p.response.reference.sha256}\nPlayback: two compiled models present`);return;}
115
- const capability=randomBytes(32).toString('hex'),server=await startCompareServer(p,{port,stateDir:options.stateDir,capability});console.log(`Compare ready: http://127.0.0.1:${server.port}/#cap=${capability}\nComparison: ${p.response.title}\nSource SHA-256: ${p.response.sourceHash}\nPress Ctrl+C to stop.`);return;
115
+ const capability=randomBytes(32).toString('hex'),server=await startCompareServer(p,{port,stateDir:options.stateDir,capability,exitOnClose:true});
116
+ const stop=(sig:string)=>{server.stop(true);console.log(`review compare: exiting — received ${sig}.`);process.exit(0);};process.once('SIGINT',()=>stop('SIGINT'));process.once('SIGTERM',()=>stop('SIGTERM'));
117
+ console.log(`Compare ready: http://127.0.0.1:${server.port}/#cap=${capability}\nComparison: ${p.response.title}\nSource SHA-256: ${p.response.sourceHash}\nPress Ctrl+C to stop.`);return;
116
118
  }
117
119
  const input=args.shift();if(!input)throw new Error(usage);let port=4317;let checkpoint:string|undefined,reference:string|undefined,compare:string|undefined,animation:string|undefined;const handoff:OpenInputs={input};
118
120
  while(args.length){const flag=args.shift();const value=args.shift();if(!value)throw new Error(`Missing value for ${flag}`);if(handoffOption(flag!)){handoff[handoffOption(flag!)!]=value;continue;}if(flag==='--port'){port=Number(value);if(!Number.isInteger(port)||port<0||port>65535)throw new Error('--port: expected integer 0…65535');}else if(flag==='--checkpoint')checkpoint=value;else if(flag==='--reference')reference=value;else if(flag==='--compare')compare=value;else if(flag==='--animation')animation=value;else throw new Error(`Unknown option ${flag}\n${usage}`);}
@@ -123,7 +125,8 @@ export async function main(args:string[],options:{stateDir?:string}={}){
123
125
  const selection=animation!==undefined||fromReport?selectAnimation([{label:'single',catalog:p.feedbackCatalog,report:p.report}],animation,true):null;const initialAnimation=selection?.name;if(command==='feedback'){const saved=await readFeedbackSession(p,options.stateDir);await assertReviewUnchanged(p);printFeedback(saved);return;}if(command==='check'){console.log(`Package valid: ${p.manifest.title}\nRevision: ${p.manifest.revision}\nSource SHA-256: ${p.sourceHash}\nDeclared files: ${p.files.size}\nPlayback: ${p.manifest.model?'compiled model present':'unavailable (no model)'}`);return;}
124
126
  if(checkpoint&&!p.manifest.checkpoints.some(v=>v.id===checkpoint))throw new Error(`Unknown checkpoint ${checkpoint}`);
125
127
  // Foreground serving uses the same `#cap=` fragment handoff as open: the printed link alone can submit.
126
- const capability=randomBytes(32).toString('hex'),server=await startServer(p,{port,stateDir:options.stateDir,initialAnimation,capability});const url=new URL(`http://127.0.0.1:${server.port}/`);if(checkpoint)url.searchParams.set('checkpoint',checkpoint);url.hash='cap='+capability;
128
+ const capability=randomBytes(32).toString('hex'),server=await startServer(p,{port,stateDir:options.stateDir,initialAnimation,capability,exitOnClose:true});const url=new URL(`http://127.0.0.1:${server.port}/`);if(checkpoint)url.searchParams.set('checkpoint',checkpoint);url.hash='cap='+capability;
129
+ const stop=(sig:string)=>{server.stop(true);console.log(`review: exiting — received ${sig}.`);process.exit(0);};process.once('SIGINT',()=>stop('SIGINT'));process.once('SIGTERM',()=>stop('SIGTERM'));
127
130
  if(fromReport&&selection)console.error(animationDiagnostic(selection));
128
131
  console.log(`Review ready: ${url}\nPackage: ${p.manifest.title} (${p.manifest.revision})\nSource SHA-256: ${p.sourceHash}\nPress Ctrl+C to stop.`);
129
132
  }
@@ -1,5 +1,5 @@
1
1
  import {createControlServer,type ControlIdentity} from './control-server.ts';
2
- import {openGate,staleOpenStatus,accessGate,openNonceGate,stampOpen,type OpenIdentity} from './open-protocol.ts';
2
+ import {openGate,staleOpenStatus,accessGate,openNonceGate,openNonceHeader,sameSecret,stampOpen,type OpenIdentity} from './open-protocol.ts';
3
3
  import { readFile } from 'node:fs/promises';
4
4
  import { appRoot, buildWeb } from './build.ts';
5
5
  import { packagePath, safeFile } from './manifest.ts';
@@ -8,6 +8,7 @@ import { serveReference } from './reference.ts';
8
8
  import {referenceFrameIndex} from './reference-frame-index.ts';
9
9
  import { exportCompareStrip, stripJson } from './strip-export.ts';
10
10
  import { readCompareSession, saveCompareSession } from './compare-session.ts';
11
+ import { createLiveLifecycle, LIVE_PATH, type LiveExitInfo, type UpgradableServer } from './live-lifecycle.ts';
11
12
 
12
13
  const headers={'X-Content-Type-Options':'nosniff','Cache-Control':'no-store','Content-Security-Policy':"default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; media-src 'self'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'",'Referrer-Policy':'no-referrer'};
13
14
  const json=(value:unknown,status=200)=>Response.json(value,{status,headers});
@@ -29,16 +30,33 @@ function serveAsset(req:Request,path:string):Response{
29
30
  return new Response(req.method==='HEAD'?null:file,{headers:{...assetHeaders,'Content-Length':String(size)}});
30
31
  }
31
32
  /** `capability` (open workers and foreground CLI serving) gates every non-GET request; tests may omit it. */
32
- export async function startCompareServer(p:ComparePackage,options:{port?:number;stateDir?:string;open?:OpenIdentity;activity?:()=>void;control?:ControlIdentity;capability?:string}={}){
33
+ export async function startCompareServer(p:ComparePackage,options:{port?:number;stateDir?:string;open?:OpenIdentity;activity?:()=>void;control?:ControlIdentity;capability?:string;graceMs?:number;unopenedTimeoutMs?:number;exitOnClose?:boolean;onClose?:(info:LiveExitInfo)=>void|Promise<void>;log?:(line:string)=>void}={}){
33
34
  const bundle=await buildWeb('compare');
34
35
  const frames=referenceFrameIndex(p.referencePath,p.response.binding.reference.sha256,p.response.sourceHash);
35
36
  const control=options.control?createControlServer({identity:options.control,sourceHash:p.response.sourceHash,mode:'compare',unchanged:()=>assertCompareUnchanged(p),activity:options.activity}):null;
36
- const handle=async(req:Request,port:number|undefined):Promise<Response>=>{try{
37
+ let rawStop:((closeActiveConnections?:boolean)=>void)|null=null;
38
+ const live=createLiveLifecycle({
39
+ label:'review compare',
40
+ graceMs:options.graceMs,
41
+ unopenedTimeoutMs:options.unopenedTimeoutMs,
42
+ exitOnClose:options.exitOnClose,
43
+ onClose:options.onClose,
44
+ log:options.log,
45
+ stopServer:()=>{rawStop?.(true);},
46
+ });
47
+ const handle=async(req:Request,port:number|undefined,srv:UpgradableServer):Promise<Response|undefined>=>{try{
37
48
  const url=new URL(req.url),origin=`http://127.0.0.1:${port}`;
38
49
  if(url.origin!==origin)return json({error:'Loopback host required'},403);
39
50
  const refused=openNonceGate(req,options.open)??accessGate(req,options.capability,!!control);if(refused)return refused;
51
+ if(req.method==='GET'&&url.pathname===LIVE_PATH){
52
+ const fromFront=Boolean(options.open&&sameSecret(req.headers.get(openNonceHeader),options.open.nonce)&&req.headers.get('origin')===null);
53
+ if(!fromFront&&req.headers.get('origin')!==origin)return json({error:'Same-origin Origin required'},403);
54
+ options.activity?.();return live.upgrade(req,srv,headers,options.open?.key);
55
+ }
56
+ live.onRequestStart(url.pathname);
57
+ try {
40
58
  const controlled=await control?.(req,origin);if(controlled)return controlled;
41
- options.activity?.();const gate=openGate(req,options.open);if(gate){if(gate.status===200){try{await assertCompareUnchanged(p);}catch{return staleOpenStatus(options.open!);}}return gate;}
59
+ options.activity?.();const gate=openGate(req,options.open);if(gate){if(gate.status===200){try{await assertCompareUnchanged(p);}catch{return staleOpenStatus(options.open!);}if(!live.rearmUnopened())return json({error:'Server is closing'},503);}return gate;}
42
60
  if(req.method==='PUT'&&url.pathname==='/api/compare/session'){
43
61
  if(req.headers.get('origin')!==origin)return json({error:'Same-origin Origin required'},403);
44
62
  return json(await saveCompareSession(p,await bodyJson(req),options.stateDir));
@@ -58,6 +76,10 @@ export async function startCompareServer(p:ComparePackage,options:{port?:number;
58
76
  if(url.pathname==='/'||url.pathname==='/index.html')return new Response(req.method==='HEAD'?null:await readFile(appRoot+'web/compare.html'),{headers:{...headers,'Content-Type':'text/html; charset=utf-8'}});
59
77
  if(url.pathname==='/styles.css')return new Response(req.method==='HEAD'?null:await readFile(appRoot+'web/compare.css'),{headers:{...headers,'Content-Type':'text/css'}});
60
78
  return json({error:'Not found'},404);
79
+ } finally { live.onRequestEnd(url.pathname); }
61
80
  }catch(e){const message=e instanceof Error?e.message:'Request failed';return json({error:message},message.includes('inputs changed')?409:400);}};
62
- return Bun.serve({hostname:'127.0.0.1',port:options.port??4317,async fetch(req,server){return stampOpen(req,await handle(req,server.port),options.open);}});
81
+ const server=Bun.serve({hostname:'127.0.0.1',port:options.port??4317,websocket:live.websocket,async fetch(req,srv){const res=await handle(req,srv.port,srv);if(!res)return undefined as unknown as Response;return stampOpen(req,res,options.open);}});
82
+ rawStop=server.stop.bind(server);
83
+ server.stop=((closeActiveConnections?:boolean)=>{live.stop();return rawStop!(closeActiveConnections);}) as typeof server.stop;
84
+ return Object.assign(server,{live});
63
85
  }
package/src/front.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  /** Managed loopback front: one stable origin (127.0.0.1:4318 by default) routing `/instances/<key>/…` to the
2
2
  * worker named by that key's private open record. It is a router, not an authority: it never reads packages,
3
3
  * never serves or logs a capability, and forwards a mutation (rewriting Origin) only with the page capability. */
4
+ import type {ServerWebSocket} from 'bun';
4
5
  import {randomUUID} from 'node:crypto';
5
6
  import {spawn} from 'node:child_process';
6
7
  import {lstat,readFile,readdir,realpath,rename,unlink,writeFile,open as openFile} from 'node:fs/promises';
@@ -8,6 +9,7 @@ import {dirname,join} from 'node:path';
8
9
  import {fileURLToPath} from 'node:url';
9
10
  import {acquireClaim,alive,openFingerprint,readRecord,releaseClaim,running,smallJson,type RecordFile} from './open.ts';
10
11
  import {capabilityHeader,openKeyHeader,openNonceHeader,sameSecret} from './open-protocol.ts';
12
+ import {DEFAULT_CLOSE_GRACE_MS,LIVE_PATH} from './live-lifecycle.ts';
11
13
  export const defaultFrontPort=4318; // Foreground `review <dir>` keeps 4317.
12
14
  interface FrontRecord {schema:'rig-review-front/1';origin:string;port:number;nonce:string;fingerprint:string;pid:number}
13
15
  interface FrontRequest {schema:'rig-review-front-request/1';control:string;request:string;record:string;port:number;nonce:string;fingerprint:string;idleMs:number}
@@ -24,7 +26,7 @@ async function frontAlive(row:FrontRecord):Promise<boolean>{try{const response=a
24
26
  /** Ensure this state directory's front on `port`; reuse a verified live one. A front from another tool
25
27
  * build is ours (verified nonce) and is replaced. Any other listener is FRONT_PORT_BUSY, never a fallback. */
26
28
  export async function ensureFront(options:{control:string;port:number;fingerprint:string;idleMs?:number}):Promise<string>{
27
- const {control,port,fingerprint}=options,name=frontName(port),recordPath=join(control,name+'.json'),nonce=randomUUID(),deadline=performance.now()+20000,idleMs=options.idleMs??30*60*1000;
29
+ const {control,port,fingerprint}=options,name=frontName(port),recordPath=join(control,name+'.json'),nonce=randomUUID(),deadline=performance.now()+20000,idleMs=options.idleMs??DEFAULT_CLOSE_GRACE_MS;
28
30
  const reuse=async()=>{const row=await readFront(recordPath,port);if(!row||!await frontAlive(row))return null;if(row.fingerprint===fingerprint)return row;
29
31
  try{process.kill(row.pid,'SIGTERM');}catch{}for(let n=0;n<100&&await frontAlive(row);n++)await sleep(30);return null;};
30
32
  const ready=await reuse();if(ready)return ready.origin;
@@ -42,10 +44,11 @@ export async function ensureFront(options:{control:string;port:number;fingerprin
42
44
  throw new Error(`FRONT_TIMEOUT: front did not become ready; log ${log}`);
43
45
  }finally{if(child&&!handedOff&&child.exitCode===null&&child.signalCode===null)child.kill('SIGTERM');await releaseClaim(join(control,name+'.claim'),nonce);if(request)await unlink(request).catch(e=>{if(e.code!=='ENOENT')throw e;});}
44
46
  }
45
- interface Route {mutation:boolean;limit:number;timeoutMs:number;control:boolean}
47
+ interface Route {mutation:boolean;limit:number;timeoutMs:number;control:boolean;live?:boolean}
46
48
  /** Closed allowlist per method. Agent control endpoints, open-status and anything unlisted are refused. */
47
49
  export function frontRoute(mode:'single'|'compare',method:string,path:string):Route|null{
48
50
  const read=method==='GET'||method==='HEAD',get:Route={mutation:false,limit:0,timeoutMs:30000,control:false};
51
+ if(path===LIVE_PATH)return method==='GET'?{...get,live:true}:null;
49
52
  if(['/','/index.html','/main.js','/styles.css','/api/access'].includes(path))return read?get:null;
50
53
  if(path==='/api/control/config')return method==='GET'?{...get,control:true}:null;
51
54
  if(['/api/control/register','/api/control/poll','/api/control/ack','/api/control/close'].includes(path))return method==='POST'?{mutation:true,limit:16384,timeoutMs:10000,control:true}:null;
@@ -91,9 +94,15 @@ async function instanceRecord(control:string,key:string):Promise<RecordFile|null
91
94
  const upstreamFailure:Record<number,string>={400:'FRONT_UPSTREAM_REJECTED',403:'FRONT_UPSTREAM_FORBIDDEN',404:'FRONT_UPSTREAM_NOT_FOUND',405:'FRONT_UPSTREAM_METHOD',409:'FRONT_UPSTREAM_CONFLICT'};
92
95
  const responseHeaders=['content-type','content-length','content-range','accept-ranges','content-disposition','cache-control','content-security-policy','x-content-type-options','referrer-policy'];
93
96
  export const maximumUpstreamStreams=32;
97
+ interface FrontLiveRelay {upstream:WebSocket;client:ServerWebSocket<FrontLiveRelay>|null}
94
98
  export function startFront(options:{control:string;port:number;nonce:string;fingerprint:string}){
95
99
  const origin=`http://127.0.0.1:${options.port}`;let active=0,last=performance.now();
96
- const server=Bun.serve({hostname:'127.0.0.1',port:options.port,async fetch(req){
100
+ const server=Bun.serve<FrontLiveRelay>({hostname:'127.0.0.1',port:options.port,websocket:{
101
+ idleTimeout:0,
102
+ open(ws){last=performance.now();ws.data.client=ws;if(ws.data.upstream.readyState!==WebSocket.OPEN){try{ws.close();}catch{}return;}try{ws.send('live');}catch{}},
103
+ message(ws,msg){last=performance.now();try{ws.data.upstream.send(msg);}catch{}},
104
+ close(ws){last=performance.now();try{ws.data.upstream.close();}catch{}},
105
+ },async fetch(req,srv){
97
106
  last=performance.now();
98
107
  try{
99
108
  const url=new URL(req.url);if(url.origin!==origin)return refuse('FRONT_LOOPBACK_REQUIRED',403);
@@ -104,6 +113,33 @@ export function startFront(options:{control:string;port:number;nonce:string;fing
104
113
  const record=await instanceRecord(options.control,key);if(!record)return refuse('FRONT_INSTANCE_UNKNOWN: reopen with rig-review open',404);
105
114
  const route=frontRoute(record.mode,req.method,path);if(!route)return refuse('FRONT_ROUTE_REFUSED',404);
106
115
  const landing=path==='/'||path==='/index.html';if(!landing&&url.search)return refuse('FRONT_QUERY_REFUSED',400);
116
+ if(route.live){
117
+ if(sentOrigin!==origin)return refuse('FRONT_SAME_ORIGIN_REQUIRED',403);
118
+ if(req.headers.get('upgrade')?.toLowerCase()!=='websocket')return refuse('FRONT_UPGRADE_REQUIRED',426);
119
+ const upstreamWs=new WebSocket(record.origin.replace(/^http/,'ws')+path,{headers:{[openNonceHeader]:record.nonce}} as unknown as string[]);
120
+ const outcome=await new Promise<'ok'|'replaced'|'timeout'|'closed'>(resolve=>{
121
+ const timer=setTimeout(()=>resolve('timeout'),route.timeoutMs);
122
+ const finish=(result:'ok'|'replaced'|'timeout'|'closed')=>{clearTimeout(timer);resolve(result);};
123
+ req.signal.addEventListener('abort',()=>finish('closed'),{once:true});
124
+ upstreamWs.onmessage=ev=>{try{const msg=JSON.parse(String(ev.data)) as {type?:string;key?:string};finish(msg?.type==='live'&&msg?.key===key?'ok':'replaced');}catch{finish('replaced');}};
125
+ upstreamWs.onerror=()=>finish('closed');
126
+ upstreamWs.onclose=()=>finish('closed');
127
+ });
128
+ if(outcome!=='ok'){
129
+ try{upstreamWs.close();}catch{}
130
+ if(outcome==='timeout'&&!req.signal.aborted)return refuse('FRONT_UPSTREAM_TIMEOUT',504);
131
+ if(outcome==='replaced')return refuse('FRONT_INSTANCE_REPLACED: reopen with rig-review open',410);
132
+ const probe=await fetch(record.origin+'/api/access',{headers:{[openNonceHeader]:record.nonce},redirect:'manual',signal:AbortSignal.timeout(1500)}).catch(()=>null);
133
+ void probe?.body?.cancel().catch(()=>{});
134
+ return probe?refuse('FRONT_INSTANCE_REPLACED: reopen with rig-review open',410):refuse('FRONT_INSTANCE_EXPIRED: reopen with rig-review open',410);
135
+ }
136
+ const relay:FrontLiveRelay={upstream:upstreamWs,client:null};
137
+ upstreamWs.onmessage=ev=>{try{relay.client?.send(String(ev.data));}catch{}};
138
+ upstreamWs.onerror=()=>{try{relay.client?.close();}catch{}};
139
+ upstreamWs.onclose=()=>{try{relay.client?.close();}catch{}};
140
+ if(!srv.upgrade(req,{data:relay,headers:noStore})){try{upstreamWs.close();}catch{}return refuse('FRONT_UPGRADE_FAILED',400);}
141
+ return undefined as unknown as Response;
142
+ }
107
143
  let body:ArrayBuffer|undefined;
108
144
  if(route.mutation){
109
145
  // Never rewrite Origin without this instance's capability; the worker compares it again itself.
@@ -124,7 +160,7 @@ export function startFront(options:{control:string;port:number;nonce:string;fing
124
160
  if(upstream.status>=400&&upstream.status!==416){void upstream.body?.cancel().catch(()=>{});release();const code=upstreamFailure[upstream.status];return refuse(code??'FRONT_UPSTREAM_FAILED',code?upstream.status:502);}
125
161
  const out=new Headers();for(const name of responseHeaders){const value=upstream.headers.get(name);if(value!==null)out.set(name,value);}
126
162
  if(!upstream.body||req.method==='HEAD'){void upstream.body?.cancel().catch(()=>{});release();return new Response(null,{status:upstream.status,headers:out});}
127
- clearTimeout(timer);const reader=upstream.body.getReader();
163
+ if(timer)clearTimeout(timer);const reader=upstream.body.getReader();
128
164
  // Media/model streams stay counted until finished or cancelled by the browser.
129
165
  const stream=new ReadableStream<Uint8Array>({async pull(controller){try{const next=await reader.read();if(next.done){controller.close();release();}else controller.enqueue(next.value);}catch(error){release();controller.error(error);}},cancel(reason){release();abort.abort();return reader.cancel(reason).catch(()=>{});}});
130
166
  return new Response(stream,{status:upstream.status,headers:out});
@@ -132,7 +168,7 @@ export function startFront(options:{control:string;port:number;nonce:string;fing
132
168
  }});
133
169
  return {origin,stop:()=>server.stop(true),idleMs:()=>performance.now()-last,active:()=>active};
134
170
  }
135
- async function liveInstances(control:string):Promise<boolean>{for(const name of await readdir(control))if(/^[a-f0-9]{64}\.json$/.test(name)){const row=await readRecord(join(control,name),name.slice(0,64)).catch(()=>null);if(row&&running(row.pid))return true;}return false;}
171
+ async function liveInstances(control:string):Promise<boolean>{for(const name of await readdir(control)){if(/^[a-f0-9]{64}\.claim$/.test(name))return true;if(/^[a-f0-9]{64}\.json$/.test(name)){const row=await readRecord(join(control,name),name.slice(0,64)).catch(()=>null);if(row&&running(row.pid))return true;}}return false;}
136
172
  export async function runFront(requestPath:string):Promise<void>{
137
173
  const spec=await smallJson(requestPath) as FrontRequest;if(spec?.schema!=='rig-review-front-request/1'||!uuid.test(spec.nonce??'')||!hex64.test(spec.fingerprint??'')||!Number.isSafeInteger(spec.port)||spec.port<1||spec.port>65535||!Number.isSafeInteger(spec.idleMs)||spec.idleMs<100)throw new Error('front: invalid request');
138
174
  const control=await realpath(spec.control);if(dirname(await realpath(requestPath))!==control||spec.request!==requestPath||spec.record!==join(control,frontName(spec.port)+'.json'))throw new Error('front: invalid state locations');
@@ -141,8 +177,8 @@ export async function runFront(requestPath:string):Promise<void>{
141
177
  try{front=startFront({control,port:spec.port,nonce:spec.nonce,fingerprint:spec.fingerprint});}catch(error){if((error as NodeJS.ErrnoException).code==='EADDRINUSE'||/in use/i.test(error instanceof Error?error.message:''))throw new Error(`FRONT_PORT_BUSY: 127.0.0.1:${spec.port}`);throw error;}
142
178
  const record:FrontRecord={schema:'rig-review-front/1',origin:front.origin,port:spec.port,nonce:spec.nonce,fingerprint:spec.fingerprint,pid:process.pid},tmp=spec.record+'.'+spec.nonce+'.tmp';await writeFile(tmp,JSON.stringify(record),{mode:0o600,flag:'wx'});await rename(tmp,spec.record);
143
179
  await unlink(requestPath).catch(e=>{if(e.code!=='ENOENT')throw e;});
144
- let stopped=false;const stop=async()=>{if(stopped)return;stopped=true;clearInterval(timer);front.stop();const current=await readFront(spec.record,spec.port).catch(()=>null);if(current?.nonce===spec.nonce)await unlink(spec.record).catch(()=>{});process.exit(0);};
180
+ let stopped=false;const stop=async(reason:string)=>{if(stopped)return;stopped=true;clearInterval(timer);front.stop();const current=await readFront(spec.record,spec.port).catch(()=>null);if(current?.nonce===spec.nonce)await unlink(spec.record).catch(()=>{});console.log(`review front: exiting — ${reason}.`);process.exit(0);};
145
181
  // Idle exit only once no request arrived for idleMs and no live worker record remains.
146
- const timer=setInterval(()=>{if(front.idleMs()>=spec.idleMs&&front.active()===0)void liveInstances(control).then(live=>{if(!live)void stop();}).catch(()=>{});},Math.min(1000,spec.idleMs));
147
- process.on('SIGTERM',()=>{void stop();});process.on('SIGINT',()=>{void stop();});
182
+ const timer=setInterval(()=>{if(front.idleMs()>=spec.idleMs&&front.active()===0)void liveInstances(control).then(live=>{if(!live)void stop(`no live review instances remain (idle for ${spec.idleMs}ms)`)}).catch(()=>{});},Math.min(250,spec.idleMs));
183
+ process.on('SIGTERM',()=>{void stop('received SIGTERM');});process.on('SIGINT',()=>{void stop('received SIGINT');});
148
184
  }
@@ -0,0 +1,351 @@
1
+ /**
2
+ * Live review window WebSocket connection tracking and idle/close server lifecycle (#236).
3
+ *
4
+ * Each open review or compare page holds one WebSocket (`GET /api/live`) connection open.
5
+ * - Why WebSocket: all managed `open` instances share the front origin (`127.0.0.1:4318`). Browsers cap HTTP/1.1
6
+ * connections at six per host, so holding one HTTP stream per tab starves requests at six windows. WebSockets sit
7
+ * outside the six-connection HTTP/1.1 pool and notify `onclose` immediately on drop so the client can reconnect
8
+ * within a couple hundred milliseconds rather than waiting on browser stream retry timers.
9
+ * - Reload vs. close: closing a tab or killing the browser (`SIGKILL`) tears down the TCP socket immediately without
10
+ * needing `pagehide` or `sendBeacon`. A reload tears down the old socket and immediately issues document/API requests
11
+ * followed by a new `/api/live` WebSocket well within `DEFAULT_CLOSE_GRACE_MS` (measured 40-slot + video reload p50
12
+ * 127.3ms, max 148.9ms; dual 40-slot compare p50 83.6ms, max 106.0ms -> 3,000ms grace gives >20x headroom, and
13
+ * incoming requests during the grace window reset the zero-connection clock).
14
+ * - Second tab: each tab holds its own `/api/live` WebSocket (`connections === 2`); closing one leaves `connections === 1`.
15
+ * - Quiet socket & machine sleep / background tab freeze: `idleTimeout` is disabled (`0`) and periodic server keepalive
16
+ * frames keep quiet sockets open; liveness is bound to the kernel loopback TCP socket rather than client JS timer
17
+ * heartbeats, and wall-clock sleep jumps reset any pending countdown on wake.
18
+ * - Unopened server: if no page ever connects within `DEFAULT_UNOPENED_TIMEOUT_MS` (30 minutes, 1,800,000ms), or after
19
+ * an `open` reuse re-arms a windowless worker, the server exits 0.
20
+ * - In-flight work: an active HTTP request or producer Apply/rebuild delays exit until it finishes, then re-checks the
21
+ * live connection count before flushing state, stopping the listener, printing one reason line, and exiting 0.
22
+ */
23
+ import type { ServerWebSocket, WebSocketHandler } from 'bun';
24
+
25
+ export const LIVE_PATH = '/api/live';
26
+
27
+ /**
28
+ * Measured heavy-package full browser reload (40-slot + multi-PNG + 313 frames + video reference):
29
+ * single review p50 127.34ms / max 148.90ms; dual 40-slot compare p50 83.60ms / max 106.01ms.
30
+ * 3,000ms provides >20x headroom over the heaviest reload while closing promptly after the last window shuts.
31
+ */
32
+ export const DEFAULT_CLOSE_GRACE_MS = 3_000;
33
+
34
+ /**
35
+ * Time a server that has not received a `/api/live` page connection waits before exiting (30 minutes).
36
+ * Preserves links handed from `rig-review open` or foreground servers to a human who opens them minutes later,
37
+ * while reaping unopened servers before the 45-minute stale threshold.
38
+ */
39
+ export const DEFAULT_UNOPENED_TIMEOUT_MS = 30 * 60 * 1_000;
40
+
41
+ /** Wall-clock jump beyond the check interval that indicates machine sleep / process pause. */
42
+ const SLEEP_JUMP_THRESHOLD_MS = 2_000;
43
+ const KEEPALIVE_INTERVAL_MS = 5_000;
44
+
45
+ export type LiveExitReason = 'last-window-closed' | 'unopened-timeout';
46
+
47
+ export interface LiveExitInfo {
48
+ reason: LiveExitReason;
49
+ line: string;
50
+ }
51
+
52
+ export interface LiveSocketData {
53
+ key?: string;
54
+ release?: () => void;
55
+ }
56
+
57
+ export interface UpgradableServer {
58
+ upgrade(req: Request, options: { data: LiveSocketData; headers?: HeadersInit }): boolean;
59
+ }
60
+
61
+ export interface LiveLifecycleOptions {
62
+ label?: string;
63
+ graceMs?: number;
64
+ unopenedTimeoutMs?: number;
65
+ busy?: () => boolean;
66
+ flush?: () => void | Promise<void>;
67
+ stopServer?: () => void | Promise<void>;
68
+ onClose?: (info: LiveExitInfo) => void | Promise<void>;
69
+ exitOnClose?: boolean;
70
+ log?: (line: string) => void;
71
+ now?: () => number;
72
+ }
73
+
74
+ export interface LiveLifecycle {
75
+ upgrade(req: Request, srv: UpgradableServer, baseHeaders: Record<string, string>, key?: string): Response | undefined;
76
+ readonly websocket: WebSocketHandler<LiveSocketData>;
77
+ attachSocket(): { close(): void };
78
+ dropSockets(): number;
79
+ onRequestStart(pathname: string): void;
80
+ onRequestEnd(pathname: string): void;
81
+ rearmUnopened(): boolean;
82
+ stop(): void;
83
+ readonly connections: number;
84
+ readonly everConnected: boolean;
85
+ readonly exited: Promise<LiveExitInfo | null>;
86
+ }
87
+
88
+ function isIgnoredActivityPath(pathname: string): boolean {
89
+ return pathname === LIVE_PATH;
90
+ }
91
+
92
+ export function formatExitLine(label: string, reason: LiveExitReason, graceMs: number, unopenedTimeoutMs: number): string {
93
+ if (reason === 'last-window-closed') {
94
+ return `${label}: exiting — last review window closed (0 live connections for ${graceMs}ms).`;
95
+ }
96
+ return `${label}: exiting — no review window connected within ${unopenedTimeoutMs}ms.`;
97
+ }
98
+
99
+ export function createLiveLifecycle(options: LiveLifecycleOptions = {}): LiveLifecycle {
100
+ const label = options.label ?? 'review';
101
+ const graceMs = Math.max(10, options.graceMs ?? DEFAULT_CLOSE_GRACE_MS);
102
+ const unopenedTimeoutMs = Math.max(10, options.unopenedTimeoutMs ?? DEFAULT_UNOPENED_TIMEOUT_MS);
103
+ const now = options.now ?? (() => Date.now());
104
+ const log = options.log ?? ((line: string) => console.log(line));
105
+
106
+ let connections = 0;
107
+ let everConnected = false;
108
+ let inFlightRequests = 0;
109
+ let startedAt = now();
110
+ let zeroSince: number | null = null;
111
+ let stopped = false;
112
+ let closing = false;
113
+ let waitingForInFlight = false;
114
+ const activeSockets = new Set<ServerWebSocket<LiveSocketData>>();
115
+
116
+ let resolveExited!: (info: LiveExitInfo | null) => void;
117
+ const exited = new Promise<LiveExitInfo | null>(resolve => {
118
+ resolveExited = resolve;
119
+ });
120
+
121
+ const checkIntervalMs = Math.min(50, Math.max(10, Math.floor(Math.min(graceMs, unopenedTimeoutMs) / 4)));
122
+ let lastTickAt = now();
123
+
124
+ function isBusy(): boolean {
125
+ return inFlightRequests > 0 || Boolean(options.busy?.());
126
+ }
127
+
128
+ async function triggerExit(reason: LiveExitReason): Promise<void> {
129
+ if (stopped || closing) return;
130
+ closing = true;
131
+ const line = formatExitLine(label, reason, graceMs, unopenedTimeoutMs);
132
+ const info: LiveExitInfo = { reason, line };
133
+ try {
134
+ await options.flush?.();
135
+ } catch { /* best-effort state flush */ }
136
+ // Re-check connection count if a page connected or new work arrived while flushing.
137
+ if (connections > 0 || isBusy()) {
138
+ closing = false;
139
+ if (connections > 0) zeroSince = null;
140
+ return;
141
+ }
142
+ clearInterval(timer);
143
+ clearInterval(keepaliveTimer);
144
+ try {
145
+ await options.onClose?.(info);
146
+ } catch { /* best-effort close hook */ }
147
+ try {
148
+ await options.stopServer?.();
149
+ } catch { /* best-effort server stop */ }
150
+ stopped = true;
151
+ log(line);
152
+ resolveExited(info);
153
+ if (options.exitOnClose) {
154
+ process.exit(0);
155
+ }
156
+ }
157
+
158
+ function check(): void {
159
+ if (stopped || closing) return;
160
+ if (connections > 0) {
161
+ zeroSince = null;
162
+ waitingForInFlight = false;
163
+ return;
164
+ }
165
+ const current = now();
166
+ let reason: LiveExitReason | null = null;
167
+ if (everConnected) {
168
+ if (zeroSince === null) zeroSince = current;
169
+ if (current - zeroSince >= graceMs) reason = 'last-window-closed';
170
+ } else {
171
+ if (current - startedAt >= unopenedTimeoutMs) reason = 'unopened-timeout';
172
+ }
173
+ if (!reason) return;
174
+ if (isBusy()) {
175
+ waitingForInFlight = true;
176
+ return;
177
+ }
178
+ if (waitingForInFlight) {
179
+ waitingForInFlight = false;
180
+ // Re-check connection count right after in-flight work completes.
181
+ if (connections > 0) {
182
+ zeroSince = null;
183
+ return;
184
+ }
185
+ }
186
+ void triggerExit(reason);
187
+ }
188
+
189
+ const timer = setInterval(() => {
190
+ if (stopped || closing) return;
191
+ const current = now();
192
+ const delta = current - lastTickAt;
193
+ lastTickAt = current;
194
+ if (delta > checkIntervalMs + SLEEP_JUMP_THRESHOLD_MS) {
195
+ if (zeroSince !== null) zeroSince = current;
196
+ if (!everConnected) startedAt = current;
197
+ return;
198
+ }
199
+ check();
200
+ }, checkIntervalMs);
201
+ timer.unref?.();
202
+
203
+ const keepaliveTimer = setInterval(() => {
204
+ if (stopped || closing || activeSockets.size === 0) return;
205
+ for (const ws of [...activeSockets]) {
206
+ try {
207
+ ws.send('keepalive');
208
+ ws.ping?.();
209
+ } catch {
210
+ ws.data?.release?.();
211
+ }
212
+ }
213
+ }, KEEPALIVE_INTERVAL_MS);
214
+ keepaliveTimer.unref?.();
215
+
216
+ function attachSocket(): { close(): void } {
217
+ connections += 1;
218
+ everConnected = true;
219
+ zeroSince = null;
220
+ waitingForInFlight = false;
221
+ let released = false;
222
+ return {
223
+ close() {
224
+ if (released) return;
225
+ released = true;
226
+ connections = Math.max(0, connections - 1);
227
+ if (connections === 0 && !stopped && !closing) {
228
+ zeroSince = now();
229
+ check();
230
+ }
231
+ },
232
+ };
233
+ }
234
+
235
+ function upgrade(req: Request, srv: UpgradableServer, baseHeaders: Record<string, string>, key?: string): Response | undefined {
236
+ if (stopped || closing) {
237
+ return new Response('Server is closing', { status: 503, headers: baseHeaders });
238
+ }
239
+ if (req.headers.get('upgrade')?.toLowerCase() !== 'websocket') {
240
+ return new Response('WebSocket upgrade required', { status: 426, headers: baseHeaders });
241
+ }
242
+ const upgraded = srv.upgrade(req, {
243
+ data: { key },
244
+ headers: baseHeaders,
245
+ });
246
+ if (upgraded) return undefined;
247
+ return new Response('WebSocket upgrade failed', { status: 400, headers: baseHeaders });
248
+ }
249
+
250
+ const websocket: WebSocketHandler<LiveSocketData> = {
251
+ idleTimeout: 0,
252
+ open(ws) {
253
+ if (stopped || closing) {
254
+ try { ws.close(); } catch {}
255
+ return;
256
+ }
257
+ const handle = attachSocket();
258
+ activeSockets.add(ws);
259
+ ws.data = {
260
+ ...ws.data,
261
+ release: () => {
262
+ activeSockets.delete(ws);
263
+ handle.close();
264
+ },
265
+ };
266
+ try {
267
+ ws.send(ws.data.key ? JSON.stringify({ type: 'live', key: ws.data.key }) : 'live');
268
+ } catch {
269
+ ws.data.release?.();
270
+ }
271
+ },
272
+ message() {},
273
+ close(ws) {
274
+ ws.data?.release?.();
275
+ },
276
+ };
277
+
278
+ function dropSockets(): number {
279
+ const list = [...activeSockets];
280
+ for (const ws of list) {
281
+ try {
282
+ ws.close(1012, 'dropped');
283
+ } catch {}
284
+ ws.data?.release?.();
285
+ }
286
+ return list.length;
287
+ }
288
+
289
+ function onRequestStart(pathname: string): void {
290
+ if (isIgnoredActivityPath(pathname)) return;
291
+ inFlightRequests += 1;
292
+ if (stopped || closing) return;
293
+ const current = now();
294
+ if (everConnected && connections === 0) {
295
+ zeroSince = current;
296
+ } else if (!everConnected) {
297
+ startedAt = current;
298
+ }
299
+ }
300
+
301
+ function onRequestEnd(pathname: string): void {
302
+ if (isIgnoredActivityPath(pathname)) return;
303
+ inFlightRequests = Math.max(0, inFlightRequests - 1);
304
+ if (inFlightRequests === 0 && !stopped && !closing) {
305
+ check();
306
+ }
307
+ }
308
+
309
+ function rearmUnopened(): boolean {
310
+ if (stopped || closing) return false;
311
+ const current = now();
312
+ startedAt = current;
313
+ waitingForInFlight = false;
314
+ if (connections === 0) {
315
+ everConnected = false;
316
+ zeroSince = null;
317
+ }
318
+ return true;
319
+ }
320
+
321
+ function stop(): void {
322
+ if (stopped) return;
323
+ stopped = true;
324
+ closing = false;
325
+ clearInterval(timer);
326
+ clearInterval(keepaliveTimer);
327
+ for (const ws of [...activeSockets]) {
328
+ try { ws.close(); } catch {}
329
+ }
330
+ activeSockets.clear();
331
+ resolveExited(null);
332
+ }
333
+
334
+ return {
335
+ upgrade,
336
+ websocket,
337
+ attachSocket,
338
+ dropSockets,
339
+ onRequestStart,
340
+ onRequestEnd,
341
+ rearmUnopened,
342
+ stop,
343
+ get connections() {
344
+ return connections;
345
+ },
346
+ get everConnected() {
347
+ return everConnected;
348
+ },
349
+ exited,
350
+ };
351
+ }