rig-review 4.6.0 → 4.7.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/web/main.ts CHANGED
@@ -1,11 +1,13 @@
1
1
  import {hasTransientQuestionImage} from './interview-panel.ts';
2
2
  import {advanceTake,bindScenePlates,loadScenePlates,takeSample} from './scene-plates.ts';
3
3
  import type {SceneInspection} from '../src/scene-inspection.ts';
4
+ import type {RecordSource} from '../src/job-contract.ts';
4
5
  import type {InterviewSubjectEntry} from '../src/joined-project.ts';
5
6
  import {mountJobScreen,joinedInterviewForms,mediaReady,jobSubmissionRefusal} from './job-session.ts';
6
7
  import {partsIssueComments,parsePartsIssue,assertPartsIssueBinding} from '../src/parts-comment.ts';
7
8
  import type {JobForm} from './job-session.ts';
8
- import {bindWorkspaceDrawer} from './workspace-layout.ts';
9
+ import type {JobRigMeshHost,JobRigMeshScreen} from './job-rig-screen.ts';
10
+ import {bindWorkspaceDrawer,settleAnimationFrames} from './workspace-layout.ts';
9
11
  import {captureRigRestStill,rigRestCanvas} from './job-rig-capture.ts';
10
12
  import {createPartsViewportProvider,bindPartsSubject,paintRigDifference,type PartsSubjectEntry,type PartsSubjectSession} from './parts-viewport-provider.ts';
11
13
  import {rigWorkspaceMarkup,rigFeedbackMarkup,sharedViewToolsMarkup,sharedCommentMarkup} from '../src/compare-html.ts';
@@ -92,7 +94,7 @@ const lifecycle=new AbortController();
92
94
  let suspended=false,disposed=false,frameHandle=0,navigationMissing=false;
93
95
  let publicEditor:unknown;
94
96
  let workspace:WorkspaceUI|null=null;
95
- interface ReviewResponse { scene?:SceneInspection; direction?:DirectionInspection; setsHash?:string; referenceHashes?:Record<string,string>; initialAnimation?:string|null; manifest: ReviewManifest; referenceBinding?:ReferenceBinding; explicitReference?:{id:string;name:string;sha256:string;url:string}; sourcePainting?:{id:string;path:string;sha256:string;url:string}; sourceHash: string; reviewedSource: ReviewedSource; report: ReportSeeds | null; feedbackCatalog: FeedbackCatalog; assetsBase: string; capabilities: { interview?:true; preRig?:true; playback: boolean; modeling: false; motion: false; feedback: boolean; audio: boolean } }
97
+ interface ReviewResponse { scene?:SceneInspection; direction?:DirectionInspection; recordSource?:RecordSource; setsHash?:string; referenceHashes?:Record<string,string>; initialAnimation?:string|null; manifest: ReviewManifest; referenceBinding?:ReferenceBinding; explicitReference?:{id:string;name:string;sha256:string;url:string}; sourcePainting?:{id:string;path:string;sha256:string;url:string}; sourceHash: string; reviewedSource: ReviewedSource; report: ReportSeeds | null; feedbackCatalog: FeedbackCatalog; assetsBase: string; capabilities: { interview?:true; preRig?:true; playback: boolean; modeling: false; motion: false; feedback: boolean; audio: boolean } }
96
98
  interface PoseReference { schema: 'rig-review-pose/1'; coordinateSystem: 'image-pixels-y-down'; width: number; height: number; joints: { id: string; x: number; y: number; parent?: string }[] }
97
99
  interface SequenceJoint { state: 'observed' | 'occluded' | 'missing' | 'inferred'; at?: [number, number]; score?: number }
98
100
  interface PoseSequence { spec: 'rig-pose-sequence/1'; space: { units: 'picture-px'; origin: 'top-left'; y: 'down' }; width: number; height: number; source?: string; frames: { t: number; people: { id: string; joints: Record<string, SequenceJoint> }[] }[]; camera?: { s: number; tx: number; ty: number; inliers: number }[]; cameraSource?: unknown }
@@ -111,7 +113,7 @@ const option = (value: string, label: string) => { const item = document.createE
111
113
  const errorText = (error: unknown) => error instanceof Error ? error.message : String(error);
112
114
  // Capability is consumed before shell composition or any URL-dependent binding.
113
115
  // A live job (#709) hosts this screen for a rig subject: its routes, its session and its submit.
114
- let host=rigHost(),access=host?.access??pageInstanceAccess();
116
+ let host:JobRigMeshHost|null=rigHost(),access=host?.access??pageInstanceAccess();
115
117
  let partsOnly=host?.subject==='parts'||screenRoot.dataset.reviewScreen==='parts';
116
118
  let firstPublicationPrompt=!!host?.waiting;
117
119
  const app=el('app');app.innerHTML=rigWorkspaceMarkup+rigFeedbackMarkup;
@@ -280,7 +282,12 @@ function message(value: string, error = false, footerOnly = false, diagnostic?:
280
282
  // A view readout (a Difference count) is not the act's state, so it stays in the footer only.
281
283
  if (footerOnly) return;
282
284
  // The modal makes the footer inert; the review dialog repeats the latest message for its reader.
283
- text('review-message', value); el('review-message').classList.toggle('error', error);
285
+ const reviewMessage=el('review-message');
286
+ if(reviewMessage.dataset?.partsPinRefusal){
287
+ if(!error)return;
288
+ delete reviewMessage.dataset.partsPinRefusal;
289
+ }
290
+ text('review-message', value); reviewMessage.classList.toggle('error', error);
284
291
  if(host&&error&&rigInspector.act.hidden&&!rigInspector.answersRendered){
285
292
  for(const node of rigInspector.act.querySelectorAll<HTMLElement>('#save,#review-status,label[for="review-status"]'))node.hidden=true;
286
293
  rigInspector.act.hidden=false;
@@ -320,7 +327,7 @@ function updateSavedState(): void {
320
327
  }
321
328
 
322
329
  /** C10: the act bar renders the latest local draft status; rig only classifies it. Nothing renders before the first status. */
323
- let liveIssueCount=()=>session?.feedback.length??0;
330
+ let liveIssueCount=()=>(session?.feedback.length??0)+(host?.verdictComments?.rows.length??0);
324
331
  function renderDraftState(): void {
325
332
  const live=host?.reviewState?.(liveIssueCount(),saving);
326
333
  renderAnswerControls();
@@ -441,7 +448,18 @@ function renderLayout():void {
441
448
  for(const id of controls.viewModeIds)if(id!=='difference')controls.setDisabled(id,state.reasons[id as SingleLayout]??null);
442
449
  if(activeInterviewImages)controls.setMode('interview-image-'+activeInterviewImages.indexOf(activeInterviewImage!));
443
450
  else controls.setMode(rigDifference||partsSubject?.comparison().mode==='difference'?'difference':state.effective,state.effective??state.requested);
444
- if(partsSubject){controls.setDisabled('difference',partsSubject.differenceAvailable()&&rigInput.state==='loaded'&&referenceInput.state==='loaded'?null:tr('PARTS_DIFFERENCE_UNAVAILABLE: missing painting_in_rig declaration or painting_in_rig.json sidecar and its bound operand.'));if(partsSubject.comparison().mode==='difference')controls.setMode('difference');}
451
+ if(partsSubject){
452
+ const previousAvailable=partsSubject.previousDraftAvailable(),comparison=partsSubject.comparison();
453
+ const available=partsSubject.differenceAvailable()&&rigInput.state==='loaded'&&(previousAvailable||referenceInput.state==='loaded');
454
+ controls.setDisabled('difference',available?null:tr('PARTS_DIFFERENCE_UNAVAILABLE: missing painting_in_rig declaration or painting_in_rig.json sidecar and its bound operand.'));
455
+ if(comparison.mode==='difference')controls.setMode('difference');
456
+ const operand=screenRoot.querySelector<HTMLSelectElement>('#parts-difference-operand');
457
+ if(operand){
458
+ operand.parentElement!.hidden=!!activeInterviewImages||!previousAvailable||comparison.mode!=='difference';
459
+ operand.value=comparison.mode==='difference'?comparison.operand??'painting':'painting';
460
+ operand.title=operand.selectedOptions[0]?.title??'';
461
+ }
462
+ }
445
463
  if(!partsSubject){controls.setDisabled('difference',tr(rigDifferenceReason()??'')||null);if(rigDifference)controls.setMode('difference');}
446
464
  el('reference-pane').hidden=state.effective!=='compare'&&state.effective!=='reference';el('rig-pane').hidden=state.effective!=='compare'&&state.effective!=='rig';
447
465
  const shown={compare:'Side by side',reference:'Reference only',rig:'Rig only'};
@@ -935,7 +953,7 @@ function isSubmittedFeedback(id:string):boolean {
935
953
  function renderProposals(): void {
936
954
  comments?.refresh();
937
955
  if(host?.direction){setSourceText(rigInspector.comments.button,`Comments (${recordComments.length})`);return;}
938
- const count=session.feedback.length;setSourceText(rigInspector.comments.button, `Comments (${count})`);
956
+ const count=session.feedback.length+(host?.verdictComments?.rows.length??0);setSourceText(rigInspector.comments.button, `Comments (${count})`);
939
957
  const area = el('proposal-list'); area.replaceChildren();
940
958
  const warnings = el('feedback-warnings'); warnings.hidden = session.feedbackWarnings.length === 0;
941
959
  const unchecked = session.feedback.map(f => appliedCheckRefusal((f.context as Record<string, unknown> | undefined)?.applied)).find(Boolean) ?? null;
@@ -1113,6 +1131,8 @@ function recordFeedback(summary:string,feedback?:Feedback,correction?:ReturnType
1113
1131
  }
1114
1132
 
1115
1133
 
1134
+ function sealedRecordRigReadOnly():string|null {return host?.record&&data?.recordSource?readOnly:null;}
1135
+
1116
1136
  function bind(): void {
1117
1137
  button('strip-export').onclick = () => { void exportStrip(); };
1118
1138
  button('chest-export').onclick = () => { void exportChest(); };
@@ -1167,19 +1187,26 @@ function bind(): void {
1167
1187
  saving = true; updateSavedState(); const savedPayload = JSON.stringify(session);
1168
1188
  if (host) {
1169
1189
  let submissionFailure: ReturnType<typeof jobSubmissionRefusal> | null = null;
1190
+ const generalRows = host.verdictComments?.rows;
1191
+ const general = generalRows?.map(row=>row.summary);
1170
1192
  try {
1171
1193
  const sent = await host.submit(structuredClone(session), async committed => {
1172
1194
  submittedBaseline = {...submittedBaseline!, ...committed.review,
1173
1195
  checkpoints: {...submittedBaseline!.checkpoints, ...committed.checkpoints}, updatedAt: committed.at};
1174
1196
  session.updatedAt = committed.at;
1197
+ if (generalRows && general?.length && committed.review) {
1198
+ generalRows.splice(0,general.length);
1199
+ persistRecordComments();
1200
+ }
1175
1201
  const ids = new Set([...Object.keys(session.checkpoints), ...Object.keys(submittedBaseline.checkpoints)]);
1176
1202
  dirty = session.status !== submittedBaseline.status || JSON.stringify(session.feedback) !== JSON.stringify(submittedBaseline.feedback) ||
1203
+ !!generalRows?.length ||
1177
1204
  [...ids].some(id => JSON.stringify(session.checkpoints[id] ?? {outcome: 'pending', note: ''}) !==
1178
1205
  JSON.stringify(submittedBaseline!.checkpoints[id] ?? {outcome: 'pending', note: ''}));
1179
1206
  if(host?.direction){for(const row of recordComments)submittedDirectionComments.add(row.id);try{localStorage.removeItem(recordCommentKey);}catch{}}
1180
1207
  await persistence?.submitted(submittedBaseline);
1181
1208
  comments?.refresh(); renderProposals();
1182
- },host.direction?recordCommentWords():undefined);
1209
+ },host.direction?recordCommentWords():undefined,general);
1183
1210
  message(sent);
1184
1211
  } catch (error) {
1185
1212
  submissionFailure = jobSubmissionRefusal(error);
@@ -1215,7 +1242,11 @@ function bind(): void {
1215
1242
  overlays=new RigOverlays({canvas:el<HTMLCanvasElement>('rig-overlay'),rigRoot:el('rig-root')});
1216
1243
  verdictSubmit=button('save').onclick as ((event:MouseEvent)=>unknown)|null;
1217
1244
  chestEditor=bindChestEditor({pane:el('rig-pane'),canvas:el('rig-overlay'),project:()=>player?rigProject():null,mapping:()=>activeChestMapping(),changed:renderChest,download:()=>{void exportChest();},apply:()=>{void applyRebuild();},reset:()=>{void resetRebuild();},message,inspector:()=>selectedInspector()});viewDisposers.push(()=>chestEditor?.dispose());
1218
- meshEditor=bindMeshEditor({pane:el('rig-pane'),canvas:el('rig-overlay'),project:()=>player?rigProject():null,mapping:()=>chestMapping,inspector:()=>selectedInspector(),source:meshSource,pause,changed:()=>redrawOverlay(false),download:doc=>{void exportMesh(doc);},apply:(doc,line)=>applyMeshDelta(doc,line),applied:()=>appliedOnStage?.schema==='rig-review-applied/3',resetBuild:()=>resetRebuild(stageWorld()),message,confirm:text=>window.confirm(tr(text)),token:name=>getComputedStyle(document.documentElement).getPropertyValue(name).trim()});viewDisposers.push(()=>meshEditor?.dispose());
1245
+ const editRefusal=sealedRecordRigReadOnly();
1246
+ if(editRefusal)chestEditor.unavailable(editRefusal);
1247
+ meshEditor=bindMeshEditor({pane:el('rig-pane'),canvas:el('rig-overlay'),project:()=>player?rigProject():null,mapping:()=>chestMapping,inspector:()=>selectedInspector(),readOnly:!!editRefusal,source:meshSource,pause,
1248
+ job:host?(host.record||host.direction||!host.access.capability?'read-only':{slots:()=>data.feedbackCatalog.slots??[],modelHash:()=>inspectionSourceState==='ready'&&chestMapping.available?stageModelHash:null}):undefined,changed:()=>{if(host)renderAnswerControls();redrawOverlay(false);},download:doc=>{void exportMesh(doc);},
1249
+ apply:(doc,line)=>applyMeshDelta(doc,line),applied:()=>appliedOnStage?.schema==='rig-review-applied/3',resetBuild:()=>resetRebuild(stageWorld()),message,confirm:text=>window.confirm(tr(text)),token:name=>getComputedStyle(document.documentElement).getPropertyValue(name).trim()});viewDisposers.push(()=>meshEditor?.dispose());
1219
1250
  weightsView=bindWeightsView({pane:el('rig-pane'),canvas:el('rig-overlay'),project:()=>player?rigProject():null,inspector:()=>selectedInspector(),slot:()=>parts?.value()?.slot??stageDraftSelection?.slot??null,
1220
1251
  model:()=>hasStageModel()?partModel??undefined:null,setup:slot=>assets?setupPoseMesh(assets,partModel,slot,document.createElement('div')):null,changed:()=>redrawOverlay(false),
1221
1252
  token:name=>getComputedStyle(document.documentElement).getPropertyValue(name).trim()});
@@ -1319,6 +1350,8 @@ async function start(): Promise<void> {
1319
1350
  const [saved,accessState]=await Promise.all([api<ReviewSession|PartsSubjectSession>('/api/session'),api<{capabilityRequired:boolean;control?:boolean}>('/api/access')]);
1320
1351
  if('subject' in opened&&opened.subject==='parts'){await startParts(opened,saved as PartsSubjectSession,accessState);return;}
1321
1352
  data=opened as ReviewResponse;session=saved as ReviewSession;writes=accessState;
1353
+ // A sealed record rig is the question's picture, so open its existing rig-only view.
1354
+ if(host?.record && data.recordSource)view='rig';
1322
1355
  readOnly = host?.unavailable?t('job.refusal.'+host.unavailable):host?.record ? tr('JOB_REVIEW_READ_ONLY') : readOnlyReason(access, writes.capabilityRequired);
1323
1356
  actReadOnly = readOnlyReason(access, writes.capabilityRequired, host?.ownerActAccess);
1324
1357
  if(data.capabilities.preRig&&!host?.record){rigInspector.comments.button.disabled=true;rigInspector.act.hidden=true;}
@@ -1330,7 +1363,7 @@ async function start(): Promise<void> {
1330
1363
  // Checkpoints and reference fold away when the package supplies neither.
1331
1364
  (el('package-context') as HTMLDetailsElement).open = data.manifest.checkpoints.length > 0 || data.manifest.references.length > 0;
1332
1365
  const sourceFiles = el('source-files'); for (const file of data.manifest.authoring) { const a = document.createElement('a'); a.href = assetUrl(file.path); a.textContent = file.label; a.className = 'source-link'; a.target = '_blank'; a.rel = 'noopener'; sourceFiles.append(a); } if (!data.manifest.authoring.length) sourceFiles.textContent = 'No source files supplied';sourceFiles.parentElement!.hidden=!data.manifest.authoring.length;
1333
- populateChestBones(); bind(); parts=new PartExplorer(el('workspace-left'),el('selected-part'),previous=>{if(rigDifference){leaveRigDifference();renderLayout();}const part=parts?.value();if(!stageCorrectionRebinding&&(previous?.side!==part?.side||previous?.slot!==part?.slot||previous?.mode!==part?.mode))stageDraftRequestToken++;if(player&&inspectionSourceState==='ready')animationPanel?.capture(player,parts?.frame('single'));else animationPanel?.capture(null,undefined);weightsView?.refresh();redrawOverlay(true);meshEditor?.selectionChanged();if(stageCorrectionPart&&!stageCorrectionRebinding&&(part?.slot??null)!==stageCorrectionPart){stageCorrectionPart=null;document.getElementById('stage-draft-label')?.remove();}animationPanel?.fromParts(part?.slot??null);meshPanel?.select(part?.slot??null);if(part&&!stageCorrectionRebinding)void openStageCorrection({part:part.slot,instrument:'selection'});requirementsPanel?.selectionChanged();renderDropNotices();if(part){viewport.state.activeCamera='rig';if(view==='reference')setView('rig');if(selectedInspector(document)!=='playback')showInspector('rig');renderCameraControls();}if(!viewport.state.cameraRestoring&&(previous?.side!==part?.side||previous?.slot!==part?.slot))cameraAction(()=>fitActiveCamera(part?'rig':availableCamera()));persistence?.save();},part=>{select('feedback-target-kind').value='slot';renderFeedbackTargets(true);input('feedback-target-name').value=part.slot;showInspector('feedback');}); animationPanel=new AnimationInspectionPanel({hideGateBanner:!!host?.direction,host:el('animation-inspection'),stage:el('rig-viewport'),project:(x,y)=>rigProject()(x,y),enabled:()=>inspectionSourceState==='ready'&&selectedInspector(document)==='playback',pause,preview:fn=>{animAdjust=fn;if(!player)return;player.adjust=composeAdjust(composeAdjust(composeAdjust(idleAdjust,dialAdjust),turnAdjust),animAdjust);if(!inDrawRig&&player.current&&!playing){if(activeScene())seek(time);else{player.seek(time);drawRig(()=>player!.draw());}}},apply:ops=>applyAnimation(ops),reset:()=>resetAnimationBuild(),seek:exact=>{if(!Number.isFinite(exact)||exact<0||exact>duration){message('KEY_TIME_OUT_OF_DOMAIN: no substitute time was used.',true);return;}seekMarker(animation,exact,'Stored key');},select:value=>{const slot=value?.kind==='slot'?value.name:null;if((parts?.value()?.slot??null)!==slot)parts?.select(slot?{side:'single',slot,mode:parts?.value()?.mode??'context'}:null);parts?.highlightBone(value?.kind==='bone'?value.name:null);redrawOverlay(false);}});viewDisposers.push(()=>animationPanel?.dispose()); updateStripControls(); stripStatus('Choose the entered start–end frames or all feedback ranges to download. Unsubmitted feedback is included; exporting does not submit the review.'); renderFeedbackTargets(true); renderFeedbackRange(); renderCheckpoints(); renderProposals(); renderProvenance(); updateSavedState(); renderCues(); initReport();
1366
+ populateChestBones(); bind(); parts=new PartExplorer(el('workspace-left'),el('selected-part'),previous=>{if(rigDifference){leaveRigDifference();renderLayout();}const part=parts?.value();if(!stageCorrectionRebinding&&(previous?.side!==part?.side||previous?.slot!==part?.slot||previous?.mode!==part?.mode))stageDraftRequestToken++;if(player&&inspectionSourceState==='ready')animationPanel?.capture(player,parts?.frame('single'));else animationPanel?.capture(null,undefined);weightsView?.refresh();redrawOverlay(true);meshEditor?.selectionChanged();if(stageCorrectionPart&&!stageCorrectionRebinding&&(part?.slot??null)!==stageCorrectionPart){stageCorrectionPart=null;document.getElementById('stage-draft-label')?.remove();}animationPanel?.fromParts(part?.slot??null);meshPanel?.select(part?.slot??null);if(part&&!stageCorrectionRebinding)void openStageCorrection({part:part.slot,instrument:'selection'});requirementsPanel?.selectionChanged();renderDropNotices();if(part){viewport.state.activeCamera='rig';if(view==='reference')setView('rig');if(selectedInspector(document)!=='playback')showInspector('rig');renderCameraControls();}if(!viewport.state.cameraRestoring&&(previous?.side!==part?.side||previous?.slot!==part?.slot))cameraAction(()=>fitActiveCamera(part?'rig':availableCamera()));persistence?.save();},part=>{select('feedback-target-kind').value='slot';renderFeedbackTargets(true);input('feedback-target-name').value=part.slot;showInspector('feedback');}); animationPanel=new AnimationInspectionPanel({hideGateBanner:!!host?.direction,readOnlyReason:sealedRecordRigReadOnly,host:el('animation-inspection'),stage:el('rig-viewport'),project:(x,y)=>rigProject()(x,y),enabled:()=>inspectionSourceState==='ready'&&selectedInspector(document)==='playback',pause,preview:fn=>{animAdjust=fn;if(!player)return;player.adjust=composeAdjust(composeAdjust(composeAdjust(idleAdjust,dialAdjust),turnAdjust),animAdjust);if(!inDrawRig&&player.current&&!playing){if(activeScene())seek(time);else{player.seek(time);drawRig(()=>player!.draw());}}},apply:ops=>applyAnimation(ops),reset:()=>resetAnimationBuild(),seek:exact=>{if(!Number.isFinite(exact)||exact<0||exact>duration){message('KEY_TIME_OUT_OF_DOMAIN: no substitute time was used.',true);return;}seekMarker(animation,exact,'Stored key');},select:value=>{const slot=value?.kind==='slot'?value.name:null;if((parts?.value()?.slot??null)!==slot)parts?.select(slot?{side:'single',slot,mode:parts?.value()?.mode??'context'}:null);parts?.highlightBone(value?.kind==='bone'?value.name:null);redrawOverlay(false);}});viewDisposers.push(()=>animationPanel?.dispose()); updateStripControls(); stripStatus('Choose the entered start–end frames or all feedback ranges to download. Unsubmitted feedback is included; exporting does not submit the review.'); renderFeedbackTargets(true); renderFeedbackRange(); renderCheckpoints(); renderProposals(); renderProvenance(); updateSavedState(); renderCues(); initReport();
1334
1367
  const requestedId = new URLSearchParams(location.search).get('checkpoint'),initial=initialReviewSelection(data.manifest,requestedId,data.explicitReference?.id,data.initialAnimation??undefined),first=initial.checkpoint;
1335
1368
  rigInput=data.manifest.model?{state:'pending'}:{state:'absent'};renderLayout();
1336
1369
  // A job rig subject lands in Animate before the model finishes loading (#709).
@@ -1360,13 +1393,16 @@ async function start(): Promise<void> {
1360
1393
  }
1361
1394
  if(!player&&(data.manifest.model||referenceInput.state!=='loaded'))throw new Error('JOB_VISUAL_UNAVAILABLE');
1362
1395
  await restorePublicationNavigation();document.body.dataset.ready='true';
1363
- host.attach({recordForms:renderRecordForms,pendingSubjects:renderPendingSubjects,stage:hostStage,redraw:()=>{if(player&&!playing)drawRig(()=>player!.draw());},message:(value,error,diagnostic)=>message(value,error,false,diagnostic),...host.record?{}:{incompatible:()=>navigationMissing,navigation:()=>({subject:'rig' as const,bookmark:inspectionBookmark()})},suspend:suspendScreen,resume:resumeScreen,dispose:disposeScreen});showInspector(data.manifest.model?'playback':'rig');host.displayed();
1396
+ const screen:JobRigMeshScreen={recordForms:renderRecordForms,pendingSubjects:renderPendingSubjects,stage:hostStage,redraw:()=>{if(player&&!playing)drawRig(()=>player!.draw());},message:(value,error,diagnostic)=>message(value,error,false,diagnostic),...host.record?{}:{incompatible:()=>navigationMissing,navigation:()=>({subject:'rig' as const,bookmark:inspectionBookmark()})},suspend:suspendScreen,resume:resumeScreen,dispose:disposeScreen,
1397
+ hasMeshEdits:()=>!!meshEditor?.hasJobEdits(),meshEdits:async()=>meshEditor?.jobEdits()??null};
1398
+ host.attach(screen);showInspector(data.manifest.model?'playback':'rig');host.displayed();
1364
1399
  }
1365
1400
  } catch (error) { if(disposed)return;message(`Could not open review package: ${errorText(error)}`, true); text('dirty', 'Load failed'); host?.failed(error); }
1366
1401
  }
1367
1402
  /** Parts have a verdict and image-space pixels, never fabricated model/session fields. */
1368
1403
  async function startParts(opened:PartsSubjectEntry,saved:PartsSubjectSession,writes:{capabilityRequired:boolean}):Promise<void>{
1369
1404
  const subject=opened.parts,issues=saved.issues;let partsBaseline=structuredClone(saved);const submittedIssues=new Set(host? saved.issues.map(issue=>issue.id):[]);
1405
+ const generalRows=host?.verdictComments?.rows;
1370
1406
  liveIssueCount=()=>issues.length;
1371
1407
  if(!partsOnly)throw new Error('PARTS_SUBJECT_ENTRY_REQUIRED');
1372
1408
  readOnly=host?.record?tr('JOB_REVIEW_READ_ONLY'):readOnlyReason(access,writes.capabilityRequired);
@@ -1378,12 +1414,18 @@ async function startParts(opened:PartsSubjectEntry,saved:PartsSubjectSession,wri
1378
1414
  const response=await fetch(access.route(path),{...init,headers:access.headers(init?.headers)});
1379
1415
  if(!response.ok){const body=await response.json();throw new Error(typeof body.error==='string'?body.error:body.error?.code??'PARTS_PAINT_FAILED');}return response;
1380
1416
  };
1381
- const changed=()=>{dirty=true;text('dirty','Unsubmitted changes');el('dirty').classList.add('dirty');parts?.refreshImages();rigInspector.actBar.setSaveState({kind:'unsaved',text:'Unsubmitted changes'});renderDraftState();setSourceText(rigInspector.comments.button,`Comments (${issues.length})`);return persistence?.save();};
1417
+ const showCommentCount=()=>setSourceText(rigInspector.comments.button,`Comments (${issues.length+(generalRows?.length??0)})`);
1418
+ const changed=()=>{dirty=true;text('dirty','Unsubmitted changes');el('dirty').classList.add('dirty');parts?.refreshImages();rigInspector.actBar.setSaveState({kind:'unsaved',text:'Unsubmitted changes'});renderDraftState();showCommentCount();return persistence?.save();};
1382
1419
  // A parts verdict is saved only over a drawn subject: until the first paint, or after a failed one, Save stays off.
1383
1420
  const saveBlocked=()=>!!readOnly||!!subject.legacyVerdict?.readOnly||rigInput.state!=='loaded'||draftConflict||!!persistence?.restoring();
1384
1421
  partsAnswerBlocked=saveBlocked;
1385
1422
  text('rig-empty','Loading package…');
1386
- partsSubject=bindPartsSubject({data:subject,canvas:partsCanvas,referenceCanvas:partsReference,viewport,el,toolbar:primaryToolbar,commentsHost:el('comments-list-host'),openComments:openReview,hasPicture:()=>!hasTransientQuestionImage(screenRoot),issues,...host?.record?{recordComments}:{},request,base,paintingPath:host?'/review-painting':'/api/parts/painting',mesh:()=>layers.mesh,restoreMesh:on=>{layers.mesh=on;input('layer-mesh').checked=on;},images:()=>layers.images,changed:()=>{if(host?.record){recordCommentsChanged();return;}return changed();},selectionChanged:()=>parts?.refreshImages(),locked:id=>submittedIssues.has(id),refusal:()=>readOnly,drawn:state=>{rigInput=state;button('save').disabled=saveBlocked();renderAnswerControls();if(state.state==='failed')text('rig-empty',state.reason);text('renderer-state',state.state==='loaded'?'Parts raster drawn · Canvas2D':'Rendering failed');text('player-state',state.state==='loaded'?'Parts images · no compiled rig loaded':'Rig load failed');renderLayout();},message});
1423
+ if(generalRows)restoreRecordComments();
1424
+ partsSubject=bindPartsSubject({data:subject,canvas:partsCanvas,referenceCanvas:partsReference,viewport,el,toolbar:primaryToolbar,commentsHost:el('comments-list-host'),openComments:openReview,hasPicture:()=>!hasTransientQuestionImage(screenRoot),issues,
1425
+ ...(host?.record?{recordComments}:host?.verdictComments?{generalComments:host.verdictComments,submitting:()=>saving}:{}),
1426
+ request,base,paintingPath:host?'/review-painting':'/api/parts/painting',mesh:()=>layers.mesh,restoreMesh:on=>{layers.mesh=on;input('layer-mesh').checked=on;},images:()=>layers.images,
1427
+ changed:()=>{if(host?.record){recordCommentsChanged();return;}if(generalRows)persistRecordComments();return changed();},
1428
+ selectionChanged:()=>parts?.refreshImages(),locked:id=>submittedIssues.has(id),refusal:()=>readOnly,drawn:state=>{rigInput=state;button('save').disabled=saveBlocked();renderAnswerControls();if(state.state==='failed')text('rig-empty',state.reason);text('renderer-state',state.state==='loaded'?'Parts raster drawn · Canvas2D':'Rendering failed');text('player-state',state.state==='loaded'?'Parts images · no compiled rig loaded':'Rig load failed');renderLayout();},message});
1387
1429
  parts=new PartExplorer(el('workspace-left'),el('selected-part'),()=>{},()=>openReview());
1388
1430
  const thumbnails=new PartThumbnails();viewDisposers.push(()=>thumbnails.dispose());
1389
1431
  parts.registerImages({thumbnail:(icon,item,glyph)=>thumbnails.showOriginal(icon,item,()=>partsSubject!.image(item.index),glyph),items:subject.items,selected:partsSubject.selected,solo:partsSubject.solo,visible:partsSubject.visible,select:partsSubject.select,isolate:partsSubject.isolate,show:partsSubject.show});
@@ -1404,9 +1446,29 @@ async function startParts(opened:PartsSubjectEntry,saved:PartsSubjectSession,wri
1404
1446
  const overlayLabel=panelMake('label',{},overlay,tr('Overlay')),opacityLabel=panelMake('label',{},tr('Part opacity'),opacity);
1405
1447
  if(!subject.painting)for(const node of [overlayLabel,opacityLabel])setSourceAttribute(node,'title','PARTS_REFERENCE_UNAVAILABLE: supply --painting to compare the original painting');
1406
1448
  secondaryToolbar.append(overlayLabel,opacityLabel);
1449
+ const previousDraft=subject.previousDraft;
1450
+ if(previousDraft){
1451
+ const paintingOption=option('painting',''),previousOption=option('previous-draft','');
1452
+ paintingOption.disabled=!partsSubject.paintingDifferenceAvailable();
1453
+ previousOption.title=`${previousDraft.id} · ${previousDraft.revision}`;
1454
+ const operand=panelMake('select',{id:'parts-difference-operand',translate:false},paintingOption,previousOption);
1455
+ const label=panelMake('label',{id:'parts-difference-operand-label',hidden:true},tr('Compare with'),operand);
1456
+ const localizeOptions=()=>{
1457
+ paintingOption.textContent=t('Original painting');
1458
+ previousOption.textContent=t('Previous accepted draft · {0} · {1}',[previousDraft.id,previousDraft.revision.slice(0,12)]);
1459
+ };
1460
+ localizeOptions();viewDisposers.push(onLanguageChange(localizeOptions));
1461
+ operand.onchange=()=>{
1462
+ const bound=partsSubject;
1463
+ if(!bound||label.hidden)return;
1464
+ void bound.setComparison('difference',operand.value==='previous-draft'?'previous-draft':'painting')
1465
+ .then(drawn=>{if(!drawn&&partsSubject===bound)renderLayout();});
1466
+ };
1467
+ secondaryToolbar.append(label);
1468
+ }
1407
1469
  overlay.onchange=()=>{partsSubject?.setComparison(overlay.checked?'overlay':'part');if(overlay.checked){view='rig';renderLayout();}};
1408
1470
  opacity.oninput=()=>partsSubject?.opacity(Number(opacity.value));
1409
- controls.setDisabled('difference',subject.differenceAvailable&&subject.painting?null:tr('PARTS_DIFFERENCE_UNAVAILABLE: missing painting_in_rig declaration or painting_in_rig.json sidecar and its bound operand.'));
1471
+ controls.setDisabled('difference',partsSubject.differenceAvailable()?null:tr('PARTS_DIFFERENCE_UNAVAILABLE: missing painting_in_rig declaration or painting_in_rig.json sidecar and its bound operand.'));
1410
1472
  const reference=select('reference-select');reference.replaceChildren(option('',subject.painting?'Original painting':'No references supplied'));reference.disabled=true;
1411
1473
  el('package-context').removeAttribute('open');el('reference-empty').hidden=!!subject.painting;el('rig-overlay').hidden=true;
1412
1474
  const state=rigInspector.actBar;state.setSaveState({kind:actReadOnly?'read-only':'unsaved',text:actReadOnly??'Not submitted'});
@@ -1414,12 +1476,14 @@ async function startParts(opened:PartsSubjectEntry,saved:PartsSubjectSession,wri
1414
1476
  button('save').disabled=saveBlocked();
1415
1477
  button('save').onclick=async()=>{
1416
1478
  if(saving||saveBlocked())return;saving=true;button('save').disabled=true;state.setSaveState({kind:'saving',text:'Saving…'});renderDraftState();
1417
- const frozen=structuredClone(issues);
1479
+ const frozen=structuredClone(issues),general=generalRows?.map(row=>row.summary);
1418
1480
  try{
1419
- if(host?.submitParts)message(await host.submitParts(frozen));
1481
+ if(host?.submitParts)message(await host.submitParts(frozen,general));
1420
1482
  else await request(base+'/verdict',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({status:frozen.length?'changes-requested':'approved',issues:frozen})});
1483
+ if(generalRows&&general?.length){generalRows.splice(0,general.length);persistRecordComments();}
1421
1484
  if(disposed)return;
1422
1485
  if(host)for(const issue of frozen)submittedIssues.add(issue.id);
1486
+ if(general?.length){partsSubject?.refreshComments();showCommentCount();}
1423
1487
  dirty=JSON.stringify(issues)!==JSON.stringify(frozen);partsBaseline={subject:'parts',issues:frozen};await persistence?.submitted(partsBaseline);if(disposed)return;state.setSaveState({kind:dirty?'unsaved':'saved',text:dirty?'Unsubmitted changes':'Submitted'});text('dirty',dirty?'Unsubmitted changes':'Submitted');el('dirty').classList.toggle('dirty',dirty);
1424
1488
  }catch(error){message(errorText(error),true);state.setSaveState({kind:'failed',text:'Save failed.'});}
1425
1489
  finally{saving=false;button('save').disabled=saveBlocked();renderDraftState();}
@@ -1432,7 +1496,7 @@ async function startParts(opened:PartsSubjectEntry,saved:PartsSubjectSession,wri
1432
1496
  const binding:InspectionBinding={mode:'single',sourceHash:subject.sourceHash,rigs:[null]};
1433
1497
  const connection=await connectInspectionPersistence({scope:'parts:'+access.key+':'+access.base+':'+subject.sourceHash,binding,baseline:partsBaseline,session:()=>({subject:'parts' as const,issues}),reviewDirty:()=>dirty,
1434
1498
  recover:value=>{try{if(!value||typeof value!=='object')return null;const row=value as PartsSubjectSession;if(row.subject!=='parts'||!Array.isArray(row.issues)||row.issues.length>1000||Object.keys(row).some(key=>!['subject','issues'].includes(key)))return null;const items=new Map(subject.items.map(item=>[item.name,{...item,imageHash:item.imageHash!}]));const restored=row.issues.map(issue=>{const parsed=parsePartsIssue(issue,false,true,false);assertPartsIssueBinding(parsed,items,subject.sourceHash);return parsed;});if(new Set(restored.map(issue=>issue.id)).size!==restored.length)return null;return {subject:'parts' as const,issues:restored};}catch{return null;}},
1435
- restoreSession:(value,isDirty)=>{issues.splice(0,issues.length,...value.issues);dirty=isDirty;partsSubject?.refreshComments();setSourceText(rigInspector.comments.button,`Comments (${issues.length})`);text('dirty',isDirty?'Unsubmitted changes':'Submitted');el('dirty').classList.toggle('dirty',isDirty);state.setSaveState({kind:isDirty?'unsaved':'saved',text:isDirty?'Unsubmitted changes':'Submitted'});},
1499
+ restoreSession:(value,isDirty)=>{issues.splice(0,issues.length,...value.issues);dirty=isDirty;partsSubject?.refreshComments();showCommentCount();text('dirty',isDirty?'Unsubmitted changes':'Submitted');el('dirty').classList.toggle('dirty',isDirty);state.setSaveState({kind:isDirty?'unsaved':'saved',text:isDirty?'Unsubmitted changes':'Submitted'});},
1436
1500
  bookmark:()=>({schema:'rig-review-inspection/1',binding,animation:null,time:null,theme:appearance?.get()??'system',layers:{images:layers.images,meshes:layers.mesh,bones:false},view:{schema:'rig-review-view/1',cameras:{rig:null,a:null,b:null,reference:null}},selection:{}}),
1437
1501
  // Parts comments carry their own explicit view restore. Opening never replays a selection or camera.
1438
1502
  restoreBookmark:async()=>{},
@@ -1440,6 +1504,7 @@ async function startParts(opened:PartsSubjectEntry,saved:PartsSubjectSession,wri
1440
1504
  if(disposed){connection.dispose();return;}persistence=connection;
1441
1505
  };
1442
1506
  await setupPartsPersistence();if(disposed)return;
1507
+ if(generalRows?.length)changed();
1443
1508
  renderPendingSubjects(host?.pendingSubjects?.()??[{kind:'parts-verdict'}]);
1444
1509
  if(host){await restorePublicationNavigation();host.attach({recordForms:renderRecordForms,stage:()=>null,redraw:()=>partsSubject?.redraw(),message:(value,error,diagnostic)=>message(value,error,false,diagnostic),pendingSubjects:renderPendingSubjects,...host.record?{}:{incompatible:()=>navigationMissing,navigation:()=>({subject:'parts' as const,part:partsSubject!.selected(),solo:partsSubject!.solo(),view,camera:numericView()})},suspend:suspendScreen,resume:resumeScreen,dispose:disposeScreen});host.displayed();}
1445
1510
 
@@ -1456,11 +1521,15 @@ function showRecordComments(preserveInspector=false):void {
1456
1521
  /** Publications without a picture reuse the empty main view; no model is manufactured. */
1457
1522
  async function startRecord(interview?:InterviewSubjectEntry):Promise<void> {
1458
1523
  if(!host?.record&&!interview)throw new Error('JOB_DISPLAY_MISMATCH');
1459
- const unavailable=interview?'MODEL_UNAVAILABLE: no compiled model is supplied in this inspection.':'This request has no picture.';
1524
+ const missingPicture=host?.record?.missingPicture;
1525
+ const unavailable=interview?'MODEL_UNAVAILABLE: no compiled model is supplied in this inspection.':
1526
+ missingPicture==='rig'?'This question refers to a rig version that this publication does not include.':
1527
+ missingPicture==='scene'?'This question refers to a scene that this publication does not include.':
1528
+ 'This request has no picture.';
1460
1529
  readOnly=tr(interview?'MODEL_UNAVAILABLE':'JOB_REVIEW_READ_ONLY');
1461
1530
  if(!interview)actReadOnly=readOnlyReason(access,true,host?.ownerActAccess);
1462
1531
  bindWorkspace();bindInspector(true);rigInput={state:'absent'};referenceInput={state:'absent'};renderLayout();
1463
- parts=new PartExplorer(el('workspace-left'),el('selected-part'),()=>{},()=>{});text('checkpoints','No checkpoints supplied.');text('dirty','Not submitted');if(interview)message(unavailable);else message(actReadOnly??unavailable,!!actReadOnly);
1532
+ parts=new PartExplorer(el('workspace-left'),el('selected-part'),()=>{},()=>{});text('checkpoints','No checkpoints supplied.');text('dirty','Not submitted');if(interview)message(unavailable);else message(actReadOnly??(host?.record?.scenePicture?'':unavailable),!!actReadOnly);
1464
1533
  text('package-title',interview?.label??host!.record!.label);text('revision','');text('source-hash',`source ${(interview?.sourceHash??host!.record!.sourceHash).slice(0,12)}`);
1465
1534
  el('rig-pane').hidden=false;el('rig-empty').hidden=false;text('rig-empty',unavailable);
1466
1535
  for(const region of document.querySelectorAll('.inspector,.workspace-secondary-toolbar'))for(const control of region.querySelectorAll<HTMLInputElement|HTMLSelectElement|HTMLButtonElement>('input,select,textarea,button')){control.disabled=true;setSourceAttribute(control,'title',unavailable);}
@@ -1486,12 +1555,13 @@ const questionPanel=panelMake('section',{id:'workspace-interview-answer',classNa
1486
1555
  let questionForms:readonly HTMLElement[]=[];
1487
1556
  let questionFormBindings=new WeakSet<HTMLElement>();
1488
1557
 
1489
- /** Reuse the form's publication binding for native record comments, without a package session. */
1558
+ /** Publication and source bind native comment drafts independently of inspection navigation. */
1490
1559
  function restoreRecordComments(form?:HTMLFormElement):void {
1491
- if((!host?.record&&!host?.direction)||recordCommentKey)return;
1492
- const publicationId=host?.direction?.publicationId??host?.record?.publicationId??form?.dataset.jobPublication,sourceHash=host?.direction?.sourceHash??host!.record!.sourceHash;
1560
+ const binding=host?.direction??host?.verdictComments??host?.record;
1561
+ if(!binding||recordCommentKey)return;
1562
+ const publicationId=binding.publicationId??form?.dataset.jobPublication,sourceHash=binding.sourceHash;
1493
1563
  if(!publicationId)throw new Error('JOB_DISPLAY_MISMATCH');
1494
- recordCommentKey='rig-review-record-comments/1:'+publicationId+':'+sourceHash;
1564
+ recordCommentKey=(host?.verdictComments?'rig-review-verdict-comments/1:':'rig-review-record-comments/1:')+publicationId+':'+sourceHash;
1495
1565
  try {
1496
1566
  const saved=JSON.parse(localStorage.getItem(recordCommentKey)??'null');
1497
1567
  if(saved?.publicationId!==publicationId||saved?.sourceHash!==sourceHash||!Array.isArray(saved.comments)||saved.comments.length>1000)return;
@@ -1500,21 +1570,31 @@ function restoreRecordComments(form?:HTMLFormElement):void {
1500
1570
  for(const row of rows){
1501
1571
  if(!row||typeof row.id!=='string'||!row.id||ids.has(row.id)||typeof row.summary!=='string'||!row.summary.trim()||row.summary.length>1000)throw new Error('JOB_ACT_INVALID');
1502
1572
  ids.add(row.id);
1573
+ if(host?.verdictComments&&('schema' in row||'target' in row))throw new Error('JOB_ACT_INVALID');
1503
1574
  if('schema' in row){const issue=parsePartsIssue(row,false,true,false),items=new Map((partsSubject?.items()??[]).map(item=>[item.name,{...item,imageHash:item.imageHash!}]));assertPartsIssueBinding(issue,items,partsSubject!.sourceHash());}
1504
1575
  else if('target' in row){const mark=parseStageComment((row.context as {comment?:unknown})?.comment);if((!host?.direction&&!host!.record!.hasPicture)||mark.sourceHash!==data.sourceHash)throw new Error('JOB_DISPLAY_MISMATCH');}
1505
1576
  else if(Object.keys(row).some(key=>key!=='id'&&key!=='summary'))throw new Error('JOB_ACT_INVALID');
1506
1577
  }
1507
- projectComments(rows.map(row=>'schema' in row?partsIssueComments([row as import('../src/parts-comment.ts').PartsIssue])[0]!:'target' in row?feedbackItemComments([row as Feedback])[0]!:{text:row.summary}));
1508
- recordComments.push(...rows);
1578
+ if(!host?.verdictComments)projectComments(rows.map(row=>'schema' in row?partsIssueComments([row as import('../src/parts-comment.ts').PartsIssue])[0]!:'target' in row?feedbackItemComments([row as Feedback])[0]!:{text:row.summary}));
1579
+ (host?.verdictComments?.rows??recordComments).push(...rows);
1509
1580
  }catch{/* A mismatched or invalid local draft has no authority. */}
1510
1581
  }
1511
1582
  /** Comments remain native rows locally; the old act field carries their scalar projection only. */
1512
1583
  function recordCommentWords():string {
1513
1584
  return projectComments(recordComments.map(row=>'schema' in row?partsIssueComments([row as import('../src/parts-comment.ts').PartsIssue])[0]!:'target' in row?feedbackItemComments([row as Feedback])[0]!:{text:row.summary}));
1514
1585
  }
1586
+ function persistRecordComments():void {
1587
+ const binding=host?.direction??host?.verdictComments??host?.record;
1588
+ if(!binding||!recordCommentKey)return;
1589
+ const comments=host?.verdictComments?.rows??recordComments;
1590
+ try{
1591
+ if(host?.verdictComments&&!comments.length)localStorage.removeItem(recordCommentKey);
1592
+ else localStorage.setItem(recordCommentKey,JSON.stringify({status:select('review-status').value,publicationId:binding.publicationId??recordDialog?.querySelector<HTMLFormElement>('form[data-job-ask]')?.dataset.jobPublication,sourceHash:binding.sourceHash,comments}));
1593
+ }catch{/* In-memory comments remain bound to this host. */}
1594
+ }
1515
1595
  function recordCommentsChanged():void {
1516
1596
  if(!host?.record&&!host?.direction)return;
1517
- try{if(recordCommentKey)localStorage.setItem(recordCommentKey,JSON.stringify({status:select('review-status').value,publicationId:host?.direction?.publicationId??host?.record?.publicationId??recordDialog?.querySelector<HTMLFormElement>('form[data-job-ask]')?.dataset.jobPublication,sourceHash:host?.direction?.sourceHash??host!.record!.sourceHash,comments:recordComments}));}catch{/* In-memory comments remain bound to this host. */}
1597
+ persistRecordComments();
1518
1598
  setSourceText(rigInspector.comments.button,`Comments (${recordComments.length})`);
1519
1599
  renderAnswerControls();
1520
1600
  for(const form of recordDialog?.querySelectorAll('form[data-job-ask]')??[])form.dispatchEvent(new Event('input',{bubbles:true}));
@@ -1525,8 +1605,8 @@ function syncQuestionImage():void {
1525
1605
  const selected=questionForms.length>0&&inspectorBlocks?.state()[selectedInspector()??'rig']==='question';
1526
1606
  if(!selected){releaseInterview?.();releaseInterview=null;return;}
1527
1607
  if(releaseInterview)return;
1528
- const images=(questionForms[0] as HTMLElement&{interviewImages:readonly {name:string;src:string}[]}).interviewImages;
1529
- if(!images.length)return;
1608
+ const images=(questionForms[0] as HTMLElement&{interviewImages?:readonly {name:string;src:string}[]}).interviewImages;
1609
+ if(!images?.length)return;
1530
1610
  const previousView=view,previousCamera=structuredClone(viewport.state);viewport.cancelFit();
1531
1611
  const previousReferenceNodes=[...el('reference-content').childNodes],previousReferenceInput=referenceInput,previousReferenceSize=referenceSize;
1532
1612
  const previousMedia={video,controlledVideoSample,sequence,sequenceSvg,selectedPerson,lastPoseFrame};
@@ -1558,19 +1638,19 @@ function renderRecordForms(forms:readonly HTMLElement[],label='job.pending',stan
1558
1638
  form.addEventListener('submit',event=>{if(draftConflict||pendingAnswers.some(subject=>subject.kind.endsWith('verdict'))){event.preventDefault();event.stopImmediatePropagation();}},true);
1559
1639
  form.addEventListener('job-answer-saved',()=>{answerSaved=true;recordDialog?.close();renderDraftState();},{once:true});
1560
1640
  }
1561
- const imageForms=forms.filter(form=>form.dataset.interviewMain!==undefined);
1562
- if(imageForms.length){
1641
+ const questionTabForms=forms.filter(form=>form.dataset.interviewMain!==undefined);
1642
+ if(questionTabForms.length){
1563
1643
  const added=!questionForms.length;
1564
- if(questionForms[0]!==imageForms[0]){releaseInterview?.();releaseInterview=null;}
1565
- for(const form of questionForms)if(!imageForms.includes(form)){form.dispatchEvent(new Event('job-form-dispose'));form.remove();}
1566
- questionForms=imageForms;
1567
- for(const form of imageForms)if(form.parentElement!==questionPanel)questionPanel.append(form);
1644
+ if(questionForms[0]!==questionTabForms[0]){releaseInterview?.();releaseInterview=null;}
1645
+ for(const form of questionForms)if(!questionTabForms.includes(form)){form.dispatchEvent(new Event('job-form-dispose'));form.remove();}
1646
+ questionForms=questionTabForms;
1647
+ for(const form of questionTabForms)if(form.parentElement!==questionPanel)questionPanel.append(form);
1568
1648
  if(added){viewDisposers.push(inspectorBlocks!.register({id:'question',panel:questionPanel,label:'Question',position:'first'}));inspectorBlocks!.restore({rig:'question',playback:'question'});inspectorBlocks!.select(selectedInspector()??'rig','question');workspace?.revealInspector();}
1569
1649
  syncQuestionImage();
1570
- if(imageForms.every(form=>form.dataset.interviewAnswered==='true'))answerSaved=true;
1650
+ if(questionTabForms.every(form=>form.dataset.interviewAnswered==='true'))answerSaved=true;
1571
1651
  rigAsk.onclick=()=>{if(draftConflict)return;inspectorBlocks?.select(selectedInspector()??'rig','question');workspace?.revealInspector();};
1572
1652
  }
1573
- forms=forms.filter(form=>!imageForms.includes(form));
1653
+ forms=forms.filter(form=>!questionTabForms.includes(form));
1574
1654
  if(!forms.length&&!recordDialog){renderDraftState();return;}
1575
1655
  if(!recordDialog){
1576
1656
  recordDialog=panelMake('dialog',{id:'job-record-asks',className:'workspace-drawer'});recordDialog.setAttribute('aria-label',tr(label));
@@ -1596,45 +1676,68 @@ function renderRecordForms(forms:readonly HTMLElement[],label='job.pending',stan
1596
1676
  }
1597
1677
  /** The ask heading reads only already-pending subjects. It never synthesizes an agent request. */
1598
1678
  function renderPendingSubjects(subjects:readonly {kind:string;stage?:string}[]):void {
1599
- const requests:Record<string,string>={'parts-verdict':'Check the parts and meshes.','interview-picks':'Answer these questions.','review-verdict:rig-review':'Check the rig and motion.','review-verdict:direction-review':'Check the direction.','review-verdict:image-review':'Check these images.','checkpoint':'Review this checkpoint.','signoff':'Approve this stage.','reopen':'Review the reopened stage.'};
1679
+ const requests:Record<string,string>={'parts-verdict':partsSubject?.items().some(item=>item.mesh)?'Check the parts and meshes.':'Check the parts.','interview-picks':'Answer these questions.','review-verdict:rig-review':'Check the rig and motion.','review-verdict:direction-review':'Check the direction.','review-verdict:image-review':'Check these images.','checkpoint':'Review this checkpoint.','signoff':'Approve this stage.','reopen':'Review the reopened stage.'};
1600
1680
  const labels=subjects.map(subject=>requests[subject.kind+':'+subject.stage]??requests[subject.kind]).filter((label):label is string=>!!label);
1681
+ const liveVerdict=(subject:{kind:string;stage?:string})=>
1682
+ partsOnly?subject.kind==='parts-verdict':subject.kind==='review-verdict'&&subject.stage==='rig-review';
1683
+ const refreshVerdictComments=host?.verdictComments&&pendingAnswers.some(liveVerdict)!==subjects.some(liveVerdict);
1601
1684
  pendingAnswers=subjects;
1685
+ if(refreshVerdictComments){comments?.refresh();partsSubject?.refreshComments();}
1602
1686
  askHeadline.hidden=false;setSourceText(askHeadline,labels.join(' · ')||(firstPublicationPrompt?t('job.waiting',undefined,'en'):'Nothing is waiting for your answer.'));
1603
1687
  if(subjects.length)firstPublicationPrompt=false;
1604
1688
  renderDraftState();
1605
1689
  }
1606
- /** Answer controls compose the existing act bar and submit handlers; act payloads stay unchanged. */
1690
+ /** Answer controls compose the existing act bar and submit handlers. */
1607
1691
  function renderAnswerControls():void {
1608
1692
  const subjects=host?.pendingSubjects?.()??pendingAnswers;
1609
- const verdict=subjects.some(subject=>subject.kind==='review-verdict'||subject.kind==='parts-verdict');
1693
+ const parts=subjects.some(subject=>subject.kind==='parts-verdict');
1694
+ const verdict=parts||subjects.some(subject=>subject.kind==='review-verdict');
1610
1695
  const dialog=subjects.some(subject=>!subject.kind.endsWith('verdict'))&&!verdict;
1611
1696
  const readable=questionForms.some(form=>form.dataset.interviewAnswered==='true')||!!recordDialog?.querySelector('form.interview-answer[data-interview-answered=true] fieldset:disabled');
1612
1697
  const enabled=questionForms.some(form=>!form.querySelector('fieldset')?.disabled)||!!recordDialog?.querySelector('fieldset:not(:disabled)');
1613
1698
  const blocked=saving||draftConflict||!!actReadOnly||!!host?.unavailable;
1614
1699
  const save=button('save');
1700
+ const hasPinnedPart=parts&&liveIssueCount()>0;
1701
+ const needsPinnedPart=parts&&!!host?.verdictComments?.rows.length&&!hasPinnedPart;
1702
+ const pinRefusal='Request changes needs at least one comment pinned to a part.';
1615
1703
  if((host||subjects.some(subject=>subject.kind==='interview-picks'))&&subjects.length&&!rigInspector.actBar.saveState())rigInspector.actBar.setSaveState({kind:'unsaved',text:'Not submitted'});
1616
1704
  select('review-status').hidden=true;document.querySelector<HTMLLabelElement>('label[for="review-status"]')!.hidden=true;
1617
- save.classList.toggle('primary',verdict&&!(subjects.some(subject=>subject.kind==='parts-verdict')&&liveIssueCount()>0));
1618
- requestChanges.classList.toggle('primary',verdict&&subjects.some(subject=>subject.kind==='parts-verdict')&&liveIssueCount()>0);
1705
+ save.classList.toggle('primary',verdict&&!hasPinnedPart);
1706
+ requestChanges.classList.toggle('primary',hasPinnedPart);
1619
1707
  rigAsk.classList.toggle('primary',dialog);
1620
1708
  const kind=subjects.find(subject=>!subject.kind.endsWith('verdict'))?.kind;
1621
1709
  setSourceText(rigAsk,kind==='signoff'?'Approve…':kind==='interview-picks'||readable?'Answer…':'Review…');
1622
1710
  rigAsk.disabled=(!enabled&&!readable)||(enabled&&blocked);
1623
1711
  if(verdict){
1624
- const parts=subjects.some(subject=>subject.kind==='parts-verdict'),count=host?.direction?recordComments.length:liveIssueCount();
1712
+ const count=host?.direction?recordComments.length:liveIssueCount();
1713
+ const hasChanges=count>0||!!host?.canSubmitMeshEdits?.()&&subjects.some(subject=>subject.kind==='review-verdict'&&subject.stage==='rig-review');
1625
1714
  setSourceText(save,'Approve');setSourceText(requestChanges,'Request changes');
1626
1715
  save.disabled=blocked||!!readOnly||!!session?.feedbackWarnings?.length||(parts&&(partsAnswerBlocked()||count>0));
1627
- requestChanges.disabled=blocked||!!readOnly||!!session?.feedbackWarnings?.length||count===0||(parts&&partsAnswerBlocked());
1716
+ requestChanges.disabled=blocked||!!readOnly||!!session?.feedbackWarnings?.length||!hasChanges||(parts&&partsAnswerBlocked());
1628
1717
  setSourceAttribute(save,'title',parts&&count>0?'Remove the flagged parts comments before approving.':'');
1629
- setSourceAttribute(requestChanges,'title',count===0?'Add a comment where changes are needed.':'');
1718
+ setSourceAttribute(requestChanges,'title',needsPinnedPart?pinRefusal:hasChanges?'':'Add a comment where changes are needed.');
1630
1719
  if(!parts){
1631
1720
  save.onclick=event=>{session.status='approved';select('review-status').value=session.status;return verdictSubmit?.(event);};
1632
1721
  }
1633
- requestChanges.onclick=()=>{if(requestChanges.disabled)return;if(parts){void save.onclick?.call(save,new PointerEvent('click'));}else{session.status='changes-requested';select('review-status').value=session.status;void verdictSubmit?.(new MouseEvent('click'));}};
1722
+ requestChanges.onclick=()=>{if(requestChanges.disabled)return;if(parts){if(liveIssueCount()===0)return;void save.onclick?.call(save,new PointerEvent('click'));}else{session.status='changes-requested';select('review-status').value=session.status;void verdictSubmit?.(new MouseEvent('click'));}};
1634
1723
  }
1635
1724
  for(const root of [recordDialog,...questionForms])for(const control of root?.querySelectorAll<HTMLButtonElement>('button[type="submit"]')??[])control.disabled=blocked||verdict;
1636
1725
  // The waiting row is already visible: finish labels, state and handlers before revealing any answer.
1637
1726
  save.hidden=!verdict||firstPublicationPrompt;requestChanges.hidden=save.hidden;rigAsk.hidden=!dialog||firstPublicationPrompt;
1727
+ if(host?.verdictComments){
1728
+ const notice=el('review-message');
1729
+ if(needsPinnedPart&&!save.hidden&&!save.disabled){
1730
+ if(!notice.classList.contains('error')){
1731
+ setSourceText(notice,pinRefusal);
1732
+ notice.classList.add('error');
1733
+ notice.dataset.partsPinRefusal='true';
1734
+ }
1735
+ }else if(notice.dataset.partsPinRefusal){
1736
+ delete notice.dataset.partsPinRefusal;
1737
+ setSourceText(notice,'');
1738
+ notice.classList.remove('error');
1739
+ }
1740
+ }
1638
1741
  if(host){rigInspector.answersRendered=true;rigInspector.act.hidden=subjects.length===0&&!firstPublicationPrompt;rigInspector.syncActRow?.();}
1639
1742
  }
1640
1743
  let verdictSubmit:((event:MouseEvent)=>unknown)|null=null;
@@ -1877,7 +1980,7 @@ async function applyInspection(bookmark:InspectionBookmark,signal:AbortSignal,pr
1877
1980
  if(selection.inspector)showInspector(selection.inspector,false);syncStageLayout(el('stage-layout'));
1878
1981
  // Mode changes schedule workspace layout and resize observers. Settle them
1879
1982
  // while restoration is held, before measuring/applying the saved pane camera.
1880
- await new Promise<void>(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve())));if(signal.aborted)throw new Error('Inspection restore superseded');fitCamera();
1983
+ await settleAnimationFrames();if(signal.aborted)throw new Error('Inspection restore superseded');fitCamera();
1881
1984
  const camera=bookmark.view.cameras.rig,ref=bookmark.view.cameras.reference,rigViewport=el('rig-viewport'),referenceViewport=el('reference-viewport');
1882
1985
  const nextZoom=camera&&player&&rigViewport.clientWidth&&rigViewport.clientHeight?restoredZoom(camera,viewport.state.rigScale/viewport.state.zoom,rigViewport.clientWidth,rigViewport.clientHeight):camera?.zoom??null;
1883
1986
  const nextReferenceZoom=ref&&referenceSize&&referenceViewport.clientWidth&&referenceViewport.clientHeight?restoredZoom(ref,viewport.state.referenceScale/viewport.state.referenceZoom,referenceViewport.clientWidth,referenceViewport.clientHeight):ref?.zoom??null;
@@ -2120,9 +2223,9 @@ function boneSetup(document:unknown):BoneSetup {
2120
2223
  }
2121
2224
  /** Setup's mesh edit: the selected slot's actual mesh as a typed delta. A two-file client download; nothing reaches the session or the package. */
2122
2225
  /** Edit Mesh's source (#100): the selected slot's mesh in the model document at the setup pose (a never-played player's bones). */
2123
- function meshSource(){
2226
+ function meshSource(slot=parts?.value()?.slot??stageDraftSelection?.slot??null){
2124
2227
  if(hasStageModel()&&!partModel)return {ok:false as const,code:'MESH_EDIT_RIG_UNAVAILABLE: the compiled model document is still loading'};
2125
- return meshEditSource({slot:parts?.value()?.slot??stageDraftSelection?.slot??null,model:hasStageModel()?partModel:null,pose:slot=>assets?readSetupPose(assets,slot,document.createElement('div')):null,mapping:chestMapping});
2228
+ return meshEditSource({slot,model:hasStageModel()?partModel:null,pose:slot=>assets?readSetupPose(assets,slot,document.createElement('div')):null,mapping:chestMapping});
2126
2229
  }
2127
2230
  async function exportMesh(doc:MeshEditDocument):Promise<void> {
2128
2231
  const text=meshEditText(doc),digest=await sha256Hex(text);
@@ -3110,7 +3213,11 @@ function commentCaptureRefusal():string|null {
3110
3213
  }
3111
3214
  function setupComments():void {
3112
3215
  if(host?.direction||host?.record){restoreRecordComments();liveIssueCount=()=>recordComments.length;if(host?.direction)dirty=dirty||recordComments.length>0;}
3113
- comments=bindStageComments<CommentRow,CommentPose>({general:host?.record||host?.direction?{create:summary=>({id:crypto.randomUUID(),summary}),matches:row=>!('target' in row)}:undefined,listHost:el('comments-list-host'),openList:openReview,hasPicture:()=>!hasTransientQuestionImage(screenRoot),toolbar:el('stage-comment').parentElement!,viewports:host?.record&&!host.record.hasPicture?{}:{rig:el('rig-viewport'),reference:el('reference-viewport')},
3216
+ if(host?.verdictComments){restoreRecordComments();if(host.verdictComments.rows.length)markDirty();}
3217
+ comments=bindStageComments<CommentRow,CommentPose>({general:host?.record||host?.direction||host?.verdictComments?{
3218
+ create:summary=>({id:crypto.randomUUID(),summary}),matches:row=>!('target' in row),
3219
+ ...(host.verdictComments?{rows:host.verdictComments.rows,available:host.verdictComments.available,refusal:()=>readOnly}:{}),
3220
+ }:undefined,listHost:el('comments-list-host'),openList:openReview,hasPicture:()=>!hasTransientQuestionImage(screenRoot),toolbar:el('stage-comment').parentElement!,viewports:host?.record&&!host.record.hasPicture?{}:{rig:el('rig-viewport'),reference:el('reference-viewport')},
3114
3221
  pose:view=>{
3115
3222
  if(hasTransientQuestionImage(screenRoot))return null;
3116
3223
  if(view!=='rig'&&view!=='reference')return null;const workspaceMode=document.querySelector<HTMLElement>('[data-mode][aria-pressed="true"]')?.dataset.mode;if(workspaceMode!=='rig'&&workspaceMode!=='playback')return null;const camera=numericView().cameras[view],pane=el(view+'-viewport');if(!camera||pane.clientWidth<=0||pane.clientHeight<=0)return null;
@@ -3118,9 +3225,10 @@ function setupComments():void {
3118
3225
  return {mode:workspaceMode==='playback'?'animate':'setup',capture:{pane,root:view==='rig'?el('rig-root'):undefined,images:view==='reference'||layers.images,canvas:view==='rig'&&renderer instanceof CanvasRenderer?renderer.canvas:undefined,backend:renderer instanceof CanvasRenderer?renderer.backendActive:renderer?.meshBackendActive??'canvas2d'},camera,frame:index===null?null:{index,basis:'producer'},...(index===null?{timeBasis:timeOnlyBasis}:{}),time:current,animation:animation||null,turn:turnPad?.snapshot()??null,sourceHash:data.sourceHash,modelHash:view==='reference'?null:stageModelHash,referenceHash,referenceId,rig:data.manifest.id,...(view==='reference'?{media:video??el('reference-content').querySelector('img')??undefined}:{posed:parts?.frame('single'),assets:assets??undefined})} as CommentPose;
3119
3226
  },
3120
3227
  pause:async()=>{const running=playing||!!video&&!video.paused;pause();if(running&&video&&video.readyState>=1){seekingControl=true;try{await inspectControlTime(time,new AbortController().signal);}finally{seekingControl=false;}}if(turnPad)turnPad.restore({...turnPad.snapshot(),held:true},false);},bookmark:inspectionBookmark,restore:(b,timed)=>restoreInspection(parseBookmark(b,inspectionBinding()),new AbortController().signal,!!timed),feedback:()=>host?.record||host?.direction?recordComments:session.feedback,
3121
- locked:host?.record?()=>false:host?.direction?id=>submittedDirectionComments.has(id):isSubmittedFeedback,add:f=>{if(host?.record||host?.direction)recordComments.push(f);else session.feedback.push(f as Feedback);},changed:()=>{if(host?.record||host?.direction){recordCommentsChanged();if(host?.direction){markDirty();comments?.refresh();}return;}markDirty();renderProposals();return persistence?.save();},error:value=>message(value,true),
3228
+ locked:host?.record?()=>false:host?.direction?id=>submittedDirectionComments.has(id):isSubmittedFeedback,add:f=>{if(host?.record||host?.direction)recordComments.push(f);else session.feedback.push(f as Feedback);},changed:()=>{if(host?.record||host?.direction){recordCommentsChanged();if(host?.direction){markDirty();comments?.refresh();}return;}if(host?.verdictComments)persistRecordComments();markDirty();renderProposals();return persistence?.save();},error:value=>message(value,true),
3122
3229
  refusal:()=>host?.record&&!host.record.hasPicture?null:commentCaptureRefusal(),blocked:()=>saving||!!persistence?.restoring()||seekingControl||!!video?.seeking||!!rebuildBusy||!!appliedOnStage,shortcutBlocked:()=>!!meshEditor?.active()
3123
3230
  });
3231
+ if(host?.verdictComments)renderProposals();
3124
3232
  }
3125
3233
 
3126
3234
  /** Open the existing precision instruments only after re-reading the same displayed draft binding. */