@rig-c/review 4.0.1 → 4.0.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rig-c/review",
3
- "version": "4.0.1",
3
+ "version": "4.0.2",
4
4
  "type": "module",
5
5
  "description": "Local human rig inspection and structured feedback export",
6
6
  "license": "MIT",
@@ -154,6 +154,30 @@ export function recoverSession<T extends {id:string;revision:string;sourceHash:s
154
154
  /** Drafts kept per origin before least-recently-written eviction; recent drafts are never evicted. */
155
155
  export const maximumDrafts=32,protectedDraftMs=24*60*60*1000;
156
156
  const draftPrefix='rig-review-draft/1:',draftIndex='rig-review-draft-index/1';
157
+ const cropDatabase='rig-review-inspection-drafts',cropStore='crops',cropReference='draft-crop:';
158
+ /** Only existing stage-comment crops in inspection sessions belong to this private transport. */
159
+ function draftCrops(session:unknown):{row:{id:string};crop:Record<string,unknown>}[] {
160
+ if(!session||typeof session!=='object'||!Array.isArray((session as PersistenceSession).feedback))return [];
161
+ return (session as PersistenceSession).feedback.flatMap(item=>{
162
+ const comment=(item as {context?:{comment?:unknown}}|null)?.context?.comment;
163
+ if(!hasStageComment(comment))return [];
164
+ const row=record(item,'draft');if(typeof row.id!=='string')throw new Error('Draft review state invalid');
165
+ return [{row:row as {id:string},crop:record((comment as {crop:unknown}).crop,'crop')}];
166
+ });
167
+ }
168
+ /** Browser counterpart of comment-crops.ts's signature/dimension/digest boundary (no Node imports). */
169
+ async function draftPng(blob:Blob,crop:Record<string,unknown>):Promise<string|null> {
170
+ if(!(blob instanceof Blob)||blob.size>150000)return null;
171
+ const bytes=new Uint8Array(await blob.arrayBuffer()),view=new DataView(bytes.buffer);
172
+ if(bytes.length<33||[137,80,78,71,13,10,26,10].some((value,i)=>bytes[i]!==value)||
173
+ view.getUint32(8)!==13||String.fromCharCode(...bytes.slice(12,16))!=='IHDR'||
174
+ ![crop.width,crop.height].every(n=>Number.isSafeInteger(n)&&Number(n)>0&&Number(n)<=1024)||
175
+ view.getUint32(16)!==crop.width||view.getUint32(20)!==crop.height)return null;
176
+ const digest=[...new Uint8Array(await crypto.subtle.digest('SHA-256',bytes))].map(n=>n.toString(16).padStart(2,'0')).join('');
177
+ if(digest!==crop.sha256||crop.path!==`comment-crops/${digest}.png`)return null;
178
+ let binary='';for(const byte of bytes)binary+=String.fromCharCode(byte);
179
+ const png='data:image/png;base64,'+btoa(binary);if(png.length>200000)return null;return png;
180
+ }
157
181
  /** Storage is confined to this app; the scope carries the source identity (`single:<id>:<sourceHash>`), so
158
182
  * revisions of one package opened on one origin keep separate drafts. Opening deletes nothing; writing evicts
159
183
  * the least-recently-written drafts beyond 32, except any written within the last 24 hours. */
@@ -162,9 +186,11 @@ export class InspectionDraftStore {
162
186
  private blocked=false;
163
187
  private rawRecovery:string|null=null;
164
188
  private priorKey:string|null=null;
189
+ private pending:Promise<void>=Promise.resolve();
165
190
  recovery():string|null{return this.rawRecovery;}
166
191
  readonly key:string;
167
- constructor(private readonly scope:string,private readonly binding:InspectionBinding,private readonly warn:(message:string)=>void,storage?:Storage,private readonly now:()=>number=Date.now){
192
+ constructor(private readonly scope:string,private readonly binding:InspectionBinding,private readonly warn:(message:string)=>void,storage?:Storage,private readonly now:()=>number=Date.now,private readonly factory?:IDBFactory|null){
193
+ this.binding=structuredClone(binding);
168
194
  this.key=`${draftPrefix}${scope}:${binding.sourceHash}`;
169
195
  try{this.storage=storage??localStorage;this.storage.getItem(draftIndex);}catch{this.storage=null;warn('Local draft storage unavailable. Keep this page open or export feedback before leaving.');}
170
196
  }
@@ -175,7 +201,7 @@ export class InspectionDraftStore {
175
201
  return times;
176
202
  }
177
203
  private evict():void{
178
- const storage=this.storage!,now=this.now(),times=this.written();if(this.priorKey&&this.priorKey!==this.key){storage.removeItem(this.priorKey);times.delete(this.priorKey);this.priorKey=null;}times.set(this.key,now);
204
+ const storage=this.storage!,now=this.now(),times=this.written();if(this.priorKey&&this.priorKey!==this.key){storage.removeItem(this.priorKey);times.delete(this.priorKey);}times.set(this.key,now);
179
205
  const old=[...times].filter(([key,time])=>key!==this.key&&now-time>protectedDraftMs).sort((a,b)=>a[1]-b[1]);
180
206
  for(const [key]of old){if(times.size<=maximumDrafts)break;storage.removeItem(key);times.delete(key);}
181
207
  storage.setItem(draftIndex,JSON.stringify(Object.fromEntries(times)));
@@ -183,21 +209,105 @@ export class InspectionDraftStore {
183
209
  private parseDraft(raw:string,expectedBinding:InspectionBinding):LocalInspectionDraft{
184
210
  if(new TextEncoder().encode(raw).length>maximumDraftBytes)throw new Error('Draft exceeds 512 KiB');const o=record(JSON.parse(raw),'draft');keys(o,['schema','sourceHash','baseline','savedAt','reviewDirty','bookmark','inputs','session','ui'],'draft');if(o.schema!=='rig-review-local-draft/1'||o.sourceHash!==expectedBinding.sourceHash)throw new Error('Draft binding/version differs');if(typeof o.reviewDirty!=='boolean')throw new Error('Draft review state invalid');const bookmark=parseBookmark(o.bookmark,expectedBinding),baseline=hash(o.baseline);if(typeof o.savedAt!=='string'||!Number.isFinite(Date.parse(o.savedAt)))throw new Error('Draft timestamp invalid');const ui=record(o.ui,'draft UI');for(const [k,v]of Object.entries(ui)){text(k,'draft UI key');if(v!==null&&typeof v!=='string'&&typeof v!=='number'||typeof v==='number'&&!Number.isFinite(v))throw new Error('Draft UI value invalid');}return {schema:o.schema,sourceHash:this.binding.sourceHash,baseline,savedAt:o.savedAt,reviewDirty:o.reviewDirty,bookmark:{...bookmark,binding:{...bookmark.binding,sourceHash:this.binding.sourceHash}},inputs:parseInputs(o.inputs),session:o.session,ui:ui as LocalInspectionDraft['ui']};
185
211
  }
186
- read(canRecover?:(session:unknown)=>boolean):LocalInspectionDraft|null {
187
- if(!this.storage)return null;try{const raw=this.storage.getItem(this.key);if(!raw){
188
- if(this.binding.mode==='compare'&&canRecover){
189
- const prefix=`${draftPrefix}${this.scope}:`,candidates=[...this.written().entries()].filter(([k])=>k!==this.key&&k.startsWith(prefix)).sort((a,b)=>b[1]-a[1]);
190
- for(const [candidateKey]of candidates){
191
- try{const candidateRaw=this.storage.getItem(candidateKey);if(!candidateRaw)continue;const sourceHash=hash(candidateKey.slice(prefix.length)),parsed=this.parseDraft(candidateRaw,{...this.binding,sourceHash});if(!canRecover(parsed.session))continue;this.priorKey=candidateKey;this.rawRecovery=candidateRaw;return parsed;}catch{}
192
- }
212
+ private ordered<T>(operation:()=>Promise<T>):Promise<T> {
213
+ const result=this.pending.then(operation);this.pending=result.then(()=>{},()=>{});return result;
214
+ }
215
+ private openCrops():Promise<IDBDatabase> {
216
+ return new Promise<IDBDatabase>((resolve,reject)=>{
217
+ const factory=this.factory===undefined?globalThis.indexedDB:this.factory;
218
+ if(!factory){reject(new Error('COMMENT_CROP_STATE_UNAVAILABLE: stored crop cannot be read'));return;}
219
+ const request=factory.open(cropDatabase,1);let blocked=false;
220
+ request.onupgradeneeded=()=>request.result.createObjectStore(cropStore);
221
+ request.onerror=()=>reject(request.error);
222
+ request.onblocked=()=>{blocked=true;reject(new Error('COMMENT_CROP_STATE_UNAVAILABLE: stored crop cannot be read'));};
223
+ request.onsuccess=()=>{if(blocked)request.result.close();else resolve(request.result);};
224
+ });
225
+ }
226
+ /** Resolve only on transaction completion, never an individual request's success. */
227
+ private async crops(mode:IDBTransactionMode,visit:(store:IDBObjectStore)=>void):Promise<void> {
228
+ const db=await this.openCrops();
229
+ try{await new Promise<void>((resolve,reject)=>{
230
+ const transaction=db.transaction(cropStore,mode);
231
+ transaction.oncomplete=()=>resolve();transaction.onabort=()=>reject(transaction.error);
232
+ transaction.onerror=()=>{};
233
+ try{visit(transaction.objectStore(cropStore));}catch(error){transaction.abort();reject(error);}
234
+ });}finally{db.close();}
235
+ }
236
+ private async unpack(raw:string,key:string,expected:InspectionBinding):Promise<LocalInspectionDraft> {
237
+ if(new TextEncoder().encode(raw).length>maximumDraftBytes)throw new Error('Draft exceeds 512 KiB');
238
+ const packed=record(JSON.parse(raw),'draft');
239
+ if(packed.schema!=='rig-review-local-draft/2')return this.parseDraft(raw,expected);
240
+ // Check the bounded envelope/binding before touching IDB; validate the full session only after hydration.
241
+ const draft=this.parseDraft(JSON.stringify({...packed,schema:'rig-review-local-draft/1'}),expected);
242
+ const crops=draftCrops(draft.session),blobs=new Map<{id:string},Blob>();
243
+ if(crops.length)await this.crops('readonly',store=>{
244
+ for(const {row,crop}of crops){
245
+ if(crop.png!==cropReference+crop.sha256)throw new Error('COMMENT_CROP_STATE_UNAVAILABLE: stored crop cannot be read');
246
+ const request=store.get([key,row.id,hash(crop.sha256)]);request.onsuccess=()=>blobs.set(row,request.result);
193
247
  }
194
- return null;
195
- }this.rawRecovery=raw;return this.parseDraft(raw,this.binding);}catch(error){this.blocked=true;this.warn(`Saved local draft was not restored: ${error instanceof Error?error.message:String(error)}. It remains in storage for recovery.`);return null;}
248
+ });
249
+ // A completed read with missing/corrupt bytes loses only that image comment; transport failures still throw.
250
+ const unavailable=new Set<unknown>();
251
+ for(const {row,crop}of crops){const png=await draftPng(blobs.get(row)!,crop);if(png===null)unavailable.add(row);else crop.png=png;}
252
+ if(unavailable.size){const session=record(draft.session,'draft');session.feedback=(session.feedback as unknown[]).filter(row=>!unavailable.has(row));}
253
+ return draft;
196
254
  }
197
- write(draft:LocalInspectionDraft):boolean {
198
- if(!this.storage||this.blocked)return false;try{const value=JSON.stringify(draft);if(new TextEncoder().encode(value).length>maximumDraftBytes)throw new Error('Draft exceeds 512 KiB');this.storage.setItem(this.key,value);try{this.evict();}catch{}return true;}catch(error){this.warn(`Local draft could not be saved: ${error instanceof Error?error.message:String(error)}. Export feedback before leaving.`);return false;}
255
+ read(canRecover?:(session:unknown)=>boolean):Promise<LocalInspectionDraft|null> {
256
+ return this.ordered(async()=>{
257
+ if(!this.storage)return null;try{const raw=this.storage.getItem(this.key);if(!raw){
258
+ if(this.binding.mode==='compare'&&canRecover){
259
+ const prefix=`${draftPrefix}${this.scope}:`,candidates=[...this.written().entries()].filter(([k])=>k!==this.key&&k.startsWith(prefix)).sort((a,b)=>b[1]-a[1]);
260
+ for(const [candidateKey]of candidates){
261
+ const candidateRaw=this.storage.getItem(candidateKey);if(!candidateRaw)continue;
262
+ let parsed:LocalInspectionDraft;
263
+ try{const sourceHash=hash(candidateKey.slice(prefix.length));parsed=await this.unpack(candidateRaw,candidateKey,{...this.binding,sourceHash});}
264
+ catch(error){let referenced=false;try{referenced=JSON.parse(candidateRaw).schema==='rig-review-local-draft/2';}catch{}if(!referenced)continue;this.priorKey=candidateKey;this.rawRecovery=candidateRaw;throw error;}
265
+ if(!canRecover(parsed.session))continue;this.priorKey=candidateKey;this.rawRecovery=JSON.parse(candidateRaw).schema==='rig-review-local-draft/2'?JSON.stringify(parsed):candidateRaw;return parsed;
266
+ }
267
+ }
268
+ return null;
269
+ }this.rawRecovery=raw;const parsed=await this.unpack(raw,this.key,this.binding);this.rawRecovery=JSON.parse(raw).schema==='rig-review-local-draft/2'?JSON.stringify(parsed):raw;return parsed;}catch(error){this.blocked=true;this.warn(`Saved local draft was not restored: ${error instanceof Error?error.message:String(error)}. It remains in storage for recovery.`);return null;}
270
+ });
271
+ }
272
+ write(draft:LocalInspectionDraft):Promise<boolean> {
273
+ // Snapshot at invocation, before any await or queued storage operation can observe later edits.
274
+ const snapshot=JSON.stringify(draft);
275
+ return this.ordered(async()=>{
276
+ if(!this.storage||this.blocked)return false;
277
+ try{
278
+ const packed=JSON.parse(snapshot) as LocalInspectionDraft;
279
+ // Clean sessions are already durable on the server and are never restored as unsent feedback.
280
+ if(!packed.reviewDirty&&packed.session&&typeof packed.session==='object'){
281
+ packed.session={...packed.session,feedback:[]};
282
+ }
283
+ const crops=draftCrops(packed.session),blobs:{key:IDBValidKey;blob:Blob}[]=[];
284
+ for(const {row,crop}of crops){
285
+ if(typeof crop.png!=='string'||crop.png.length>200000||!/^data:image\/png;base64,[A-Za-z0-9+/]+={0,2}$/.test(crop.png))throw new Error('COMMENT_CROP_STATE_UNAVAILABLE: stored crop cannot be read');
286
+ blobs.push({key:[this.key,row.id,hash(crop.sha256)],blob:new Blob([Uint8Array.from(atob(crop.png.slice(22)),c=>c.charCodeAt(0))],{type:'image/png'})});
287
+ crop.png=cropReference+crop.sha256;
288
+ }
289
+ let value=JSON.stringify({...packed,schema:'rig-review-local-draft/2'});
290
+ if(new TextEncoder().encode(value).length>maximumDraftBytes)throw new Error('Draft exceeds 512 KiB');
291
+ try{if(blobs.length)await this.crops('readwrite',store=>{for(const {key,blob}of blobs)store.put(blob,key);});}
292
+ catch{value=snapshot;if(new TextEncoder().encode(value).length>maximumDraftBytes)throw new Error('Draft exceeds 512 KiB');}
293
+ // IDB has committed before localStorage can publish a crop reference. Failure retains the old draft.
294
+ this.storage.setItem(this.key,value);try{this.evict();}catch{}return true;
295
+ }catch(error){this.warn(`Local draft could not be saved: ${error instanceof Error?error.message:String(error)}. Export feedback before leaving.`);return false;}
296
+ });
297
+ }
298
+ clear():Promise<void> {
299
+ return this.ordered(async()=>{
300
+ const keys=[this.key,...(this.priorKey&&this.priorKey!==this.key?[this.priorKey]:[])];
301
+ try{
302
+ for(const key of keys)this.storage?.removeItem(key);
303
+ this.priorKey=null;this.blocked=false;this.rawRecovery=null;
304
+ // Only explicit clear/submission reclaims blobs, never opening, autosave or draft-index eviction.
305
+ try{await this.crops('readwrite',store=>{
306
+ const request=store.openCursor();request.onsuccess=()=>{const cursor=request.result;if(cursor){if(Array.isArray(cursor.key)&&keys.includes(String(cursor.key[0])))cursor.delete();cursor.continue();}};
307
+ });}catch{} // Unavailable IDB must not prevent clearing the local draft.
308
+ }catch{this.warn('Local draft could not be cleared.');}
309
+ });
199
310
  }
200
- clear():void {try{this.storage?.removeItem(this.key);if(this.priorKey&&this.priorKey!==this.key){this.storage?.removeItem(this.priorKey);this.priorKey=null;}this.blocked=false;this.rawRecovery=null;}catch{this.warn('Local draft could not be cleared.');}}
201
311
  }
202
312
 
203
313
  interface PersistenceSession {id:string;revision:string;sourceHash:string;status:string;feedback:unknown[]}
@@ -218,7 +328,7 @@ export async function connectInspectionPersistence<T extends PersistenceSession>
218
328
  const holdRestore=(value:boolean)=>{restoring=value;const body=document.body;if(value){if(body&&previousInert===null){previousInert=body.inert;body.inert=true;}}else if(body&&previousInert!==null){body.inert=previousInert;previousInert=null;}};
219
329
  let baseline=await sessionFingerprint(adapter.baseline);const status=adapter.onStatus,initialInputs=captureInputs();
220
330
  const store=new InspectionDraftStore(adapter.scope,adapter.binding,status);
221
- let draft=store.read(session=>recoverSession(session,adapter.baseline)!==null);
331
+ let draft=await store.read(session=>recoverSession(session,adapter.baseline)!==null);
222
332
  const notices=[document.getElementById('draft-recovery'),document.getElementById('review-draft-recovery')].filter((node):node is HTMLElement=>node!==null);
223
333
  const clearNotices=()=>{for(const node of notices)node.replaceChildren();};
224
334
  const appendAction=(label:string,onclick:()=>void)=>{for(const node of notices){const button=actionButton(label,onclick);node.append(button);}};
@@ -231,7 +341,7 @@ export async function connectInspectionPersistence<T extends PersistenceSession>
231
341
  recovered=recoverSession(draft.session,adapter.baseline);
232
342
  const prior=recovered?recoverSession(adapter.baseline,draft.session as T):null;
233
343
  sameBaseline=draft.baseline===baseline||(prior!==null&&draft.baseline===await sessionFingerprint(prior));
234
- if(!draft.reviewDirty&&(!sameBaseline||!recovered||draft.baseline!==baseline)){store.clear();draft=null;recovered=null;}
344
+ if(!draft.reviewDirty&&(!sameBaseline||!recovered||draft.baseline!==baseline)){await store.clear();draft=null;recovered=null;}
235
345
  }
236
346
  const raw=store.recovery();
237
347
  if(draft){
@@ -245,7 +355,7 @@ export async function connectInspectionPersistence<T extends PersistenceSession>
245
355
  }
246
356
  if(raw&&(conflict||!draft))appendAction('Download saved local draft',()=>download(raw));
247
357
  if(conflict&&recovered)appendAction('Recover local draft as pending',()=>{try{adapter.restoreSession({...recovered,status:'pending'},true);conflict=false;adapter.onConflict(false);clearNotices();status('Recovered local draft as pending · not submitted');save();}catch(error){status(`Local draft recovery refused: ${error instanceof Error?error.message:String(error)}`);}});
248
- if(conflict)appendAction('Discard conflicting local draft',()=>{adapter.restoreSession(structuredClone(adapter.baseline),false);restoreInputs(initialInputs,viewInputIds);adapter.afterInputs();store.clear();conflict=false;adapter.onConflict(false);clearNotices();status('Local draft discarded · current submitted review retained.');save();});
358
+ if(conflict)appendAction('Discard conflicting local draft',async()=>{adapter.restoreSession(structuredClone(adapter.baseline),false);restoreInputs(initialInputs,viewInputIds);adapter.afterInputs();await store.clear();conflict=false;adapter.onConflict(false);clearNotices();status('Local draft discarded · current submitted review retained.');save();});
249
359
  const selected=location.hash.startsWith('#review=')?explicit:draft?.bookmark;
250
360
  let restored=location.hash.startsWith('#review=')||!!draft;
251
361
  if(selected){try{await adapter.restoreBookmark(selected,new AbortController().signal);restored=true;}catch(error){status(`Inspection was not restored: ${error instanceof Error?error.message:String(error)}`);}}
@@ -253,13 +363,20 @@ export async function connectInspectionPersistence<T extends PersistenceSession>
253
363
  const excluded=new Set(viewInputIds);if(conflict||!draft.reviewDirty){excluded.add('review-status');excluded.add('status');excluded.add('checkpoint-note');for(const key of Object.keys(draft.inputs))if(key.startsWith('radio:outcome:'))excluded.add(key);}
254
364
  restoreInputs(draft.inputs,excluded);adapter.afterInputs();
255
365
  }
256
- if(raw&&!draft)appendAction('Discard unusable local draft',()=>{store.clear();clearNotices();status('Unusable local draft discarded for this review only.');save();});
366
+ if(raw&&!draft)appendAction('Discard unusable local draft',async()=>{await store.clear();clearNotices();status('Unusable local draft discarded for this review only.');save();});
367
+ let writes=Promise.resolve();
257
368
  restoring=false;
258
369
  if(draft&&!conflict&&draft.baseline!==baseline)save();
370
+ function snapshot():LocalInspectionDraft {
371
+ return structuredClone<LocalInspectionDraft>({schema:'rig-review-local-draft/1',sourceHash:adapter.binding.sourceHash,baseline,savedAt:new Date().toISOString(),reviewDirty:adapter.reviewDirty(),bookmark:parseBookmark(adapter.bookmark(),adapter.binding),inputs:captureInputs(),session:adapter.session(),ui:adapter.ui()});
372
+ }
373
+ async function persist(value:LocalInspectionDraft,navigation:number):Promise<void> {
374
+ value.baseline=baseline;
375
+ if(await store.write(value)&&!closed&&!restoring&&navigation===navigationGeneration){const url=new URL(location.href);url.hash=encodeBookmark(value.bookmark);history.replaceState(null,'',url);lastNavigationHash=url.hash;}
376
+ }
259
377
  function save():void {
260
378
  if(closed||restoring||conflict)return;
261
- try{const bookmark=parseBookmark(adapter.bookmark(),adapter.binding);const value:LocalInspectionDraft={schema:'rig-review-local-draft/1',sourceHash:adapter.binding.sourceHash,baseline,savedAt:new Date().toISOString(),reviewDirty:adapter.reviewDirty(),bookmark,inputs:captureInputs(),session:adapter.session(),ui:adapter.ui()};
262
- if(store.write(value)){const url=new URL(location.href);url.hash=encodeBookmark(bookmark);history.replaceState(null,'',url);lastNavigationHash=url.hash;}
379
+ try{const value=snapshot(),navigation=navigationGeneration;writes=writes.then(()=>persist(value,navigation)).catch(error=>{status(`Local view was not saved: ${error instanceof Error?error.message:String(error)}`);});
263
380
  }catch(error){status(`Local view was not saved: ${error instanceof Error?error.message:String(error)}`);}
264
381
  }
265
382
  function navigateView():void {
@@ -285,5 +402,9 @@ export async function connectInspectionPersistence<T extends PersistenceSession>
285
402
  const events=['input','change','click','pointerup','wheel'] as const;for(const event of events)window.addEventListener(event,schedule,{passive:true});
286
403
  const interval=setInterval(()=>{if(!document.hidden)save();},1000);
287
404
  const copy=document.getElementById('copy-view');const copyView=async()=>{if(closed)return;try{const url=inspectionLink(location.href,adapter.bookmark());await navigator.clipboard.writeText(url.href);history.replaceState(null,'',url);lastNavigationHash=url.hash;status('View link copied · source-bound numeric region, no review decisions.');}catch(error){status(`View link was not copied: ${error instanceof Error?error.message:String(error)}`);}};if(copy)copy.onclick=copyView;
288
- return {restored,restoring:()=>restoring,save,submitted:async session=>{baseline=await sessionFingerprint(session);save();},dispose:()=>{save();closed=true;++navigationGeneration;navigationAbort?.abort();holdRestore(false);window.removeEventListener('hashchange',navigateView);window.removeEventListener('popstate',navigateView);if(copy?.onclick===copyView)copy.onclick=null;if(timer)clearTimeout(timer);clearInterval(interval);for(const event of events)window.removeEventListener(event,schedule);}};
405
+ return {restored,restoring:()=>restoring,save,submitted:session=>{
406
+ if(closed)return Promise.resolve();
407
+ const submitted=structuredClone(session),value=snapshot(),navigation=navigationGeneration;
408
+ writes=writes.then(async()=>{baseline=await sessionFingerprint(submitted);await store.clear();await persist(value,navigation);});return writes;
409
+ },dispose:()=>{save();closed=true;++navigationGeneration;navigationAbort?.abort();holdRestore(false);window.removeEventListener('hashchange',navigateView);window.removeEventListener('popstate',navigateView);if(copy?.onclick===copyView)copy.onclick=null;if(timer)clearTimeout(timer);clearInterval(interval);for(const event of events)window.removeEventListener(event,schedule);}};
289
410
  }
@@ -171,7 +171,8 @@ export function createJobRigScreen(options: {
171
171
  let modals:JobRigScreenPrepared['modals'];
172
172
  const asks=options.window.state().pending.filter(ask=>ask.publicationId===display.publication.publicationId&&ask.subject.kind!=='review-verdict'&&ask.subject.kind!=='parts-verdict'&&jobRigScreenAsk(display,ask,checkpoints));
173
173
  if(!backdropOnly&&options.formDependencies){
174
- const inspection=await prepareJobInspection(display,signal,true);
174
+ // The shared main workspace loads visuals; modal forms keep data and checkpoint evidence.
175
+ const inspection=await prepareJobInspection(display,signal,true,false);
175
176
  try{modals={inspection,forms:prepareJobForms(display,asks,ask=>formFor(ask,inspection,options.formDependencies!))};}
176
177
  catch(error){inspection.dispose();throw error;}
177
178
  }
@@ -866,8 +866,8 @@ export function mediaReady(media: HTMLVideoElement, name: 'loadeddata' | 'seeked
866
866
  failed();
867
867
  });
868
868
  }
869
- /** Prepare the real published Play model, references and every form dependency off-stage. */
870
- export async function prepareJobInspection(display: DisplayPublicationV3, signal: AbortSignal, formsOnly=false): Promise<JobPreparedInspection> {
869
+ /** Prepare off-stage; modal-only callers may skip workspace visuals, never checkpoint evidence. */
870
+ export async function prepareJobInspection(display: DisplayPublicationV3, signal: AbortSignal, formsOnly=false, preloadVisuals=true): Promise<JobPreparedInspection> {
871
871
  const routes = jobPublicationRoutes(display, location.origin);
872
872
  const metadata = await jobJson<JobInspectionMetadataV3>(routes.api('review'), signal);
873
873
  const publishedSource = display.publication.source;
@@ -1006,7 +1006,7 @@ export async function prepareJobInspection(display: DisplayPublicationV3, signal
1006
1006
  checkpointEvidence[index] = {packet, table, images};
1007
1007
  })());
1008
1008
  }
1009
- for (const reference of metadata.manifest?.references ?? []) {
1009
+ for (const reference of preloadVisuals ? metadata.manifest?.references ?? [] : []) {
1010
1010
  if (reference.id === metadata.sourcePainting?.id) continue;
1011
1011
  preload.push((async () => {
1012
1012
  if (reference.type === 'image') {
@@ -1105,7 +1105,7 @@ export async function prepareJobInspection(display: DisplayPublicationV3, signal
1105
1105
  }
1106
1106
  })());
1107
1107
  }
1108
- if (metadata.sourcePainting) {
1108
+ if (preloadVisuals && metadata.sourcePainting) {
1109
1109
  const source = metadata.sourcePainting;
1110
1110
  preload.push(image(routes.instance(source.url), source.sha256).then(element => {
1111
1111
  element.alt = source.path;
@@ -1113,11 +1113,11 @@ export async function prepareJobInspection(display: DisplayPublicationV3, signal
1113
1113
  width: element.naturalWidth, height: element.naturalHeight, seek: async () => { } });
1114
1114
  }));
1115
1115
  }
1116
- for (const part of parts?.items ?? []) {
1116
+ for (const part of preloadVisuals ? parts?.items ?? [] : []) {
1117
1117
  preload.push(image(routes.api('stage-parts/image/' + part.index), part.imageHash)
1118
1118
  .then(element => { element.alt = part.name; partImages.set(part.name, element); }));
1119
1119
  }
1120
- for (const page of parts?.pages ?? []) {
1120
+ for (const page of preloadVisuals ? parts?.pages ?? [] : []) {
1121
1121
  preload.push(image(routes.api('stage-parts/page/' + page.index))
1122
1122
  .then(element => { partPages.set(page.index, element); }));
1123
1123
  }