rig-review 3.7.0 → 4.0.1

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.
Files changed (109) hide show
  1. package/README.md +3 -3
  2. package/docs/DESIGN.md +145 -74
  3. package/docs/PANELS.md +20 -12
  4. package/docs/PARTS_VIEW.md +133 -76
  5. package/docs/REVIEW_PACKAGE.md +446 -100
  6. package/docs/STABILITY.md +132 -198
  7. package/docs/WORKFLOWS.md +41 -120
  8. package/package.json +4 -3
  9. package/skills/rig-review/SKILL.md +41 -27
  10. package/src/build.ts +10 -2
  11. package/src/cli.ts +17 -16
  12. package/src/comment-crops.ts +6 -1
  13. package/src/compare-html.ts +22 -24
  14. package/src/compare-server.ts +1 -1
  15. package/src/compare-session.ts +41 -3
  16. package/src/correction-handoff.ts +27 -4
  17. package/src/create-pin-gate.ts +3 -0
  18. package/src/direction-inspection.ts +6 -2
  19. package/src/feedback-export.ts +68 -1
  20. package/src/front.ts +5 -200
  21. package/src/handoff.ts +1 -1
  22. package/src/interview-routes.ts +1 -1
  23. package/src/interview-scene.ts +3 -3
  24. package/src/job-act.ts +77 -73
  25. package/src/job-api.ts +326 -13
  26. package/src/job-checkpoint-evidence.ts +113 -0
  27. package/src/job-cli.ts +27 -14
  28. package/src/job-contract.ts +284 -62
  29. package/src/job-front.ts +192 -61
  30. package/src/job-host.ts +23 -4
  31. package/src/job-session.ts +109 -24
  32. package/src/job-source.ts +227 -58
  33. package/src/job-store.ts +80 -6
  34. package/src/job-worker.ts +1 -47
  35. package/src/joined-project.ts +61 -4
  36. package/src/manifest.ts +32 -4
  37. package/src/open-workspace.ts +12 -12
  38. package/src/open.ts +19 -12
  39. package/src/parts-comment-crops.ts +126 -31
  40. package/src/parts-comment.ts +351 -28
  41. package/src/parts-server.ts +19 -7
  42. package/src/parts-view.ts +588 -109
  43. package/src/scene-inspection.ts +50 -0
  44. package/src/server.ts +31 -22
  45. package/src/session.ts +58 -0
  46. package/src/stage-comment.ts +48 -1
  47. package/src/stage-parts.ts +23 -11
  48. package/web/animation-inspection.ts +1 -1
  49. package/web/bones-panel.ts +1 -3
  50. package/web/catalog-en.ts +175 -39
  51. package/web/catalog-ko.ts +175 -39
  52. package/web/cloth-panel.ts +1 -2
  53. package/web/compare.css +3 -13
  54. package/web/compare.html +3 -3
  55. package/web/compare.ts +69 -64
  56. package/web/cuts-panel.ts +1 -3
  57. package/web/density-strip-panel.ts +1 -2
  58. package/web/direction-panel.ts +22 -6
  59. package/web/i18n.ts +13 -1
  60. package/web/idle-panel.ts +1 -2
  61. package/web/index.html +1 -5
  62. package/web/inspection-persistence.ts +2 -1
  63. package/web/inspector-blocks.ts +149 -40
  64. package/web/instance-access.ts +24 -5
  65. package/web/interview-panel.ts +224 -175
  66. package/web/job-rig-capture.ts +164 -21
  67. package/web/job-rig-screen.ts +344 -0
  68. package/web/job-session.ts +611 -1443
  69. package/web/main.ts +614 -151
  70. package/web/mesh-panel.ts +1 -2
  71. package/web/owner-workspace.ts +88 -109
  72. package/web/part-selection.ts +47 -6
  73. package/web/part-thumbnails.ts +20 -6
  74. package/web/parts-render.ts +26 -19
  75. package/web/parts-viewport-provider.ts +181 -7
  76. package/web/physics-panel.ts +1 -2
  77. package/web/readings-panel.ts +1 -2
  78. package/web/requirements-panel.ts +1 -3
  79. package/web/retained-frame-stage.ts +105 -0
  80. package/web/retarget-panel.ts +2 -3
  81. package/web/rig-fields-panel.ts +1 -2
  82. package/web/rig-host.ts +64 -0
  83. package/web/rig-viewport-provider.ts +65 -16
  84. package/web/scene-plates.ts +57 -4
  85. package/web/stage-comments.ts +103 -46
  86. package/web/styles.css +117 -63
  87. package/web/view-controls.ts +201 -12
  88. package/web/viewport-capture.ts +12 -2
  89. package/web/viewport-controller.ts +107 -27
  90. package/web/viewport-pair.ts +2 -1
  91. package/web/workspace-preferences.ts +5 -4
  92. package/web/workspace-ui.ts +151 -19
  93. package/src/front-worker.ts +0 -2
  94. package/src/interview-server.ts +0 -54
  95. package/src/job-hub.ts +0 -304
  96. package/src/job-image-set.ts +0 -50
  97. package/web/interview.css +0 -28
  98. package/web/interview.html +0 -17
  99. package/web/interview.ts +0 -40
  100. package/web/job-hub.css +0 -14
  101. package/web/job-hub.html +0 -5
  102. package/web/job-hub.ts +0 -179
  103. package/web/owner-workspace.css +0 -14
  104. package/web/owner-workspace.html +0 -5
  105. package/web/parts-flags.ts +0 -48
  106. package/web/parts.css +0 -104
  107. package/web/parts.html +0 -49
  108. package/web/parts.ts +0 -604
  109. package/web/stage-nav.ts +0 -136
package/web/main.ts CHANGED
@@ -1,9 +1,18 @@
1
+ import {bindScenePlates,loadScenePlates,takeSample} from './scene-plates.ts';
2
+ import type {SceneInspection} from '../src/scene-inspection.ts';
3
+ import type {InterviewSubjectEntry} from '../src/joined-project.ts';
4
+ import {mountJobScreen,joinedInterviewForms,mediaReady,jobSubmissionRefusal} from './job-session.ts';
5
+ import {partsIssueComments,parsePartsIssue,assertPartsIssueBinding} from '../src/parts-comment.ts';
6
+ import type {JobForm} from './job-session.ts';
7
+ import {bindWorkspaceDrawer} from './workspace-layout.ts';
8
+ import {captureRigRestStill,rigRestCanvas} from './job-rig-capture.ts';
9
+ import {createPartsViewportProvider,bindPartsSubject,paintRigDifference,type PartsSubjectEntry,type PartsSubjectSession} from './parts-viewport-provider.ts';
10
+ import {rigWorkspaceMarkup,rigFeedbackMarkup,sharedViewToolsMarkup,sharedCommentMarkup} from '../src/compare-html.ts';
1
11
  import {bindDirectionPanel} from './direction-panel.ts';
2
12
  import {bindWorkspaceVisibility} from './workspace-visibility.ts';
3
13
  import type {DirectionInspection} from '../src/direction-inspection.ts';
4
- import {bindStageNav} from './stage-nav.ts';
5
- import {timeOnlyBasis,feedbackTimingLabel,requireFeedbackFrames,isTimeOnlyFeedback} from '../src/stage-comment.ts';
6
- import {bindStageComments,type CommentPose} from './stage-comments.ts';
14
+ import {parseStageComment,feedbackItemComments,projectComments,timeOnlyBasis,unprojectMark,feedbackTimingLabel,requireFeedbackFrames,isTimeOnlyFeedback} from '../src/stage-comment.ts';
15
+ import {bindStageComments,type CommentRow,type CommentPose} from './stage-comments.ts';
7
16
  import {discoverTurnDials,TurnState} from '../src/turn-pad.ts';
8
17
  import {bindTurnPad,type TurnPad} from './turn-pad.ts';
9
18
  import {PartExplorer,loadPartModel,partBounds,partCatalog,type PartEntry} from './part-selection.ts';
@@ -14,7 +23,7 @@ import {createViewportController,createViewportState,type CameraTarget} from './
14
23
  import {createRigViewportProvider,rigPanCarry} from './rig-viewport-provider.ts';
15
24
  import {mountViewportPair} from './viewport-pair.ts';
16
25
  import {rendererStatus} from './renderer-status.ts';
17
- import {bindAppearance,syncStageLayout,bindInspectorTabs,idleAvailable,initialIdleAnimation,automaticIdlePreview,bindLayerShortcuts,describeLayerToggles,type ViewPoint} from './view-controls.ts';
26
+ import {panelMake,createRigLayerControls,createViewControls,inspectionViewSwitch,actionButton,bindAppearance,syncStageLayout,bindInspectorTabs,idleAvailable,initialIdleAnimation,automaticIdlePreview,idlePreviewOnOpen,bookmarkCameraKept,bindLayerShortcuts,describeLayerToggles,type ViewPoint} from './view-controls.ts';
18
27
  import {RigOverlays,type OverlayCircle,type OverlayMarker,type OverlayRegion,type OverlaySnapshot} from './rig-overlays.ts';
19
28
  import {bindMeshPanel,type MeshPanel} from './mesh-panel.ts';
20
29
  import {bindDensityStrip,type DensityStripPanel,type DensityStripViewLike} from './density-strip-panel.ts';
@@ -35,13 +44,14 @@ import type {RetargetFlags} from '../src/retarget.ts';
35
44
  import {appliedCheckState,renderAppliedHistory,isPatchJob,recordFor,refusedText,restoredOutcomeForJob,retargetStage,undoControl,type AppliedHistoryView,type UndoView,type AnyJobView,appliedRecord,deltaAppliedRecord,deltaOutcomeLine,MESH_DELTA_APPLIED_SOURCE,chestPartFields,chestStatusForPart,chestSeed,designatedRegions,handoffText,landmarksRequest,noContourReason,seedLandmarks,makePatch,outcomeLine,patchAppliedRecord,patchOutcomeLine,pickBustPart,pickPart,runRebuild,seedFields,stageModel,type AppliedDelta,type AppliedPatch,type AppliedRecord,type DeltaJobView,type DeltaRequestBody,type ConfigPatch,type PatchJobView,type RebuildJobView,type RebuildRefusal,type RebuildRequestBody,type RebuildStatusView} from './rebuild-client.ts';
36
45
  import {meshEditBinding,meshEditText,type MeshEditDocument} from '../src/mesh-edit.ts';
37
46
  import {chestRegionsBinding,cropWorldMapping,type CropWorldMapping} from '../src/chest-regions.ts';
38
- import {bindWorkspaceUI,selectedInspector,type WorkspaceUI} from './workspace-ui.ts';
39
- import {setSourceAttribute,setSourceText,sourceTextContent,t,tr} from './i18n.ts';
47
+ import {mountWorkspaceShell,mountStatusBar,bindWorkspaceUI,bindHeaderModeAvailability,selectedInspector,type WorkspaceUI} from './workspace-ui.ts';
48
+ import {setSourceAttribute,setSourceText,sourceTextContent,onLanguageChange,t,tr} from './i18n.ts';
40
49
  import {holdScrubBox,releaseScrubBox,scrubBox} from './scrub-box.ts';
41
- import {bindInspectorBlocks,activeBlocksUI,restoreActiveBlocksUI,type InspectorBlocks} from './inspector-blocks.ts';
50
+ import {mountRigInspector,bindInspectorBlocks,activeBlocksUI,restoreActiveBlocksUI,type InspectorBlocks} from './inspector-blocks.ts';
42
51
  import {connectControl} from './control.ts';
43
52
  import {connectLiveWindow} from './live-connection.ts';
44
53
  import {pageInstanceAccess,readOnlyReason} from './instance-access.ts';
54
+ import {rigHost,type RigHostStage} from './rig-host.ts';
45
55
  import {controlComparison,type ControlCommand,type ControlInspection,type ControlView} from '../src/control.ts';
46
56
  import {singleEligibility,videoReferenceAt,type InputState,type SingleLayout} from '../src/comparison-eligibility.ts';
47
57
  import {parseBookmark,connectInspectionPersistence,serializableView,restoredZoom,restoreTransaction,captureInputs,restoreInputs,type InspectionBookmark,type InspectionBinding,type PersistenceConnection} from './inspection-persistence.ts';
@@ -52,8 +62,8 @@ import type { Checkpoint, Json, Reference, ReviewedSource, ReviewManifest } from
52
62
  import type { Feedback, ReviewSession } from '../src/session.ts';
53
63
  import type { ReportEvent, ReportSeeds } from '../src/report.ts';
54
64
  import { frameAtTime, lastFrame as lastProducerFrame, rigPaneLabel, timeAtFrame, transportClock, type StageClock } from '../src/frame-clock.ts';
55
- import { feedbackLastFrame, feedbackTargetNames, validateFeedbackSelection, type FeedbackCatalog } from '../src/feedback-validation.ts';
56
- import { eventCoordinates, eventSeekTime, eventSelection, eventTimingLabel, reportCounts, reportDraftForMarker, targetLabel } from './report-view.ts';
65
+ import { feedbackLastFrame, feedbackTargetNames, validateFeedbackSelection, validateTimedFeedbackSelection, type FeedbackCatalog } from '../src/feedback-validation.ts';
66
+ import { eventCoordinates, eventSeekTime, eventSelection, eventTimingLabel, reportCounts, targetLabel } from './report-view.ts';
57
67
  import type { StripInterval, StripRequest } from '../src/strip.ts';
58
68
  import {createWindModel,environmentFor,windReadout,RUNTIME_START_READOUT,joltPacket,dueJolts,dragImpulse,loadModelDocument,environmentContext,environmentJson,type JoltStep,type WindSnapshot,type WindState} from '../src/environment.ts';
59
69
  import {tuningRows,readoutRows,type InspectedCheckView} from '../src/physics-tuning.ts';
@@ -74,12 +84,19 @@ import {assertRigFieldOps,RIG_FIELDS_READOUT_BARS,TURN_BONE} from '../src/rig-fi
74
84
  import {IDLE_READOUT_BARS,type LocalChannel} from '../src/idle-tracks.ts';
75
85
  import type {PatchOp} from '../src/config-patch.ts';
76
86
 
77
- interface ReviewResponse { 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 } }
87
+ /** Mount the existing composition again for a live publication; each instance owns its source-bound state. */
88
+ export function mountRigScreen():{dispose():void} {
89
+ const screenRoot=document.getElementById('app')!;
90
+ const lifecycle=new AbortController();
91
+ let suspended=false,disposed=false,frameHandle=0,navigationMissing=false;
92
+ let publicEditor:unknown;
93
+ let workspace:WorkspaceUI|null=null;
94
+ 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 } }
78
95
  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 }[] }
79
96
  interface SequenceJoint { state: 'observed' | 'occluded' | 'missing' | 'inferred'; at?: [number, number]; score?: number }
80
97
  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 }
81
98
  const el = <T extends HTMLElement = HTMLElement>(id: string): T => {
82
- const node = document.getElementById(id);
99
+ const node = id==='app'?screenRoot:screenRoot.querySelector<HTMLElement>('#'+id)??workspace?.element(id);
83
100
  if (!node) throw new Error(`Missing UI element: ${id}`);
84
101
  return node as T;
85
102
  };
@@ -91,21 +108,67 @@ const titledIds = new Set(['message', 'player-state', 'layout-state', 'renderer-
91
108
  const text = (id: string, value: string) => { const node = el(id); setSourceText(node, value); if (titledIds.has(id)) setSourceAttribute(node, 'title', value); };
92
109
  const option = (value: string, label: string) => { const item = document.createElement('option'); item.value = value; item.textContent = label; return item; };
93
110
  const errorText = (error: unknown) => error instanceof Error ? error.message : String(error);
111
+ // Capability is consumed before shell composition or any URL-dependent binding.
112
+ // A live job (#709) hosts this screen for a rig subject: its routes, its session and its submit.
113
+ const host=rigHost(),access=host?.access??pageInstanceAccess();
114
+ const partsOnly=host?.subject==='parts'||screenRoot.dataset.reviewScreen==='parts';
115
+ const app=el('app');app.innerHTML=rigWorkspaceMarkup+rigFeedbackMarkup;
116
+ const rigStatusBar=mountStatusBar({
117
+ message:'Loading local review package…',
118
+ readouts:[
119
+ panelMake('span',{id:'player-state',className:'subtle',textContent:'No rig supplied'}),
120
+ panelMake('span',{id:'layout-state',className:'subtle',textContent:'Loading inputs…'}),
121
+ panelMake('span',{id:'renderer-state',className:'subtle',title:'DOM images for rigid parts; WebGL meshes when available, Canvas2D fallback.',textContent:'Not rendered'}),
122
+ panelMake('span',{id:'layer-state',className:'hint',textContent:'No rig supplied'}),
123
+ panelMake('span',{id:'idle-state',className:'hint',textContent:'Idle preview unavailable'}),
124
+ panelMake('span',{id:'control-state',className:'hint'}),
125
+ panelMake('div',{className:'draft-notice'},panelMake('span',{id:'draft-state'}),panelMake('div',{id:'draft-recovery'})),
126
+ ],
127
+ source:panelMake('div',{className:'status-source'},
128
+ panelMake('details',{className:'view-region'},panelMake('summary',{},'View region'),
129
+ panelMake('div',{className:'view-region-body'},
130
+ panelMake('span',{className:'hint',textContent:'Numeric source region · opening this link restores a paused inspection'}),
131
+ panelMake('pre',{id:'view-coordinates',className:'numeric-view'}),
132
+ panelMake('p',{className:'hint',textContent:'Sync cameras links fit-relative zoom and viewport-relative pan across visible panes. Turn it off to inspect each pane independently. Toolbar zoom and Fit use the last active pane. Hold Space while dragging a video to pan without taking over its native controls.'}))),
133
+ panelMake('span',{id:'source-hash',className:'subtle'})),
134
+ });
135
+ app.querySelector<HTMLElement>('[data-workspace-status]')!.replaceWith(rigStatusBar.footer);
136
+ for(const id of ['layout-state','idle-state','control-state','draft-state'])el(id).setAttribute('role','status');
137
+ el('layout-state').setAttribute('aria-label','Effective layout');el('renderer-state').setAttribute('aria-label','Last draw backend');el('draft-state').setAttribute('aria-live','polite');el('view-coordinates').setAttribute('aria-label','Current numeric inspection region');
138
+ const shell=mountWorkspaceShell({compatibility:'rigStep1',embedded:new URLSearchParams(location.search).has('stageEmbed')&&!location.pathname.endsWith('/stage-interview.html')});app.prepend(shell.header);
139
+ el('app').querySelector<HTMLElement>('[data-workspace-comment]')!.innerHTML=sharedCommentMarkup;
140
+ el('app').querySelector<HTMLElement>('[data-workspace-layers]')!.append(createRigLayerControls());
141
+ el('app').querySelector<HTMLElement>('[data-workspace-view-tools]')!.innerHTML=sharedViewToolsMarkup;
142
+ const controls=createViewControls({layout:'rigStep1',viewSwitch:inspectionViewSwitch(chooseInspectionView,true)}),cameraControls=el('app').querySelector<HTMLElement>('[data-workspace-camera]')!;cameraControls.append(controls.syncLabel,controls.zoomGroup!);
143
+ const primaryToolbar=app.querySelector<HTMLElement>('.viewbar')!;primaryToolbar.classList.add('workspace-main-toolbar');
144
+ const secondaryToolbar=document.createElement('div');secondaryToolbar.className='workspace-secondary-toolbar';secondaryToolbar.append(app.querySelector<HTMLElement>('[data-workspace-layers]')!,app.querySelector<HTMLElement>('[data-workspace-view-tools]')!);primaryToolbar.after(secondaryToolbar);
145
+ for(const event of ['click','change'])secondaryToolbar.addEventListener(event,()=>{if(rigDifference){leaveRigDifference();renderLayout();}},true);
146
+ const rigInspector=mountRigInspector();
147
+ const rigAsk=panelMake('button',{className:'workspace-act-ask',id:'workspace-pending-ask',hidden:true});rigAsk.type='button';rigInspector.act.prepend(rigAsk);
94
148
  mountViewportPair(el('stage-layout'));
95
149
  const viewportState=createViewportState();
96
- const viewport=createViewportController(createRigViewportProvider({el,player:()=>player,assets:()=>assets,referenceSize:()=>referenceSize,view:()=>view,referenceGeneration:()=>referenceGeneration,parts:()=>parts,text,message,redrawOverlay},viewportState),viewportState);
150
+ const partsCanvas=document.createElement('canvas'),partsReference=document.createElement('canvas');partsCanvas.width=partsCanvas.height=partsReference.width=partsReference.height=0;
151
+ let partsSubject:ReturnType<typeof bindPartsSubject>|null=null;
152
+ let rigDifference:{assets:ModelAssets;painting:HTMLImageElement;camera:ReturnType<typeof createViewportState>;hidden:Map<HTMLElement,boolean>;label:string;bookmark:InspectionBookmark}|null=null;
153
+ let rigDifferenceFailure:string|null=null;
154
+ const rigRaster={el,canvas:partsCanvas,message,reference:()=>null,frameSize:()=>({w:partsCanvas.width,h:partsCanvas.height}),active:()=>!!rigDifference};
155
+ if(partsOnly){partsCanvas.id='parts-canvas';el('rig-root').append(partsCanvas);el('reference-content').append(partsReference);}
156
+ let sceneComposite:ReturnType<typeof bindScenePlates>|undefined;
157
+ const activeScene=()=>sceneComposite&&data.direction&&(!stageSource||stageSource.url===inspectedModel?.url)?data.direction:undefined;
158
+ const sceneBox=()=>{const direction=activeScene();return direction?takeSample(direction,time).box:null;};
159
+ const viewport=createViewportController(partsOnly?createPartsViewportProvider({el,canvas:partsCanvas,message,reference:()=>partsReference.width>0?partsReference:null,frameSize:target=>partsSubject?.frameSize(target)??null},viewportState):createRigViewportProvider({fitLabel:'Fit',framingBox:sceneBox,el,player:()=>player,assets:()=>assets,referenceSize:()=>referenceSize,view:()=>view,referenceGeneration:()=>referenceGeneration,parts:()=>parts,text,message,redrawOverlay,raster:rigRaster},viewportState),viewportState);
97
160
  const {fitCamera,paneFrame,availableCamera,alignCameras,renderCameraControls,setCameraSync,cameraAction,updateCamera,fitActiveCamera}=viewport;
98
161
  // First, before any URL use: take the `#cap=` handoff into memory/session storage and strip it.
99
- const access = pageInstanceAccess();
100
- connectLiveWindow(access);
162
+ if(!host)connectLiveWindow(access);
101
163
  let readOnly: string | null = null;
164
+ let actReadOnly: string | null = null;
102
165
  let data: ReviewResponse;
103
166
  let directionPanel:ReturnType<typeof bindDirectionPanel>|undefined;
104
167
  let session: ReviewSession;
105
168
  let dirty = false;
106
169
  let saving = false;
107
170
  let stripBusy = false;
108
- let persistence:PersistenceConnection|null=null,submittedBaseline:ReviewSession|null=null,draftConflict=false;
171
+ let persistence:PersistenceConnection|null=null,submittedBaseline:ReviewSession|null=null,draftConflict=false,draftStatus:string|null=null;
109
172
  let checkpoint: Checkpoint | undefined;
110
173
  let assets: ModelAssets | null = null;
111
174
  let player: RigPlayer | null = null;
@@ -120,6 +183,9 @@ let lastFrame = 0;
120
183
  /** #346: wall-clock seconds accumulated toward the next fixed playback step. */
121
184
  let playbackCarry = 0;
122
185
  let comments:ReturnType<typeof bindStageComments>|null=null;
186
+ const recordComments:CommentRow[]=[];
187
+ let recordCommentKey='';
188
+ const submittedDirectionComments=new Set<string>();
123
189
  let view: 'compare' | 'reference' | 'rig' = 'compare';
124
190
  // Requested layout persists in the source-bound draft; the effective one follows actual load events only.
125
191
  let rigInput:InputState={state:'pending'},referenceInput:InputState={state:'absent'},effectiveView:SingleLayout|null=null;
@@ -145,7 +211,8 @@ function hasStageModel():boolean{return Boolean(data.manifest.model||(data?.capa
145
211
  /** Apply · Rebuild (#99): the inspected model's URL, the producer status, and the applied record while its scratch build is on the stage. */
146
212
  let inspectedModel:{url:string;prefix:string;sha256:string}|null=null,rebuildStatus:RebuildStatusView|null=null,appliedOnStage:AppliedRecord|AppliedPatch|AppliedDelta|AppliedRetarget|AppliedAnimation|null=null,rebuildBusy=false,stageModelHash:string|null=null;
147
213
  let appearance:ReturnType<typeof bindAppearance>|null=null;
148
- let workspace:WorkspaceUI|null=null;
214
+
215
+ let inspectorTabs:ReturnType<typeof bindInspectorTabs>|null=null;
149
216
  let inspectorBlocks:InspectorBlocks|null=null;
150
217
  let idleHeld=false;
151
218
  let suspendedPreview=false;
@@ -191,16 +258,21 @@ let readingsPanel:ReadingsPanel|null=null,readingsJob:ReadingsJobView|null=null,
191
258
  /** The world an Apply's reload resumes: wind (clock and active pulse), pending jolts, whether the controls are engaged, gravity. */
192
259
  interface StageWorld {wind:WindState;jolts:JoltStep[];applied:boolean;gravity:number}
193
260
 
194
- function message(value: string, error = false): void {
261
+ function message(value: string, error = false, footerOnly = false, diagnostic?: string): void {
195
262
  text('message', value);
196
263
  el('message').title = value; // the footer truncates long messages
197
264
  el('message').classList.toggle('error', error);
265
+ // A view readout (a Difference count) is not the act's state, so it stays in the footer only.
266
+ if (footerOnly) return;
198
267
  // The modal makes the footer inert; the review dialog repeats the latest message for its reader.
199
268
  text('review-message', value); el('review-message').classList.toggle('error', error);
269
+ // A background refusal names its code and origin on hover; only Submit's own catch changes the act bar.
270
+ if (diagnostic) el('message').title = diagnostic;
200
271
  }
201
272
 
202
273
  async function api<T>(path: string, init?: RequestInit): Promise<T> {
203
274
  const method = (init?.method ?? 'GET').toUpperCase();
275
+ const hosted = host?.read(path, method); if (hosted) return await hosted as T;
204
276
  const response = await fetch(access.route(path), method === 'GET' || method === 'HEAD' ? init : { ...init, headers: access.headers(init?.headers) });
205
277
  if (!response.ok) throw new Error(`${response.status}: ${await response.text()}`);
206
278
  return await response.json() as T;
@@ -222,7 +294,16 @@ function updateSavedState(): void {
222
294
  text('dirty', dirty ? 'Unsubmitted changes' : session.updatedAt ? 'Submitted' : 'Not submitted');
223
295
  el('dirty').classList.toggle('dirty', dirty);
224
296
  button('save').disabled = saving || draftConflict || !!readOnly || session.feedbackWarnings.length > 0;
225
- button('save').title = readOnly ? readOnly : session.feedbackWarnings.length ? 'Delete feedback with validation warnings, then add it again with a valid target.' : '';
297
+ button('save').title = actReadOnly ? actReadOnly : session.feedbackWarnings.length ? 'Delete feedback with validation warnings, then add it again with a valid target.' : '';
298
+ renderDraftState();
299
+ }
300
+
301
+ /** C10: the act bar renders the latest local draft status; rig only classifies it. Nothing renders before the first status. */
302
+ let liveIssueCount=()=>session?.feedback.length??0;
303
+ function renderDraftState(): void {
304
+ const live=host?.reviewState?.(liveIssueCount(),saving);
305
+ if (draftStatus === null && !live) return;
306
+ rigInspector.actBar.setSaveState({ kind: actReadOnly ? 'read-only' : saving ? 'saving' : draftConflict ? 'failed' : dirty ? 'unsaved' : 'saved', text: actReadOnly??live??draftStatus! });
226
307
  }
227
308
 
228
309
  function renderProvenance(): void {
@@ -255,7 +336,7 @@ function renderCheckpoints(): void {
255
336
 
256
337
  async function chooseCheckpoint(point: Checkpoint,initial?:{referenceId?:string;updateUrl:boolean}): Promise<void> {
257
338
  pause(); checkpoint = point; axisInspection = false;
258
- if(initial?.updateUrl!==false){const url = new URL(location.href); url.searchParams.set('checkpoint', point.id); window.history.replaceState(null, '', url);}
339
+ if(!host&&initial?.updateUrl!==false){const url = new URL(location.href); url.searchParams.set('checkpoint', point.id); window.history.replaceState(null, '', url);}
259
340
  if (point.animation) chooseAnimation(point.animation);
260
341
  time = point.time ?? 0;
261
342
  const referenceId=initial?.referenceId??point.reference;
@@ -265,6 +346,8 @@ async function chooseCheckpoint(point: Checkpoint,initial?:{referenceId?:string;
265
346
  viewport.state.zoom = Math.min(8, Math.max(.25, point.camera?.zoom ?? 1));
266
347
  if(viewport.state.cameraSync)viewport.state.activeCamera=player?'rig':'reference';
267
348
  viewport.state.cameraCenter = point.camera ? { x: point.camera.x, y: point.camera.y } : null;
349
+ // A checkpoint without its own camera opens at Fit, held until the panes are measured and until someone moves it.
350
+ if(point.camera)viewport.cancelFit();else viewport.requestFit();
268
351
  seek(time);
269
352
  if (point.axis && player && !input('axis-value').disabled) {
270
353
  select('axis-select').value = point.axis.id; chooseAxis(); input('axis-value').value = String(point.axis.value); applyAxis();
@@ -277,18 +360,60 @@ function renderCheckpoint(): void {
277
360
  text('detail-title', checkpoint?.title ?? 'No checkpoint supplied');
278
361
  text('detail-note', checkpoint?.note ?? 'Record checkpoint notes and outcomes.');
279
362
  const entry = checkpoint ? session.checkpoints[checkpoint.id] : undefined;
280
- el<HTMLTextAreaElement>('checkpoint-note').value = entry?.note ?? '';
281
- el<HTMLTextAreaElement>('checkpoint-note').disabled = !checkpoint;
363
+ el('checkpoint-note').textContent = entry?.note ?? '';
282
364
  for (const radio of document.querySelectorAll<HTMLInputElement>('input[name="outcome"]')) { radio.checked = radio.value === (entry?.outcome ?? 'pending'); radio.disabled = !checkpoint; }
283
365
  }
284
366
 
285
367
  function setView(value: typeof view): void {view=value;renderLayout();}
368
+ function chooseInspectionView(id:string):void {
369
+ if(!partsSubject){
370
+ if(id==='difference'){
371
+ const reason=rigDifferenceReason();if(reason){message(reason,true);renderLayout();return;}
372
+ try{
373
+ const painting=el('reference-content').querySelector<HTMLImageElement>('img')!;
374
+ const still=captureRigRestStill(assets!,{width:painting.naturalWidth,height:painting.naturalHeight});
375
+ const result=paintRigDifference(partsCanvas,still,painting);
376
+ pause();
377
+ if(!rigDifference)rigDifference={assets:assets!,painting,camera:structuredClone(viewport.state),hidden:new Map(),label:sourceTextContent(el('rig-label')),bookmark:inspectionBookmark()};
378
+ partsCanvas.id='rig-difference-canvas';el('rig-root').append(partsCanvas);partsCanvas.hidden=false;
379
+ for(const node of [...el('rig-root').children,...el('rig-viewport').children])if(node instanceof HTMLElement&&node!==partsCanvas&&node!==el('rig-root')&&node!==el('rig-label')&&node!==el('rig-empty')){if(!rigDifference.hidden.has(node))rigDifference.hidden.set(node,node.hidden);node.hidden=true;}
380
+ viewport.cancelFit();viewport.state.cameraFrames={};viewport.state.cameraCenter=null;viewport.state.referenceCenter=null;viewport.state.activeCamera='rig';
381
+ text('rig-label','Difference');setView('rig');viewport.fitActiveCamera('rig');
382
+ message(t('Difference: {0} of {1} pixels differ, compared where the rig draws · rest still vs original painting.',[result.count,result.compared],'en'),false,true);
383
+ }catch(error){leaveRigDifference();rigDifferenceFailure=errorText(error);message(rigDifferenceFailure,true);renderLayout();}
384
+ }else{leaveRigDifference();setView(id as SingleLayout);}
385
+ return;
386
+ }
387
+ const overlay=document.getElementById('parts-overlay') as HTMLInputElement;
388
+ if(id==='difference')overlay.checked=false;
389
+ partsSubject.setComparison(id==='difference'?'difference':overlay.checked?'overlay':'part');
390
+ setView(id==='difference'?'rig':id as SingleLayout);
391
+ }
392
+ /** Availability follows the actual loaded image and declared native rig canvas, never a resized reference. */
393
+ function rigDifferenceReason():string|null {
394
+ if(selectedInspector()!=='rig')return 'RIG_DIFFERENCE_SETUP_ONLY: Difference is available in Setup.';
395
+ if(!assets||!player||rigInput.state!=='loaded')return 'RIG_DIFFERENCE_MODEL_UNAVAILABLE: no compiled rig is loaded.';
396
+ const painting=el('reference-content').querySelector<HTMLImageElement>('img');
397
+ if(referenceInput.state!=='loaded'||!painting?.naturalWidth)return 'RIG_DIFFERENCE_REFERENCE_UNAVAILABLE: select a loaded original painting image.';
398
+ try{rigRestCanvas(assets,{width:painting.naturalWidth,height:painting.naturalHeight});}catch{return 'RIG_DIFFERENCE_NATIVE_SCALE: original painting and declared rig canvas must align at native scale.';}
399
+ return rigDifferenceFailure;
400
+ }
401
+ /** Restore the compiled view without carrying image-space zoom, hidden layers or diagnostic pixels into capture. */
402
+ function leaveRigDifference():void {
403
+ const previous=rigDifference;if(!previous)return;rigDifference=null;
404
+ partsCanvas.remove();for(const [node,hidden]of previous.hidden)node.hidden=hidden;
405
+ viewport.cancelFit();Object.assign(viewport.state,previous.camera);viewport.state.cameraFrames={};viewport.state.cameraLayout='';
406
+ text('rig-label',previous.label);
407
+ }
286
408
  function layoutEligibility(){return singleEligibility({rig:rigInput,reference:referenceInput,requested:view});}
287
409
  /** Unavailable layouts stay visible but disabled with their named reason; no placeholder pane stands in for a missing input. */
288
410
  function renderLayout():void {
411
+ if(rigDifference&&(rigDifferenceReason()||rigDifference.assets!==assets||rigDifference.painting!==el('reference-content').querySelector('img')))leaveRigDifference();
289
412
  const state=layoutEligibility();effectiveView=state.effective;
290
- for(const item of document.querySelectorAll<HTMLButtonElement>('[data-view]')){const layout=item.dataset.view as SingleLayout,reason=state.reasons[layout]??'';item.setAttribute('aria-pressed',String(layout===state.effective));item.disabled=!!reason;item.title=reason;if(reason)item.setAttribute('aria-description',reason);else item.removeAttribute('aria-description');}
291
- const menuLabels={compare:'Side by side',reference:'Reference',rig:'Rig'};text('view-menu-label',menuLabels[state.effective??state.requested]);
413
+ for(const id of controls.viewModeIds)if(id!=='difference')controls.setDisabled(id,state.reasons[id as SingleLayout]??null);
414
+ controls.setMode(rigDifference||partsSubject?.comparison().mode==='difference'?'difference':state.effective,state.effective??state.requested);
415
+ 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');}
416
+ if(!partsSubject){controls.setDisabled('difference',tr(rigDifferenceReason()??'')||null);if(rigDifference)controls.setMode('difference');}
292
417
  el('reference-pane').hidden=state.effective!=='compare'&&state.effective!=='reference';el('rig-pane').hidden=state.effective!=='compare'&&state.effective!=='rig';
293
418
  const shown={compare:'Side by side',reference:'Reference only',rig:'Rig only'};
294
419
  text('layout-state',state.effective===null?`No input rendered · ${state.reasons.compare??''}`:state.effective===state.requested?shown[state.effective]:`${shown[state.effective]} · ${shown[state.requested]} unavailable: ${state.reasons[state.requested]??''}`);
@@ -362,6 +487,7 @@ function renderSequenceFrame(): void {
362
487
  }
363
488
 
364
489
  async function showReference(id: string): Promise<void> {
490
+ rigDifferenceFailure=null;leaveRigDifference();
365
491
  const generation = ++referenceGeneration;
366
492
  video?.pause(); video = null;controlledVideoSample=null;delete viewport.state.cameraFrames.reference; viewport.state.referenceCenter=null; referenceSize = null; sequence = null; sequenceSvg = null; selectedPerson=''; lastPoseFrame = -1; el('person-control').hidden = true;
367
493
  const content = el('reference-content'); content.replaceChildren();
@@ -466,10 +592,11 @@ function renderFrameTransport(): void {
466
592
  }
467
593
 
468
594
  function activeTransportClock() {
595
+ if(activeScene())return null;
469
596
  const active = player && player.current !== animation ? '' : animation;
470
597
  return transportClock({ clock: data.report?.clock, animation: data.report?.animation }, active, !!player, stageClock, stageModelHash);
471
598
  }
472
- function activeFrameClock() { return activeTransportClock()?.clock ?? null; }
599
+ function activeFrameClock() { return activeScene()?null:activeTransportClock()?.clock ?? null; }
473
600
 
474
601
  function seekFrame(frame: number): void {
475
602
  const exact = timeAtFrame(activeFrameClock(), frame);
@@ -481,28 +608,35 @@ function seekFrame(frame: number): void {
481
608
  }
482
609
 
483
610
  function drawRig(action:()=>void):void {
611
+ if(rigDifference&&rigDifference.assets!==assets){leaveRigDifference();renderLayout();}
484
612
  inDrawRig=true;
485
- try{action();parts?.present('single');if(player&&inspectionSourceState==='ready')animationPanel?.capture(player,parts?.frame('single'));else animationPanel?.capture(null,undefined);text('renderer-state',rendererStatus(player?.renderer??null,'succeeded').label);redrawOverlay(true);}
613
+ try{const box=sceneBox();if(box&&player?.renderer instanceof CanvasRenderer)player.renderer.viewport=box;action();if(box&&player){sceneComposite?.draw(player,box);}parts?.present('single');if(box)viewport.fitCamera();if(player&&inspectionSourceState==='ready')animationPanel?.capture(player,parts?.frame('single'));else animationPanel?.capture(null,undefined);text('renderer-state',rendererStatus(player?.renderer??null,'succeeded').label);redrawOverlay(true);}
486
614
  catch(error){animationPanel?.capture(null,undefined);overlays?.clear();text('renderer-state',rendererStatus(null,'failed').label);throw error;}
487
615
  finally{inDrawRig=false;}
488
616
  }
489
617
 
490
618
  function chooseAnimation(name: string, move: ClipMove = { kind: 'choose' }): void {
619
+ if(rigDifference){leaveRigDifference();renderLayout();}
491
620
  pause(); animation = name; axisInspection = false; el('angle-panel').hidden = true;
492
621
  const runtimeAnimation = assets?.animations.find(item => item.name === name);
493
- duration = clipDuration(name);
622
+ duration = activeScene()?.take.duration??clipDuration(name);
494
623
  select('animation-select').value = name;
495
624
  // #191: the wind restarts before the clip's first frame is drawn, so the paused stage shows the schedule's t=0 world.
496
- time = 0; clipMoved(move);
497
- if (player && runtimeAnimation) { drawRig(()=>{player!.play(name,{loop:canRepeatIdle()});player!.pause();refreshAnimationInspection();player!.draw();}); }
625
+ time = 0; const scene=activeScene();if(!scene)clipMoved(move);
626
+ if (player && runtimeAnimation) {
627
+ restartSetupPlayer();
628
+ if(scene){player.play(name,{loop:canRepeatIdle()});player.pause();seek(0,move);}
629
+ else drawRig(()=>{player!.play(name,{loop:canRepeatIdle()});player!.pause();refreshAnimationInspection();player!.draw();});
630
+ }
498
631
  else if (player && name){text('renderer-state',rendererStatus(null,'failed').label);message(`Animation "${name}" is not present in the rig.`, true);}
499
632
  renderTransport(); renderCues();renderIdle();
500
633
  }
501
634
 
502
635
  function seek(value: number, move?: ClipMove): void {
636
+ if(rigDifference){leaveRigDifference();renderLayout();}
503
637
  time = duration > 0 ? Math.min(Math.max(0, value), duration) : Math.max(0, value);
504
638
  clipMoved(move ?? { kind: 'seek', to: time });
505
- if (player && player.current) { try { player.seek(time); drawRig(()=>player!.draw()); } catch (error) {text('renderer-state',rendererStatus(null,'failed').label); message(errorText(error), true); } }
639
+ if (player && player.current) { try { player.seek(activeScene()?takeSample(activeScene()!,time).sourceTime:time); drawRig(()=>player!.draw()); } catch (error) {text('renderer-state',rendererStatus(null,'failed').label); message(errorText(error), true); } }
506
640
  if (video && video.readyState >= 1) holdVideoReference(video, referenceGeneration);
507
641
  renderSequenceFrame(); renderTransport();
508
642
  }
@@ -524,8 +658,8 @@ function renderCues(): void {
524
658
  const clip = data.manifest.audio.clips.find(item => item.id === cue.clip);
525
659
  const row = document.createElement('div'); row.className = 'cue';
526
660
  const label = document.createElement('span'); label.textContent = `◇ ${cue.id} · ${cue.time.toFixed(2)} s → ${clip?.label ?? cue.clip}`;
527
- const jump = document.createElement('button'); jump.type = 'button'; jump.textContent = 'Go to cue'; jump.onclick = () => { pause(); seek(cue.time); };
528
- const play = document.createElement('button'); play.type = 'button'; play.textContent = 'Audition'; play.disabled = !clip; play.onclick = () => { void audition(cue.clip); };
661
+ const jump = actionButton('Go to cue', () => { pause(); seek(cue.time); });
662
+ const play = actionButton('Audition', () => { void audition(cue.clip); }, !clip);
529
663
  row.append(label, jump, play); area.append(row);
530
664
  }
531
665
  if (!activeCues().length) area.textContent = 'No linked sound cues.';
@@ -581,8 +715,7 @@ function prefillReportEvent(): void {
581
715
  }
582
716
 
583
717
  function chooseReportEvent(event: ReportEvent): void {
584
- const draft = reportDraftForMarker(selectedReportEvent?.id ?? null, event.id, { category: select('feedback-category').value, summary: input('feedback-summary').value });
585
- select('feedback-category').value = draft.category; input('feedback-summary').value = draft.summary;
718
+ if (selectedReportEvent?.id !== event.id) select('feedback-category').value = '';
586
719
  pause(); selectedReportEvent = event; selectedReportTime = undefined; selectedReportTarget = undefined;
587
720
  const selection = eventSelection(event);
588
721
  const times = select('report-time'); times.replaceChildren();
@@ -633,10 +766,11 @@ function seekReading(clip: string, frame: number, exact: number | null, label: s
633
766
  }
634
767
 
635
768
  function tick(now: number): void {
769
+ if(suspended||disposed||!screenRoot.isConnected)return;
636
770
  // #356: the scrub box is read before this frame writes anything (a read after the writes forces a layout).
637
771
  if (playing) try { holdScrubBox(input('scrub')); tickPlaying(now); } finally { releaseScrubBox(); }
638
772
  else tickHeldPhysics(now);
639
- requestAnimationFrame(tick);
773
+ frameHandle=requestAnimationFrame(tick);
640
774
  }
641
775
 
642
776
  /** Animate steps held physics under the standing environment; wind time and queued jolts stay frozen. */
@@ -660,7 +794,7 @@ function tickPlaying(now: number): void {
660
794
  const stepped = next.steps.reduce((sum, step) => sum + step, 0);
661
795
  // The wrap does what the replaced seek(0) did besides the player: restart the wind clock and re-hold the reference at the wrapped time.
662
796
  if (next.wrapped) { stopAudio(); clipMoved({ kind: 'replay' }); if (video) { if (video.readyState >= 1) holdVideoReference(video, referenceGeneration); void video.play().catch(error => { pause(); message(errorText(error), true); }); } }
663
- if (player && player.current && next.steps.length) { try { stepEnvironment(stepped); drawRig(()=>{ for (const step of next.steps) player!.advance(step); player!.draw(); }); } catch (error) { pause(); message(errorText(error), true); } }
797
+ if (player && player.current && next.steps.length) { try { const direction=activeScene();if(direction){stepEnvironment(stepped);drawRig(()=>{player!.seek(takeSample(direction,time).sourceTime);player!.draw();});}else{stepEnvironment(stepped); drawRig(()=>{ for (const step of next.steps) player!.advance(step); player!.draw(); });} } catch (error) { pause(); message(errorText(error), true); } }
664
798
  if (video && video.readyState >= 1 && time > video.duration) { if (referenceInput.state !== 'out-of-domain') holdVideoReference(video, referenceGeneration); } else if (video && referenceInput.state === 'loaded' && Math.abs(video.currentTime - time) > .15) video.currentTime = time;
665
799
  if (input('sync-audio').checked) for (const cue of activeCues()) if (cueDue(cue.time, previous, next, duration)) void audition(cue.clip);
666
800
  renderSequenceFrame(); renderTransport(); if (next.ended) pause(); lastFrame = now;
@@ -699,6 +833,22 @@ function configurePartSets(keep=''):void {
699
833
  if(keep&&presets.some(set=>set.name===keep)){player!.setSet(keep);picker.value=keep;}
700
834
  }
701
835
 
836
+ /** One creation path for initial load, rebuilds and a post-Setup single-track restart. */
837
+ function createInspectionPlayer(root:HTMLElement,loaded:ModelAssets,mode?:RigPlayer['mode']):RigPlayer {
838
+ const next=new RigPlayer(root,loaded,{mode});
839
+ next.on('event',event=>{text('event-log',`Runtime event: ${event.name} · ${event.time.toFixed(2)} s`);});
840
+ return next;
841
+ }
842
+ /** Public clear composes tracks permanently; restart single-track seeking over the same immutable assets. */
843
+ function restartSetupPlayer(force=false):void {
844
+ const previous=player,loaded=assets;if(!previous||!loaded||!force&&(previous.current!==null||!previous.composed))return;
845
+ const skin=previous.skin,sets=[...previous.activeSets],slots=previous.slots,adjust=previous.adjust,world=previous.environment(),mode=previous.mode;
846
+ const entries=partModel&&inspectionSourceState==='ready'?partCatalog(partModel,data.feedbackCatalog.slots??[]):null;
847
+ previous.dispose();player=createInspectionPlayer(el('rig-root'),loaded,mode);
848
+ player.skin=skin;if(sets.length)player.setSets(sets);player.slots=slots;player.adjust=adjust;player.environment(world);
849
+ setupChestWorld=readSetupChest(player);
850
+ if(entries)parts?.register('single',entries,player,new PartThumbnails(pageRegionTable(partModel),loaded.pageImages));
851
+ }
702
852
  async function initPlayer(initialCheckpoint?:Checkpoint): Promise<void> {
703
853
  text('renderer-state',rendererStatus(null,'pending').label);
704
854
  if (!data.manifest.model) { text('player-state', 'No rig supplied · reference review is available'); return; }
@@ -709,15 +859,15 @@ async function initPlayer(initialCheckpoint?:Checkpoint): Promise<void> {
709
859
  assets = await loadModel({ modelUrl, ...stageLoadInputs(modelUrl,inspectedModel.sha256), resolvePage: (name, url) => {
710
860
  const target = new URL(name, url); if (target.origin !== location.origin || !target.pathname.startsWith(access.route('/assets/'))) throw new Error(`Model page escapes local package: ${name}`); return target.href;
711
861
  } });
712
- player = new RigPlayer(el('rig-root'), assets);
862
+ if(data.scene){sceneComposite=bindScenePlates(data.scene,await loadScenePlates(data.scene,assetUrl));input('idle-repeat').checked=data.direction!.take.loop;input('idle-repeat').disabled=true;}
863
+ player = createInspectionPlayer(el('rig-root'), assets,sceneComposite?'canvas':undefined);
713
864
  setupChestWorld = readSetupChest(player);
714
865
  // Parts inspection is an add-on: a catalog refusal is shown in the explorer and never aborts the rig.
715
866
  try{const catalog=await loadPartModel(modelUrl,data.reviewedSource.rig!.sha256,data.feedbackCatalog.slots??[]);inspectionSourceState='ready';partModel=catalog.model;configureTurnPad(catalog.model);refreshAnimationInspection();weightsView?.refresh();parts?.register('single',catalog.entries,player,new PartThumbnails(pageRegionTable(catalog.model),assets.pageImages));}catch(error){inspectionSourceState='failed';partModel=null;refreshAnimationInspection();parts?.refuseCatalog('single',error);}
716
- player.on('event', event => { text('event-log', `Runtime event: ${event.name} · ${event.time.toFixed(2)} s`); });
717
867
  const animations = select('animation-select'); animations.replaceChildren();
718
868
  for (const item of assets.animations) animations.append(option(item.name, data.manifest.animations.find(a => a.id === item.name)?.label ?? item.name));
719
- animations.disabled = assets.animations.length === 0;
720
- const names=assets.animations.map(clip=>clip.name),initial=initialIdleAnimation(names,initialPlayerAnimation(names,data.initialAnimation??undefined,initialCheckpoint),!!data.initialAnimation||!!initialCheckpoint?.animation||!!initialCheckpoint?.axis);
869
+ animations.disabled = assets.animations.length === 0 || !!data.scene;
870
+ const names=assets.animations.map(clip=>clip.name),initial=data.scene?.animation??initialIdleAnimation(names,initialPlayerAnimation(names,data.initialAnimation??undefined,initialCheckpoint),!!data.initialAnimation||!!initialCheckpoint?.animation||!!initialCheckpoint?.axis);
721
871
  if(initial)chooseAnimation(initial);else drawRig(()=>player!.draw());
722
872
  el('rig-empty').hidden = true; text('player-state', '@rig-c/play · Actual rig');
723
873
  configurePartSets();
@@ -746,8 +896,16 @@ function applyAxis(): void {
746
896
  const value = Number(input('axis-value').value); text('axis-value-label', value.toFixed(3)); seek((value - axis.min) / (axis.max - axis.min) * duration);
747
897
  }
748
898
 
899
+ /** A changed draft with the same id is still editable; only the exact submitted row is locked. */
900
+ function isSubmittedFeedback(id:string):boolean {
901
+ const row=session.feedback.find(item=>item.id===id);
902
+ return !!row&&!!submittedBaseline?.updatedAt&&submittedBaseline.feedback.some(item=>item.id===id&&JSON.stringify(item)===JSON.stringify(row));
903
+ }
904
+
749
905
  function renderProposals(): void {
750
906
  comments?.refresh();
907
+ if(host?.direction){setSourceText(rigInspector.comments.button,`Comments (${recordComments.length})`);return;}
908
+ const count=session.feedback.length;setSourceText(rigInspector.comments.button, `Comments (${count})`);
751
909
  const area = el('proposal-list'); area.replaceChildren();
752
910
  const warnings = el('feedback-warnings'); warnings.hidden = session.feedbackWarnings.length === 0;
753
911
  const unchecked = session.feedback.map(f => appliedCheckRefusal((f.context as Record<string, unknown> | undefined)?.applied)).find(Boolean) ?? null;
@@ -758,7 +916,8 @@ function renderProposals(): void {
758
916
  const title = document.createElement('span'); title.className = 'feedback-heading'; title.textContent = `${feedback.category} · ${feedback.target.kind}:${feedback.target.name} · `;
759
917
  const timing = document.createElement('span'); timing.textContent = feedbackTimingLabel(feedback); heading.append(title, timing);
760
918
  const description = document.createElement('span'); description.className = 'feedback-summary'; description.textContent = feedback.summary;
761
- item.append(heading, description);
919
+ const marked=(feedback.context as any)?.comment?.schema==='rig-review-comment/1';
920
+ if(!marked)item.append(heading, description);
762
921
  const context = feedback.context as Record<string, Json> | undefined;
763
922
  const correction = context?.correction as {path?: string;selector?:{kind?:string}} | undefined;
764
923
  if (correction) {
@@ -774,7 +933,7 @@ function renderProposals(): void {
774
933
  item.append(label);
775
934
  }
776
935
  if ((context?.comment as {schema?: string} | undefined)?.schema === 'rig-review-comment/1' &&
777
- !submittedBaseline?.feedback.some(row => row.id === feedback.id)) {
936
+ !isSubmittedFeedback(feedback.id)) {
778
937
  const describe = document.createElement('button');
779
938
  describe.type = 'button';
780
939
  setSourceText(describe, 'Use as described correction');
@@ -786,8 +945,8 @@ function renderProposals(): void {
786
945
  }
787
946
  for (const warning of session.feedbackWarnings.filter(value => value.id === feedback.id)) { const note = document.createElement('p'); note.className = 'hint'; note.textContent = `Validation warning · ${warning.error}`; item.append(note); }
788
947
  const details = document.createElement('details'), summary = document.createElement('summary'), source = document.createElement('pre'); summary.textContent = 'Saved feedback and inspection context'; source.className = 'feedback-json'; source.textContent = JSON.stringify(feedback, null, 2); details.append(summary, source);
789
- const remove = document.createElement('button'); remove.type = 'button'; remove.textContent = 'Delete'; remove.onclick = () => { session.feedback = session.feedback.filter(item => item.id !== feedback.id); session.feedbackWarnings = session.feedbackWarnings.filter(warning => warning.id !== feedback.id); markDirty(); renderProposals(); };
790
- item.append(details);if((feedback.context as any)?.comment?.schema!=='rig-review-comment/1'||!submittedBaseline?.feedback.some(f=>f.id===feedback.id))item.append(remove); area.append(item);
948
+ const remove = actionButton('Delete', () => { session.feedback = session.feedback.filter(item => item.id !== feedback.id); session.feedbackWarnings = session.feedbackWarnings.filter(warning => warning.id !== feedback.id); markDirty(); renderProposals(); });
949
+ item.append(details);if((feedback.context as any)?.comment?.schema!=='rig-review-comment/1'||!isSubmittedFeedback(feedback.id))item.append(remove); const commentRow=marked?document.querySelector<HTMLElement>(`[data-comment-id="${feedback.id}"]`):null;(commentRow??area).append(item);
791
950
  }
792
951
  updateSavedState();
793
952
  }
@@ -827,9 +986,9 @@ function propose(tool: string): void {
827
986
  angle: { target: 'rig', hint: 'One-line feedback on face or torso angle deformation' }, pose: { target: 'bone', hint: 'One-line feedback on differences from the input pose' }, timing: { target: 'rig', hint: 'One-line feedback on timing in the selected range' }, audio: { target: 'rig', hint: 'One-line feedback on event or audio links' },
828
987
  };
829
988
  const choice = choices[tool]; if (!choice) return;
830
- select('feedback-target-kind').value = choice.target; input('feedback-target-name').value = choice.target === 'rig' ? data.manifest.id : ''; input('feedback-summary').placeholder = choice.hint;
989
+ select('feedback-target-kind').value = choice.target; input('feedback-target-name').value = choice.target === 'rig' ? data.manifest.id : '';
831
990
  renderFeedbackTargets();
832
- showInspector('feedback');input('feedback-summary').focus(); message('Specify a frame range and actual bone or slot name to add feedback. Motion keys are not edited.');
991
+ showInspector('feedback');input('feedback-start').focus(); message('Specify a frame range and actual bone or slot name to add feedback. Motion keys are not edited.');
833
992
  }
834
993
 
835
994
 
@@ -885,6 +1044,44 @@ async function exportStrip(): Promise<void> {
885
1044
  }
886
1045
 
887
1046
 
1047
+ function recordFeedback(summary:string,feedback?:Feedback,correction?:ReturnType<typeof correctionSelection>):void {
1048
+ const start = input('feedback-start').value.trim(), end = input('feedback-end').value.trim(), frameStart = start ? Number(start) : feedback?.frameStart??null, frameEnd = end ? Number(end) : feedback?.frameEnd??null;
1049
+ const name = input('feedback-target-name').value.trim();
1050
+ if(!feedback&&(!start||!end))throw new Error(tr('Enter nonnegative integer start and end frames, with the end at or after the start.'));
1051
+ if (start || end) { if (!start || !end || !Number.isSafeInteger(Number(start)) || !Number.isSafeInteger(Number(end)) || Number(start) < 0 || Number(end) < Number(start)) throw new Error(tr('Enter nonnegative integer start and end frames, with the end at or after the start.')); }
1052
+ if (!['bone', 'slot', 'rig'].includes(select('feedback-target-kind').value) || !['defect', 'quality'].includes(select('feedback-category').value || feedback?.category || '')) throw new Error(tr('Select a target type and defect or quality category.'));
1053
+ if (!name) throw new Error(tr('Enter the actual target name and a one-line summary of up to 1,000 characters.'));
1054
+ const target: Feedback['target'] = { kind: select('feedback-target-kind').value as Feedback['target']['kind'], name };
1055
+ const captured=feedback?.context as Record<string,Json>|undefined;
1056
+ const selectedAnimation = feedback?(typeof captured?.animation==='string'?captured.animation:null):feedbackAnimation();
1057
+ if(feedback&&feedback.frameStart===null&&(start||end))throw new Error(tr('Frame ranges require an explicit producer frame. Leave both fields empty for this seconds-only comment.'));
1058
+ if(frameStart!==null&&frameEnd!==null)validateFeedbackSelection(data.feedbackCatalog, { frameStart, frameEnd, target, animation: selectedAnimation });
1059
+ else validateTimedFeedbackSelection(data.feedbackCatalog,{target,animation:selectedAnimation,time:Number(captured?.time)});
1060
+ const box = assets?.stage ?? player?.bounds();
1061
+ const center = viewport.state.cameraCenter ?? (box ? { x: box.x + box.width / 2, y: box.y + box.height / 2 } : null);
1062
+ session.feedback.push({ id:feedback?.id??crypto.randomUUID(), ...feedback, frameStart, frameEnd, target, category: (select('feedback-category').value || feedback?.category || '') as Feedback['category'], summary, context: {...(feedback?.context as Record<string,Json>),...(turnPad?{turn:JSON.parse(JSON.stringify(turnPad.snapshot())) as Json}:{}),part:parts?.feedback()??null,
1063
+ ...(correction ? { correction } : {}),
1064
+ interval: frameStart===null||frameEnd===null ? null : { frameStart, frameEnd, inclusive: true },
1065
+ checkpoint: checkpoint?.id ?? null, animation: selectedAnimation, time:captured?.time??time, frame:feedback?captured?.frame??null:frameAtTime(activeFrameClock(),time),
1066
+ reference: select('reference-select').value || null, person: selectedPerson || null,
1067
+ sourceTime: sequence ? sequence.frames[0]!.t + time : time,
1068
+ camera: center ? { zoom:viewport.state.zoom, x: center.x, y: center.y, coordinateSystem: 'world-y-up' } : { zoom:viewport.state.zoom, coordinateSystem: 'reference-fit' },
1069
+ view:{...serializableView(numericView()),theme:appearance?.get()??'system',layers:{...layers}},
1070
+ axis: axisInspection ? { id: select('axis-select').value, value: Number(input('axis-value').value) } : null,
1071
+ environment: feedbackEnvironment(),
1072
+ // The exported schedule (#112): the drawn clip's rigc-environment/1 bytes and their sha256, and whether readings and Apply read them.
1073
+ environmentSchedule: feedbackSchedule() as unknown as Json,
1074
+ // The exact last applied designation and the producer's line, only while that scratch build is what is drawn.
1075
+ applied: appliedOnStage ? JSON.parse(JSON.stringify(appliedOnStage)) as Json : null,
1076
+ // The readings chosen (#108): the pairs of the last finished run and the builds they ran on, not their results.
1077
+ readings: readingsContext() as unknown as Json,
1078
+ // The declared requirements (#113): the file by hash and content, and its last check, or null when none are declared.
1079
+ requirements: (requirementsPanel?.context() ?? null) as unknown as Json,
1080
+ reportEvent: selectedReportEvent ? { id: selectedReportEvent.id, field: selectedReportEvent.field, source: { ...selectedReportEvent.source }, frames: selectedReportEvent.frames ? [...selectedReportEvent.frames] : null, exactTime: eventSeekTime(selectedReportEvent, selectedReportTime), targets: selectedReportEvent.targets.map(target => ({ ...target })) } : null,
1081
+ } });
1082
+ }
1083
+
1084
+
888
1085
  function bind(): void {
889
1086
  button('strip-export').onclick = () => { void exportStrip(); };
890
1087
  button('chest-export').onclick = () => { void exportChest(); };
@@ -892,14 +1089,13 @@ function bind(): void {
892
1089
  // A discarded local draft restores the form after its button's own handler; re-read the tool then.
893
1090
  for (const id of ['draft-recovery', 'review-draft-recovery']) el(id).addEventListener('click', () => { renderChest(); restoreEnvironment(); physicsPanel?.restore(); bonesPanel?.restore(); cutsPanel?.restore(); clothPanel?.restore(); idlePanel?.restore(); rigFieldsPanel?.restore(); syncCorrectionStage(); });
894
1091
  for (const id of ['strip-scope', 'strip-reference', 'strip-format']) select(id).onchange = () => stripStatus('Selection changed. Check the ranges, animation and reference video before downloading.');
895
- for (const item of document.querySelectorAll<HTMLButtonElement>('[data-view]')) item.onclick = () => {setView(item.dataset.view as typeof view);const menu=document.getElementById('view-menu') as HTMLDetailsElement|null;if(menu)menu.open=false;};
896
1092
  for (const item of document.querySelectorAll<HTMLButtonElement>('[data-proposal]')) item.onclick = () => propose(item.dataset.proposal ?? '');
897
1093
  select('reference-select').onchange = () => { void showReference(select('reference-select').value); };
898
1094
  select('person-select').onchange = () => { selectedPerson = select('person-select').value; lastPoseFrame = -1; renderSequenceFrame(); };
899
1095
  select('animation-select').onchange = () => {chooseAnimation(select('animation-select').value);if(canRepeatIdle())void playPreview();};
900
1096
  select('part-set').onchange = () => { try { if(!player)return;player.setSet(select('part-set').value || null);drawRig(()=>player!.draw());fitCamera(); } catch (error) {text('renderer-state',rendererStatus(null,'failed').label); message(errorText(error), true); } };
901
1097
  select('axis-select').onchange = chooseAxis; input('axis-value').oninput = applyAxis;
902
- viewport.bindControls();
1098
+ viewport.bindControls(unitScaleMessage);
903
1099
  input('scrub').oninput = () => { pause(); seek(Number(input('scrub').value)); };
904
1100
  input('frame-number').onfocus = pause;
905
1101
  input('frame-number').onkeydown = event => { if (event.key === 'Enter') { event.preventDefault(); const value = input('frame-number').value.trim(); seekFrame(value ? Number(value) : NaN); } };
@@ -918,62 +1114,55 @@ function bind(): void {
918
1114
  select('report-time').onchange = () => { selectedReportTime = Number(select('report-time').value); renderReportSelection(); seekReportEvent(); };
919
1115
  select('report-target').onchange = () => { const value = select('report-target').value; selectedReportTarget = value ? Number(value) : undefined; prefillReportEvent(); };
920
1116
  select('review-status').onchange = () => { session.status = select('review-status').value as ReviewSession['status']; markDirty(); };
921
- el<HTMLTextAreaElement>('checkpoint-note').oninput = () => { const entry = checkpointEntry(); if (entry) { entry.note = el<HTMLTextAreaElement>('checkpoint-note').value; markDirty(); } };
922
1117
  for (const radio of document.querySelectorAll<HTMLInputElement>('input[name="outcome"]')) radio.onchange = () => { const entry = checkpointEntry(); if (entry) { entry.outcome = radio.value as typeof entry.outcome; markDirty(); renderCheckpoints(); } };
923
1118
  select('feedback-target-kind').onchange = () => renderFeedbackTargets();
924
1119
  button('add-proposal').onclick = async () => {
925
- const start = input('feedback-start').value.trim(), end = input('feedback-end').value.trim(), frameStart = Number(start), frameEnd = Number(end);
926
- const name = input('feedback-target-name').value.trim();
927
- const path = select('correction-path').value, capturedApply = appliedOnStage;
928
- let summary = input('feedback-summary').value.trim(), correction: ReturnType<typeof correctionSelection> | undefined;
929
- if (path === 'described' || path === 'made') {
930
- try {
931
- correction = correctionSelection(path);
932
- summary = input('feedback-summary').value;
933
- const file = input('correction-words').files?.[0];
934
- if (file) {
935
- if (file.size > 4000) throw new Error(tr('Correction text must be valid UTF-8 and at most 1,000 characters.'));
936
- summary = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(await file.arrayBuffer());
937
- }
938
- if (!summary.trim() || summary.length > 1000) throw new Error(tr('Correction text must be valid UTF-8 and at most 1,000 characters.'));
939
- if (path === 'made' && (!capturedApply || capturedApply !== appliedOnStage)) throw new Error(tr('CORRECTION_APPLY_PENDING: Apply and check the correction first.'));
940
- } catch (error) { message(errorText(error), true); return; }
941
- }
942
- if (!start || !end || !Number.isSafeInteger(frameStart) || !Number.isSafeInteger(frameEnd) || frameStart < 0 || frameEnd < frameStart) { message('Enter nonnegative integer start and end frames, with the end at or after the start.', true); return; }
943
- if (!['bone', 'slot', 'rig'].includes(select('feedback-target-kind').value) || !['defect', 'quality'].includes(select('feedback-category').value)) { message('Select a target type and defect or quality category.', true); return; }
944
- if (!name || !summary || (!correction && /[\r\n]/.test(summary)) || summary.length > 1000) { message('Enter the actual target name and a one-line summary of up to 1,000 characters.', true); return; }
945
- const target: Feedback['target'] = { kind: select('feedback-target-kind').value as Feedback['target']['kind'], name };
946
- const selectedAnimation = feedbackAnimation();
947
- try { validateFeedbackSelection(data.feedbackCatalog, { frameStart, frameEnd, target, animation: selectedAnimation }); } catch (error) { message(errorText(error), true); return; }
948
- const box = assets?.stage ?? player?.bounds();
949
- const center = viewport.state.cameraCenter ?? (box ? { x: box.x + box.width / 2, y: box.y + box.height / 2 } : null);
950
- session.feedback.push({ id: crypto.randomUUID(), frameStart, frameEnd, target, category: select('feedback-category').value as Feedback['category'], summary, context: {...(turnPad?{turn:JSON.parse(JSON.stringify(turnPad.snapshot())) as Json}:{}),part:parts?.feedback()??null,
951
- ...(correction ? { correction } : {}),
952
- interval: { frameStart, frameEnd, inclusive: true },
953
- checkpoint: checkpoint?.id ?? null, animation: selectedAnimation, time, frame: frameAtTime(activeFrameClock(), time),
954
- reference: select('reference-select').value || null, person: selectedPerson || null,
955
- sourceTime: sequence ? sequence.frames[0]!.t + time : time,
956
- camera: center ? { zoom:viewport.state.zoom, x: center.x, y: center.y, coordinateSystem: 'world-y-up' } : { zoom:viewport.state.zoom, coordinateSystem: 'reference-fit' },
957
- view:{...serializableView(numericView()),theme:appearance?.get()??'system',layers:{...layers}},
958
- axis: axisInspection ? { id: select('axis-select').value, value: Number(input('axis-value').value) } : null,
959
- environment: feedbackEnvironment(),
960
- // The exported schedule (#112): the drawn clip's rigc-environment/1 bytes and their sha256, and whether readings and Apply read them.
961
- environmentSchedule: feedbackSchedule() as unknown as Json,
962
- // The exact last applied designation and the producer's line, only while that scratch build is what is drawn.
963
- applied: appliedOnStage ? JSON.parse(JSON.stringify(appliedOnStage)) as Json : null,
964
- // The readings chosen (#108): the pairs of the last finished run and the builds they ran on, not their results.
965
- readings: readingsContext() as unknown as Json,
966
- // The declared requirements (#113): the file by hash and content, and its last check, or null when none are declared.
967
- requirements: (requirementsPanel?.context() ?? null) as unknown as Json,
968
- reportEvent: selectedReportEvent ? { id: selectedReportEvent.id, field: selectedReportEvent.field, source: { ...selectedReportEvent.source }, frames: selectedReportEvent.frames ? [...selectedReportEvent.frames] : null, exactTime: eventSeekTime(selectedReportEvent, selectedReportTime), targets: selectedReportEvent.targets.map(target => ({ ...target })) } : null,
969
- } });
970
- input('feedback-summary').value = ''; input('correction-words').value = ''; markDirty(); renderProposals(); message('Added structured feedback. Submit the review to save it.');
1120
+ const path=select('correction-path').value,capturedApply=appliedOnStage;
1121
+ try {
1122
+ if(path!=='described'&&path!=='made')throw new Error(tr('Choose the explicit Create source identity.'));
1123
+ const correction=correctionSelection(path),file=input('correction-words').files?.[0];
1124
+ if(!file||file.size>4000)throw new Error(tr('Correction text must be valid UTF-8 and at most 1,000 characters.'));
1125
+ const summary=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(await file.arrayBuffer());
1126
+ if(!summary.trim()||summary.length>1000)throw new Error(tr('Correction text must be valid UTF-8 and at most 1,000 characters.'));
1127
+ if(path==='made'&&(!capturedApply||capturedApply!==appliedOnStage))throw new Error(tr('CORRECTION_APPLY_PENDING: Apply and check the correction first.'));
1128
+ recordFeedback(summary,undefined,correction);
1129
+ input('correction-words').value='';markDirty();renderProposals();message('Added structured feedback. Submit the review to save it.');
1130
+ }catch(error){message(errorText(error),true);}
971
1131
  };
972
1132
  button('save').onclick = async () => {
973
1133
  if(readOnly){message(readOnly,true);return;}
974
1134
  if(draftConflict){message('Resolve the saved local draft conflict before submitting.',true);return;}
975
1135
  if (session.feedbackWarnings.length) { message('Resolve validation warnings in existing feedback before submitting. Delete the marked entries and add valid replacements.', true); return; }
976
1136
  saving = true; updateSavedState(); const savedPayload = JSON.stringify(session);
1137
+ if (host) {
1138
+ let submissionFailure: ReturnType<typeof jobSubmissionRefusal> | null = null;
1139
+ try {
1140
+ const sent = await host.submit(structuredClone(session), async committed => {
1141
+ submittedBaseline = {...submittedBaseline!, ...committed.review,
1142
+ checkpoints: {...submittedBaseline!.checkpoints, ...committed.checkpoints}, updatedAt: committed.at};
1143
+ session.updatedAt = committed.at;
1144
+ const ids = new Set([...Object.keys(session.checkpoints), ...Object.keys(submittedBaseline.checkpoints)]);
1145
+ dirty = session.status !== submittedBaseline.status || JSON.stringify(session.feedback) !== JSON.stringify(submittedBaseline.feedback) ||
1146
+ [...ids].some(id => JSON.stringify(session.checkpoints[id] ?? {outcome: 'pending', note: ''}) !==
1147
+ JSON.stringify(submittedBaseline!.checkpoints[id] ?? {outcome: 'pending', note: ''}));
1148
+ if(host?.direction){for(const row of recordComments)submittedDirectionComments.add(row.id);try{localStorage.removeItem(recordCommentKey);}catch{}}
1149
+ await persistence?.submitted(submittedBaseline);
1150
+ comments?.refresh(); renderProposals();
1151
+ },host.direction?recordCommentWords():undefined);
1152
+ message(sent);
1153
+ } catch (error) {
1154
+ submissionFailure = jobSubmissionRefusal(error);
1155
+ message(submissionFailure.text, true);
1156
+ }
1157
+ finally {
1158
+ saving = false; updateSavedState();
1159
+ if (submissionFailure) {
1160
+ rigInspector.actBar.setSaveState({kind: 'failed', text: submissionFailure.text, title: submissionFailure.title});
1161
+ el('message').title = submissionFailure.title;
1162
+ }
1163
+ }
1164
+ return;
1165
+ }
977
1166
  try { const saved = await api<ReviewSession>('/api/session', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: savedPayload });
978
1167
  if (JSON.stringify(session) === savedPayload) { session = saved; dirty = false; } else session.updatedAt = saved.updatedAt;
979
1168
  submittedBaseline=structuredClone(saved);comments?.refresh();await persistence?.submitted(saved);renderProvenance();renderProposals();
@@ -985,16 +1174,13 @@ function bind(): void {
985
1174
  const inspected=!!inspectedModel&&(!stageSource||stageSource.url===inspectedModel.url);
986
1175
  const model=player&&stageModelHash?{path:inspected?data.manifest.model!:new URL(stageSource!.url).pathname,sha256:stageModelHash,inspected}:null;
987
1176
  return {model,revision:data.manifest.revision,sourceHash:data.sourceHash,runtime:data.reviewedSource.runtimeVersion,
988
- dials:player?turnPad?.state.dials??[]:[],sets:player?.sets().map(set=>set.name)??[],activeSet:select('part-set').value,authored:data.direction};
1177
+ dials:player?turnPad?.state.dials??[]:[],sets:player?.sets().map(set=>set.name)??[],activeSet:select('part-set').value,authored:data.direction,scene:data.scene};
989
1178
  },name=>{
990
1179
  const picker=select('part-set');picker.value=name;picker.dispatchEvent(new Event('change',{bubbles:true}));
991
1180
  });
1181
+ directionPanel.show(!!data.direction);
992
1182
  viewDisposers.push(()=>directionPanel?.dispose());
993
- viewDisposers.push(bindStageNav({access,interview:data.capabilities.interview,preRig:data.capabilities.preRig,model:!!data.manifest.model,direction:active=>directionPanel?.show(active),setup:()=>showInspector('rig'),draftBuild:()=>appliedOnStage?.buildId??'inspected',refresh:fn=>{refreshStageParts=fn;},correction:openStageCorrection}));
994
- workspace=bindWorkspaceUI({changed:fitCamera,defaultTheme:theme=>appearance?.set(theme),currentTheme:()=>appearance?.get()});
995
- viewport.state.cameraSync=workspace.defaults().defaultCameraSync;input('camera-sync').checked=viewport.state.cameraSync;input('idle-repeat').checked=workspace.defaults().defaultIdleRepeat;
996
- appearance=bindAppearance(select('settings-theme'),workspace.defaults().theme);
997
- inspectorBlocks=bindInspectorBlocks({sections:[el('inspector-rig'),el('inspector-playback')],changed:()=>persistence?.save()});
1183
+ bindWorkspace(!!data.manifest.model);
998
1184
  overlays=new RigOverlays({canvas:el<HTMLCanvasElement>('rig-overlay'),rigRoot:el('rig-root')});
999
1185
  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());
1000
1186
  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());
@@ -1044,19 +1230,33 @@ function bind(): void {
1044
1230
  input('idle-repeat').onchange=()=>{syncPlayerLoop();renderIdle();if(canRepeatIdle())void playPreview();};
1045
1231
  bindEnvironment();
1046
1232
  for(const id of ['proposal-panel','checkpoint-detail'])el(id).addEventListener('focusin',pause);
1047
- bindInspector();bindReviewDialog();
1048
- document.addEventListener('visibilitychange',()=>{if(document.hidden){const resume=playing;pause();suspendedPreview=resume;}else if(suspendedPreview){suspendedPreview=false;void playPreview();}});
1233
+ bindInspector();
1234
+ document.addEventListener('visibilitychange',()=>{if(!screenRoot.isConnected)return;if(document.hidden){const resume=playing;pause();suspendedPreview=resume;}else if(suspendedPreview){suspendedPreview=false;void playPreview();}},{signal:lifecycle.signal});
1049
1235
  const resize = viewport.observeResize();
1050
- window.addEventListener('beforeunload', event => { if (dirty) { event.preventDefault(); event.returnValue = ''; } });
1051
- window.addEventListener('pagehide', () => { comments?.dispose();persistence?.dispose();turnPad?.dispose();workspace?.dispose();pause();controlDispose?.();appearance?.dispose();viewDisposers.forEach(dispose=>dispose());overlays?.dispose(); player?.dispose(); assets?.dispose(); resize.disconnect(); });
1236
+ window.addEventListener('beforeunload', event => { if (screenRoot.isConnected&&dirty) { event.preventDefault(); event.returnValue = ''; } },{signal:lifecycle.signal});
1237
+ viewDisposers.push(()=>resize.disconnect());
1052
1238
  }
1053
1239
 
1240
+ /** The one shell and block binding, for either subject. */
1241
+ function bindWorkspace(hasModel=false):void {
1242
+ workspace=bindWorkspaceUI({root:screenRoot,regions:{layout:screenRoot.querySelector<HTMLElement>('.layout')!,left:screenRoot.querySelector<HTMLElement>('.left-panel')!,main:el('stage-layout').parentElement!,stage:el('stage-layout'),bottom:screenRoot.querySelector<HTMLElement>('.inspector')!,columns:{left:'rightWidth',right:null}},language:shell.language!,bottomPanel:rigInspector,changed:fitCamera,defaultTheme:theme=>appearance?.set(theme),currentTheme:()=>appearance?.get()});
1243
+ viewport.state.cameraSync=workspace.defaults().defaultCameraSync;input('camera-sync').checked=viewport.state.cameraSync;input('idle-repeat').checked=workspace.defaults().defaultIdleRepeat;
1244
+ appearance=bindAppearance(select('settings-theme'),workspace.defaults().theme);
1245
+ bindReviewDialog();
1246
+ inspectorBlocks=bindInspectorBlocks({sections:[el('inspector-rig'),el('inspector-playback')],available:host?.record&&(!host.record.hasPicture||!hasModel)?['feedback']:undefined,bottom:{strip:rigInspector.strip,comment:rigInspector.comments.button,panel:rigInspector.comments.panel},changed:()=>{workspace?.refresh();persistence?.save();}});
1247
+ }
1054
1248
  async function start(): Promise<void> {
1055
1249
  try {
1250
+ if(host?.record&&!host.record.hasPicture){await startRecord();return;}
1056
1251
  let writes: { capabilityRequired: boolean; control?: boolean };
1057
- [data, session, writes] = await Promise.all([api<ReviewResponse>('/api/review'), api<ReviewSession>('/api/session'), api<{ capabilityRequired: boolean; control?: boolean }>('/api/access')]);
1058
- readOnly = readOnlyReason(access, writes.capabilityRequired);
1059
- if(data.capabilities.preRig)el('write-review').hidden=true;
1252
+ const opened=await api<ReviewResponse|PartsSubjectEntry|InterviewSubjectEntry>('/api/review');
1253
+ if('subject' in opened&&opened.subject==='interview'){await startRecord(opened);return;}
1254
+ const [saved,accessState]=await Promise.all([api<ReviewSession|PartsSubjectSession>('/api/session'),api<{capabilityRequired:boolean;control?:boolean}>('/api/access')]);
1255
+ if('subject' in opened&&opened.subject==='parts'){await startParts(opened,saved as PartsSubjectSession,accessState);return;}
1256
+ data=opened as ReviewResponse;session=saved as ReviewSession;writes=accessState;
1257
+ readOnly = host?.unavailable?t('job.refusal.'+host.unavailable):host?.record ? tr('JOB_REVIEW_READ_ONLY') : readOnlyReason(access, writes.capabilityRequired);
1258
+ actReadOnly = readOnlyReason(access, writes.capabilityRequired, host?.ownerActAccess);
1259
+ if(data.capabilities.preRig&&!host?.record){rigInspector.comments.button.disabled=true;rigInspector.act.hidden=true;}
1060
1260
  submittedBaseline=structuredClone(session);
1061
1261
  text('package-title', data.manifest.title); text('revision', data.manifest.revision); document.title = `${data.manifest.title} · rig review`; text('source-hash', `source ${data.sourceHash.slice(0, 12)}`); select('review-status').value = session.status; select('feedback-target-kind').value = 'rig'; input('feedback-target-name').value = data.manifest.id;
1062
1262
  select('reference-select').replaceChildren(); for (const reference of data.manifest.references) select('reference-select').append(option(reference.id, `${reference.label} · ${reference.type}`));
@@ -1065,9 +1265,11 @@ async function start(): Promise<void> {
1065
1265
  // Checkpoints and reference fold away when the package supplies neither.
1066
1266
  (el('package-context') as HTMLDetailsElement).open = data.manifest.checkpoints.length > 0 || data.manifest.references.length > 0;
1067
1267
  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';
1068
- populateChestBones(); bind(); parts=new PartExplorer(el('workspace-left'),el('selected-part'),previous=>{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);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({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){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();
1268
+ 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);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({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();
1069
1269
  const requestedId = new URLSearchParams(location.search).get('checkpoint'),initial=initialReviewSelection(data.manifest,requestedId,data.explicitReference?.id,data.initialAnimation??undefined),first=initial.checkpoint;
1070
1270
  rigInput=data.manifest.model?{state:'pending'}:{state:'absent'};renderLayout();
1271
+ // A job rig subject lands in Animate before the model finishes loading (#709).
1272
+ if(host)showInspector(data.manifest.model?'playback':'rig');
1071
1273
  if(initial.referenceId){select('reference-select').value=initial.referenceId;await showReference(initial.referenceId);}
1072
1274
  await initPlayer(first);
1073
1275
  // initPlayer keeps `player` only after its first draw succeeded; a declared model path alone never counts.
@@ -1076,32 +1278,273 @@ async function start(): Promise<void> {
1076
1278
  if (first) await chooseCheckpoint(first,initial); else renderCheckpoint();
1077
1279
  viewport.state.activeCamera=player?'rig':'reference';if(viewport.state.cameraSync)alignCameras();renderTransport();fitCamera();
1078
1280
  if (requestedId && !first) message(`Checkpoint "${requestedId}" is not in this package. Select one from the list.`, true);
1079
- else if (readOnly) message(readOnly, true);
1281
+ else if (actReadOnly) message(actReadOnly, true);
1282
+ else if (host?.ownerActAccess) message('Not submitted');
1080
1283
  else message(data.manifest.model ? 'Record review status and structured feedback while preserving sources. Motion is read only.' : 'No rig supplied. Review the available references and checkpoints.');
1081
- requestAnimationFrame(tick);
1082
- const restored=await setupPersistence();setupComments();await loadRebuildStatus();void loadRequirements();renderChest();restoreEnvironment();physicsPanel?.restore();bonesPanel?.restore();cutsPanel?.restore();clothPanel?.restore();idlePanel?.restore();rigFieldsPanel?.restore();meshPanel?.restore();void refreshDensityStrip();renderIdle();if(!restored&&canRepeatIdle()&&automaticIdlePreview(assets?.animations.map(item=>item.name)??[],animation,first,!!requestedId))void playPreview();
1284
+ frameHandle=requestAnimationFrame(tick);
1285
+ const restored=await setupPersistence();setupComments();if(host?.direction)showRecordComments(true);else if(host?.record&&!data.manifest.model)showRecordComments();await loadRebuildStatus();void loadRequirements();renderChest();restoreEnvironment();physicsPanel?.restore();bonesPanel?.restore();cutsPanel?.restore();clothPanel?.restore();idlePanel?.restore();rigFieldsPanel?.restore();meshPanel?.restore();void refreshDensityStrip();renderIdle();if(idlePreviewOnOpen(restored,!!host)&&canRepeatIdle()&&automaticIdlePreview(assets?.animations.map(item=>item.name)??[],animation,first,!!requestedId))void playPreview();
1083
1286
  // Only an instance that serves agent control is asked for its config: a plain open has no control endpoint (#164).
1084
1287
  if(!readOnly&&writes.control!==false)controlDispose=connectControl({sourceHash:data.sourceHash,mode:'single',route:access.route,headers:()=>access.headers(),observe:controlState,apply:applyControl,onStatus:value=>text('control-state',value)});
1085
1288
  bindWorkspaceVisibility({key:access.key,sourceHash:data.sourceHash,pause});
1086
- } catch (error) { message(`Could not open review package: ${errorText(error)}`, true); text('dirty', 'Load failed'); }
1087
- }
1088
- /** `feedback` is the review dialog, not an Inspector section: a user action opens it; a restored older bookmark that saved it selects nothing. */
1089
- function showInspector(name:string,reveal=true):void {if(name==='feedback'){if(reveal)openReview();return;}if(reveal)workspace?.revealInspector();const selector=document.querySelector<HTMLButtonElement>(`[data-inspector="${name}"]`);if(selector&&selector.getAttribute('aria-pressed')!=='true'&&selector.getAttribute('aria-selected')!=='true')selector.click();}
1090
- function bindInspector():void {bindInspectorTabs(()=>{workspace?.afterTab();fitCamera();},()=>workspace?.beforeTab());}
1091
- /** Opening the review pauses playback, as selecting Feedback did. Its inputs stay in the document whether or not it is open, so the draft keeps them. */
1092
- function openReview():void {document.querySelector<HTMLButtonElement>('[data-review-stage="3"]')?.click();const dialog=el<HTMLDialogElement>('review-dialog');for(const drawer of document.querySelectorAll<HTMLDialogElement>('dialog.workspace-drawer[open]'))drawer.close();pause();syncCorrectionStage();if(!dialog.open)dialog.showModal();}
1093
- function bindReviewDialog():void {
1094
- const dialog=el<HTMLDialogElement>('review-dialog');
1095
- button('write-review').onclick=openReview;button('review-dialog-close').onclick=()=>dialog.close();
1096
- select('correction-stage').onchange=syncCorrectionStage;
1097
- // Escape closes the native modal; every close returns focus to the button that opens it.
1098
- dialog.addEventListener('close',()=>{button('write-review').setAttribute('aria-expanded','false');button('write-review').focus();});
1099
- dialog.addEventListener('toggle',()=>{if(dialog.open)button('write-review').setAttribute('aria-expanded','true');});
1100
- }
1289
+ if(host){
1290
+ if(!player&&video){
1291
+ await waitReferenceMetadata(video,lifecycle.signal);
1292
+ if(video.readyState<2)await mediaReady(video,'loadeddata',lifecycle.signal);
1293
+ if(video.seeking)await mediaReady(video,'seeked',lifecycle.signal);
1294
+ if(!video.seeking&&video.readyState>=2&&video.currentTime===time)setReferenceInput({state:'loaded'});
1295
+ }
1296
+ if(!player&&(data.manifest.model||referenceInput.state!=='loaded'))throw new Error('JOB_VISUAL_UNAVAILABLE');
1297
+ await restorePublicationNavigation();document.body.dataset.ready='true';
1298
+ 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();
1299
+ }
1300
+ } catch (error) { message(`Could not open review package: ${errorText(error)}`, true); text('dirty', 'Load failed'); host?.failed(error); }
1301
+ }
1302
+ /** Parts have a verdict and image-space pixels, never fabricated model/session fields. */
1303
+ async function startParts(opened:PartsSubjectEntry,saved:PartsSubjectSession,writes:{capabilityRequired:boolean}):Promise<void>{
1304
+ const subject=opened.parts,issues=saved.issues,submittedIssues=new Set(host? saved.issues.map(issue=>issue.id):[]);
1305
+ liveIssueCount=()=>issues.length;
1306
+ if(!partsOnly)throw new Error('PARTS_SUBJECT_ENTRY_REQUIRED');
1307
+ readOnly=host?.record?tr('JOB_REVIEW_READ_ONLY'):readOnlyReason(access,writes.capabilityRequired);
1308
+ actReadOnly=readOnlyReason(access,writes.capabilityRequired,host?.ownerActAccess);
1309
+ text('package-title',subject.title);text('revision','Parts package, before rigging');text('source-hash',`source ${subject.sourceHash.slice(0,12)}`);document.title=subject.title;
1310
+ bindWorkspace();bindInspector(true);
1311
+ const base=host?'/api/stage-parts':'/api/parts';
1312
+ const request=async(path:string,init?:RequestInit)=>{
1313
+ const response=await fetch(access.route(path),{...init,headers:access.headers(init?.headers)});
1314
+ 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;
1315
+ };
1316
+ 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})`);};
1317
+ // A parts verdict is saved only over a drawn subject: until the first paint, or after a failed one, Save stays off.
1318
+ const saveBlocked=()=>!!readOnly||!!subject.legacyVerdict?.readOnly||rigInput.state!=='loaded';
1319
+ text('rig-empty','Loading package…');
1320
+ partsSubject=bindPartsSubject({data:subject,canvas:partsCanvas,referenceCanvas:partsReference,viewport,el,toolbar:primaryToolbar,commentsHost:el('comments-list-host'),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;}changed();},selectionChanged:()=>parts?.refreshImages(),locked:id=>submittedIssues.has(id),refusal:()=>readOnly,drawn:state=>{rigInput=state;button('save').disabled=saveBlocked();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});
1321
+ parts=new PartExplorer(el('workspace-left'),el('selected-part'),()=>{},()=>openReview());
1322
+ const thumbnails=new PartThumbnails();viewDisposers.push(()=>thumbnails.dispose());
1323
+ 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});
1324
+ const unavailable='PARTS_RIG_UNAVAILABLE: this parts subject has no compiled rig.';
1325
+ for(const node of el('proposal-panel').children)if(node.id!=='comments-list-host')(node as HTMLElement).hidden=true;
1326
+ for(const control of document.querySelectorAll<HTMLInputElement|HTMLSelectElement|HTMLButtonElement>('#checkpoint-detail input,#proposal-panel input,#proposal-panel select,#proposal-panel button,#strip-panel input,#strip-panel select,#strip-panel button'))if(!control.closest('#comments-list-host')){control.disabled=true;setSourceAttribute(control,'title',unavailable);if(control instanceof HTMLInputElement&&control.name==='outcome')control.checked=false;}
1327
+ text('detail-note',unavailable);text('checkpoint-note','');el('strip-panel').hidden=true;
1328
+ text('provenance-version','Parts package, before rigging');text('provenance-rig','Not supplied');text('provenance-motion','Not supplied');
1329
+ text('provenance-full',JSON.stringify({subject:'parts',sourceHash:subject.sourceHash,painting:subject.painting,images:subject.items.map(({name,imageHash})=>({name,imageHash}))},null,2));
1330
+ text('source-files',`source ${subject.sourceHash}`);const provenanceHint=document.querySelector<HTMLElement>('.provenance>.hint');if(provenanceHint)setSourceText(provenanceHint,'Source files remain unchanged.');
1331
+ for(const tab of document.querySelectorAll<HTMLButtonElement>('[data-block-target]'))if(!['selected-part','feedback'].includes(tab.dataset.blockTarget??'')){tab.disabled=true;setSourceAttribute(tab,'title',unavailable);}
1332
+ for(const tool of document.querySelectorAll<HTMLButtonElement>('[data-workspace-view-tools] button')){tool.hidden=false;tool.disabled=true;setSourceAttribute(tool,'title',unavailable);}
1333
+ input('layer-images').disabled=false;input('layer-mesh').disabled=!subject.items.some(item=>item.mesh);input('layer-bones').disabled=true;
1334
+ describeLayerToggles(document,unavailable);
1335
+ for(const [id,key]of [['layer-images','images'],['layer-mesh','mesh']]as const)input(id).onchange=()=>{layers[key]=input(id).checked;partsSubject?.redraw();};
1336
+ const overlay=panelMake('input',{id:'parts-overlay',type:'checkbox',disabled:!subject.painting}),opacity=panelMake('input',{id:'parts-opacity',type:'range',min:'0',max:'1',step:'0.001',value:'0.5',disabled:!subject.painting});
1337
+ const overlayLabel=panelMake('label',{},overlay,tr('Overlay')),opacityLabel=panelMake('label',{},tr('Part opacity'),opacity);
1338
+ if(!subject.painting)for(const node of [overlayLabel,opacityLabel])setSourceAttribute(node,'title','PARTS_REFERENCE_UNAVAILABLE: supply --painting to compare the original painting');
1339
+ secondaryToolbar.append(overlayLabel,opacityLabel);
1340
+ overlay.onchange=()=>{partsSubject?.setComparison(overlay.checked?'overlay':'part');if(overlay.checked){view='rig';renderLayout();}};
1341
+ opacity.oninput=()=>partsSubject?.opacity(Number(opacity.value));
1342
+ 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.'));
1343
+ const reference=select('reference-select');reference.replaceChildren(option('',subject.painting?'Original painting':'No references supplied'));reference.disabled=true;
1344
+ el('package-context').removeAttribute('open');el('reference-empty').hidden=!!subject.painting;el('rig-overlay').hidden=true;
1345
+ const state=rigInspector.actBar;state.setSaveState({kind:actReadOnly?'read-only':'unsaved',text:actReadOnly??'Not submitted'});
1346
+ select('review-status').hidden=true;document.querySelector<HTMLLabelElement>('label[for="review-status"]')!.hidden=true;
1347
+ button('save').disabled=saveBlocked();
1348
+ button('save').onclick=async()=>{
1349
+ if(saving||saveBlocked())return;saving=true;button('save').disabled=true;state.setSaveState({kind:'saving',text:'Saving…'});renderDraftState();
1350
+ const frozen=structuredClone(issues);
1351
+ try{
1352
+ if(host?.submitParts)message(await host.submitParts(frozen));
1353
+ else await request(base+'/verdict',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({status:frozen.length?'changes-requested':'approved',issues:frozen})});
1354
+ if(host)for(const issue of frozen)submittedIssues.add(issue.id);
1355
+ dirty=JSON.stringify(issues)!==JSON.stringify(frozen);state.setSaveState({kind:dirty?'unsaved':'saved',text:dirty?'Unsubmitted changes':'Submitted'});text('dirty',dirty?'Unsubmitted changes':'Submitted');el('dirty').classList.toggle('dirty',dirty);
1356
+ }catch(error){message(errorText(error),true);state.setSaveState({kind:'failed',text:'Save failed.'});}
1357
+ finally{saving=false;button('save').disabled=saveBlocked();renderDraftState();}
1358
+ };
1359
+ viewDisposers.push(viewport.bindControls(unitScaleMessage),viewport.bindNavigation(undefined,()=>!el('stage-layout').getAttribute('aria-busy')?.includes('true')),bindLayerShortcuts(document));
1360
+ const resize=viewport.observeResize();viewDisposers.push(()=>resize.disconnect());
1361
+ viewport.requestFit();await partsSubject.ready();text('dirty','Not submitted');message(actReadOnly??(host?.ownerActAccess?'Not submitted':'Parts ready. Source files remain unchanged.'),!!actReadOnly);referenceInput=subject.painting?{state:'loaded'}:{state:'absent'};renderLayout();
1362
+ renderPendingSubjects(host?.pendingSubjects?.()??[{kind:'parts-verdict'}]);
1363
+ 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();}
1364
+
1365
+ document.body.dataset.ready='true';
1366
+ }
1367
+ /** Use the existing Comments-only presentation for subjects without rig capabilities. */
1368
+ function showRecordComments(preserveInspector=false):void {
1369
+ for(const child of el('proposal-panel').children)if(child.id!=='comments-list-host')(child as HTMLElement).hidden=true;
1370
+ if(preserveInspector)return;
1371
+ for(const child of rigInspector.comments.panel.children)(child as HTMLElement).hidden=child!==el('proposal-panel')&&!child.classList.contains('review-dialog-header');
1372
+ rigInspector.comments.panel.style.display='block';
1373
+ rigInspector.collapse.disabled=false;setSourceAttribute(rigInspector.collapse,'title','');
1374
+ }
1375
+ /** Publications without a picture reuse the empty main view; no model is manufactured. */
1376
+ async function startRecord(interview?:InterviewSubjectEntry):Promise<void> {
1377
+ if(!host?.record&&!interview)throw new Error('JOB_DISPLAY_MISMATCH');
1378
+ const unavailable=interview?'MODEL_UNAVAILABLE: no compiled model is supplied in this inspection.':'This request has no picture.';
1379
+ readOnly=tr(interview?'MODEL_UNAVAILABLE':'JOB_REVIEW_READ_ONLY');
1380
+ if(!interview)actReadOnly=readOnlyReason(access,true,host?.ownerActAccess);
1381
+ bindWorkspace();bindInspector(true);rigInput={state:'absent'};referenceInput={state:'absent'};renderLayout();
1382
+ 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);
1383
+ text('package-title',interview?.label??host!.record!.label);text('revision','');text('source-hash',`source ${(interview?.sourceHash??host!.record!.sourceHash).slice(0,12)}`);
1384
+ el('rig-pane').hidden=false;el('rig-empty').hidden=false;text('rig-empty',unavailable);
1385
+ 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);}
1386
+ if(interview){
1387
+ button('save').disabled=true;setSourceAttribute(button('save'),'title',unavailable);
1388
+ const label=()=>{setSourceText(rigAsk,t('interview.title'));recordDialog?.setAttribute('aria-label',t('interview.title'));};
1389
+ label();viewDisposers.push(onLanguageChange(label));
1390
+ viewDisposers.push(await joinedInterviewForms(access,forms=>renderRecordForms(forms,t('interview.title'),true)));
1391
+ text('provenance-rig',unavailable);text('provenance-motion',unavailable);text('source-files','project.json');
1392
+ }else{restoreRecordComments();setupComments();showRecordComments();rigInspector.comments.button.disabled=false;button('stage-comment').disabled=false;}
1393
+ const resize=viewport.observeResize();viewDisposers.push(()=>resize.disconnect());
1394
+ await workspace?.settle();if(disposed)return;
1395
+ if(host?.unavailable){message(t('job.refusal.'+host.unavailable),true);el('message').title=host.unavailable;button('save').disabled=true;button('save').title=host.unavailable;}
1396
+ document.body.dataset.ready='true';
1397
+ if(!interview){host!.attach({recordForms:renderRecordForms,pendingSubjects:renderPendingSubjects,stage:()=>null,redraw:()=>{},message:(value,error,diagnostic)=>message(value,error,false,diagnostic),suspend:suspendScreen,resume:resumeScreen,dispose:disposeScreen});host!.displayed();}
1398
+ }
1399
+ let recordDialog:HTMLDialogElement|null=null;
1400
+ /** Reuse the form's publication binding for native record comments, without a package session. */
1401
+ function restoreRecordComments(form?:HTMLFormElement):void {
1402
+ if((!host?.record&&!host?.direction)||recordCommentKey)return;
1403
+ const publicationId=host?.direction?.publicationId??host?.record?.publicationId??form?.dataset.jobPublication,sourceHash=host?.direction?.sourceHash??host!.record!.sourceHash;
1404
+ if(!publicationId)throw new Error('JOB_DISPLAY_MISMATCH');
1405
+ recordCommentKey='rig-review-record-comments/1:'+publicationId+':'+sourceHash;
1406
+ try {
1407
+ const saved=JSON.parse(localStorage.getItem(recordCommentKey)??'null');
1408
+ if(saved?.publicationId!==publicationId||saved?.sourceHash!==sourceHash||!Array.isArray(saved.comments)||saved.comments.length>1000)return;
1409
+ const ids=new Set<string>();
1410
+ const rows=saved.comments as CommentRow[];
1411
+ for(const row of rows){
1412
+ 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');
1413
+ ids.add(row.id);
1414
+ 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());}
1415
+ 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');}
1416
+ else if(Object.keys(row).some(key=>key!=='id'&&key!=='summary'))throw new Error('JOB_ACT_INVALID');
1417
+ }
1418
+ 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}));
1419
+ recordComments.push(...rows);
1420
+ }catch{/* A mismatched or invalid local draft has no authority. */}
1421
+ }
1422
+ /** Comments remain native rows locally; the old act field carries their scalar projection only. */
1423
+ function recordCommentWords():string {
1424
+ 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}));
1425
+ }
1426
+ function recordCommentsChanged():void {
1427
+ if(!host?.record&&!host?.direction)return;
1428
+ 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. */}
1429
+ setSourceText(rigInspector.comments.button,`Comments (${recordComments.length})`);
1430
+ for(const form of recordDialog?.querySelectorAll('form[data-job-ask]')??[])form.dispatchEvent(new Event('input',{bubbles:true}));
1431
+ }
1432
+ /** The shared answer forms use the one native dialog, opened from the current ask line. */
1433
+ function renderRecordForms(forms:readonly HTMLElement[],label='job.pending',standalone=false):void {
1434
+ if(!forms.length&&!recordDialog)return;
1435
+ if(!recordDialog){
1436
+ recordDialog=panelMake('dialog',{id:'job-record-asks',className:'workspace-drawer'});recordDialog.setAttribute('aria-label',tr(label));
1437
+ const close=panelMake('button',{className:'workspace-drawer-close',type:'button'},tr('Close'));recordDialog.append(close);app.append(recordDialog);
1438
+ viewDisposers.push(bindWorkspaceDrawer({trigger:rigAsk,drawer:recordDialog,label:tr(label),close}));
1439
+ viewDisposers.push(()=>{recordDialog?.close();recordDialog?.remove();recordDialog=null;});
1440
+ }
1441
+ recordDialog.classList.toggle('interview-modal',forms.some(form=>form.classList.contains('interview-answer')));
1442
+ for(const form of recordDialog.querySelectorAll<HTMLFormElement>('form.interview-answer,form[data-job-ask]'))if(!forms.includes(form)){if(!standalone)form.dispatchEvent(new Event('job-form-dispose'));form.remove();}
1443
+ if(!standalone&&forms[0])restoreRecordComments(forms[0] as HTMLFormElement);
1444
+ const added=forms.filter(form=>!recordDialog!.contains(form));
1445
+ for(const form of forms){
1446
+ if(!standalone)(form as JobForm['form']).commentWords=()=>host?.record||host?.direction?recordCommentWords():partsOnly?projectComments(partsIssueComments(partsSubject?.issues()??[])):projectComments(feedbackItemComments(session.feedback));
1447
+ if(!recordDialog.contains(form)){if(!form.classList.contains('interview-answer'))form.style.overflow='auto';form.style.minHeight='0';recordDialog.append(form);}
1448
+ }
1449
+ if(host?.record){
1450
+ for(const child of el('proposal-panel').children)if(child.id!=='comments-list-host')(child as HTMLElement).hidden=true;
1451
+ setSourceText(rigInspector.comments.button,`Comments (${recordComments.length})`);comments?.refresh();partsSubject?.refreshComments();
1452
+ button('save').disabled=!forms.some(form=>!form.querySelector('fieldset')?.disabled);button('save').onclick=()=>rigAsk.click();
1453
+ }
1454
+ if(standalone){rigAsk.hidden=false;setSourceText(rigAsk,t('interview.title'));}
1455
+ rigAsk.disabled=!forms.length;
1456
+ if((standalone?added.length>0:added.some(form=>form.classList.contains('interview-answer')))&&!recordDialog.open)rigAsk.click();
1457
+ }
1458
+ /** The ask heading reads only already-pending subjects. It never synthesizes an agent request. */
1459
+ function renderPendingSubjects(subjects:readonly {kind:string;stage?:string}[]):void {
1460
+ 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.'};
1461
+ const labels=subjects.map(subject=>requests[subject.kind+':'+subject.stage]??requests[subject.kind]).filter((label):label is string=>!!label);
1462
+ renderDraftState();
1463
+ rigAsk.hidden=!labels.length;setSourceText(rigAsk,labels.join(' · '));setSourceAttribute(rigAsk,'title',labels.join(' · '));
1464
+ }
1465
+ /** The rig pane for a live job's still (#709): the job binds and copies it, this screen keeps its view. */
1466
+ function hostStage():RigHostStage|null {
1467
+ if(!player)return null;const frame=parts?.frame('single');
1468
+ return {pane:el('rig-viewport'),paneHidden:el('rig-pane').hidden,root:el('rig-root'),player,frameGeneration:frame?.generation,camera:numericView().cameras.rig,frame:paneFrame('rig'),
1469
+ wholeRig:!rigDifference&&!parts?.value()&&player.slots===null&&layers.images,playing,posed:frame,assets};
1470
+ }
1471
+ /** Navigation alone crosses publication identity. The source's draft and submitted baseline were loaded normally above. */
1472
+ async function restorePublicationNavigation():Promise<void> {
1473
+ const navigation=host?.navigation;if(!navigation)return;
1474
+ if(navigation.subject==='parts'){
1475
+ if(!partsSubject)return;
1476
+ const opened=await api<PartsSubjectEntry>('/api/review');
1477
+ const exists=navigation.part===null||opened.parts.items.some(item=>item.name===navigation.part);
1478
+ partsSubject.select(exists?navigation.part:null);partsSubject.isolate(exists&&navigation.solo);parts?.refreshImages();
1479
+ await partsSubject.paint();
1480
+ view=navigation.view==='reference'?'reference':navigation.view==='compare'?'compare':'rig';renderLayout();
1481
+ viewport.cancelFit();
1482
+ for(const target of ['rig','reference']as const){const camera=navigation.camera.cameras[target];if(camera)viewport.writeCamera(target,camera);}
1483
+ viewport.state.cameraSync=navigation.camera.cameraSync??false;fitCamera();
1484
+ navigationMissing=!exists;if(!exists)message(tr('job.incompatible'));return;
1485
+ }
1486
+ if(partsOnly)return;
1487
+ const bookmark=structuredClone(navigation.bookmark);bookmark.binding=inspectionBinding();
1488
+ let missing=false;
1489
+ if(bookmark.selection.part){
1490
+ const {side,slot,mode}=bookmark.selection.part;bookmark.selection.part={side,slot,mode};
1491
+ try{parts?.validate(bookmark.selection.part);}catch{bookmark.selection.part=null;missing=true;}
1492
+ }
1493
+ if(bookmark.selection.checkpoint&&!data.manifest.checkpoints.some(item=>item.id===bookmark.selection.checkpoint))bookmark.selection.checkpoint=null;
1494
+ if(bookmark.selection.reference&&!data.manifest.references.some(item=>item.id===bookmark.selection.reference)){bookmark.selection.reference=null;bookmark.view.cameras.reference=null;missing=true;}
1495
+ if(bookmark.animation&&!assets?.animations.some(item=>item.name===bookmark.animation)){bookmark.animation=null;bookmark.time=0;bookmark.selection.axis=null;missing=true;}
1496
+ if(bookmark.selection.turn){try{if(!turnPad)throw new Error('TURN_UNAVAILABLE');turnPad.state.validate(bookmark.selection.turn);}catch{delete bookmark.selection.turn;missing=true;}}
1497
+ if(bookmark.selection.partSet&&!player?.sets().some(item=>item.name===bookmark.selection.partSet)){bookmark.selection.partSet=null;missing=true;}
1498
+ if(bookmark.selection.axis){const saved=bookmark.selection.axis,axis=data.manifest.axes.find(item=>item.id===saved.id);if(!axis||axis.animation!==bookmark.animation||saved.value<axis.min||saved.value>axis.max){bookmark.selection.axis=null;missing=true;}}
1499
+ const info=await inspectionReferenceInfo(bookmark.selection.reference===undefined?select('reference-select').value:bookmark.selection.reference,new AbortController().signal);
1500
+ const limit=inspectionTimeLimit(bookmark,info);
1501
+ if(bookmark.time!==null&&(bookmark.time<0||bookmark.time>limit&&limit>=0)){bookmark.time=0;missing=true;}
1502
+ if(bookmark.selection.person&&!info.people.includes(bookmark.selection.person)){bookmark.selection.person=null;missing=true;}
1503
+ await restoreInspection(bookmark,new AbortController().signal,true,true);
1504
+ persistence?.save();
1505
+ navigationMissing=missing;if(missing)message(tr('job.incompatible'));
1506
+ }
1507
+ function suspendScreen():void {
1508
+ if(suspended||disposed)return;
1509
+ if(!partsOnly&&(!host?.record||host.record.hasPicture))pause();
1510
+ persistence?.dispose();persistence=null;suspended=true;cancelAnimationFrame(frameHandle);
1511
+ }
1512
+ async function resumeScreen():Promise<void> {
1513
+ if(disposed)return;
1514
+ (window as unknown as {rigReviewEditor:unknown}).rigReviewEditor=publicEditor;
1515
+ const wasInert=screenRoot.inert;let ready=false;screenRoot.inert=true;document.body.removeAttribute('data-ready');
1516
+ try{
1517
+ await workspace?.settle();
1518
+ if(disposed)return;
1519
+ if(!partsOnly&&(!host?.record||host.record.hasPicture))await setupPersistence(true);
1520
+ suspended=false;if(!partsOnly&&(!host?.record||host.record.hasPicture))frameHandle=requestAnimationFrame(tick);ready=true;
1521
+ }finally{screenRoot.inert=ready?wasInert:true;if(ready&&!disposed)document.body.dataset.ready='true';}
1522
+ }
1523
+ function disposeScreen():void {
1524
+ if(disposed)return;suspendScreen();disposed=true;lifecycle.abort();
1525
+ comments?.dispose();partsSubject?.dispose();turnPad?.dispose();inspectorBlocks?.dispose();inspectorTabs?.dispose();
1526
+ workspace?.dispose();controlDispose?.();appearance?.dispose();rigInspector.actBar.dispose();shell.dispose();
1527
+ viewDisposers.forEach(dispose=>dispose());overlays?.dispose();player?.dispose();assets?.dispose();
1528
+ }
1529
+ window.addEventListener('pagehide',disposeScreen,{once:true,signal:lifecycle.signal});
1530
+ /** Old feedback bookmarks keep their inspection mode; only an explicit reveal opens the act. */
1531
+ function showInspector(name:string,reveal=true):void {if(name==='feedback'){if(reveal)openReview();return;}if(reveal)inspectorTabs?.select(name);else inspectorTabs?.restore(name);}
1532
+ function bindInspector(partsSubject=false):void {
1533
+ inspectorTabs?.dispose();
1534
+ rigInspector.row.reveal=()=>workspace?.revealInspector();
1535
+ inspectorTabs=bindInspectorTabs(()=>{const mode=inspectorTabs?.state();if(mode)inspectorBlocks?.activate(mode);workspace?.afterTab();renderLayout();},()=>workspace?.beforeTab(),rigInspector.row);
1536
+ viewDisposers.push(bindHeaderModeAvailability(partsSubject?{model:false,parts:true}:{model:!!data.manifest.model,preRig:data.capabilities.preRig,parts:!!host?.record&&!data.manifest.model}));
1537
+ for(const mode of document.querySelectorAll<HTMLButtonElement>('[data-mode]'))if(mode.dataset.mode==='rig'||mode.dataset.mode==='playback')mode.onclick=()=>showInspector(mode.dataset.mode!);
1538
+ }
1539
+ /** Pause at the held time and reveal the existing act without changing Setup/Animate mode. */
1540
+ function openReview():void {pause();if(!partsOnly)syncCorrectionStage();inspectorBlocks?.select(selectedInspector()??'rig','feedback');workspace?.revealInspector();}
1541
+ function unitScaleMessage(target:CameraTarget):void {message(partsOnly?'1:1':target==='rig'?'1:1 · one CSS pixel per model coordinate unit.':'1:1 · one CSS pixel per reference grid unit.');}
1542
+ function bindReviewDialog():void {select('correction-stage').onchange=syncCorrectionStage;button('native-one').title=tr('One CSS pixel per current pane coordinate unit; synchronized panes retain relative zoom.');}
1101
1543
 
1102
1544
  /** Rig world → rig-pane pixels for the current camera. */
1103
1545
  function rigProject(){const root=el('rig-root');return (x:number,y:number)=>({x:parseFloat(root.style.left||'0')+x*viewport.state.rigScale,y:parseFloat(root.style.top||'0')-y*viewport.state.rigScale});}
1104
1546
  function redrawOverlay(fresh:boolean):void {
1547
+ if(rigDifference)return;
1105
1548
  animationPanel?.redraw(layers.bones);
1106
1549
  if(!overlays||!player)return;
1107
1550
  const project=rigProject();
@@ -1117,10 +1560,10 @@ function redrawOverlay(fresh:boolean):void {
1117
1560
  function syncPlayerLoop():void {
1118
1561
  const want=canRepeatIdle();
1119
1562
  if(!player?.current||player.composed||player.entry(0)?.loop===want)return;
1120
- try{drawRig(()=>{player!.play(animation,{loop:want});if(!playing)player!.pause();player!.seek(time);player!.draw();});}
1563
+ try{drawRig(()=>{player!.play(animation,{loop:want});if(!playing)player!.pause();player!.seek(activeScene()?takeSample(activeScene()!,time).sourceTime:time);player!.draw();});}
1121
1564
  catch(error){message(errorText(error),true);}
1122
1565
  }
1123
- function canRepeatIdle():boolean{return !!player&&idleAvailable(assets?.animations.map(a=>a.name)??[],animation)&&!axisInspection&&input('idle-repeat').checked&&duration>0;}
1566
+ function canRepeatIdle():boolean{const direction=activeScene();if(direction)return direction.take.loop;return !!player&&idleAvailable(assets?.animations.map(a=>a.name)??[],animation)&&!axisInspection&&input('idle-repeat').checked&&duration>0;}
1124
1567
  function renderIdle():void {text('idle-state',canRepeatIdle()?'Actual idle · repeat enabled':animation==='idle'?'Idle repeat paused':'Non-idle inspection · no automatic playback');}
1125
1568
  async function playPreview():Promise<void> {
1126
1569
  if((!player&&!video&&!sequence)||duration<=0)return;
@@ -1128,7 +1571,7 @@ async function playPreview():Promise<void> {
1128
1571
  if(video&&referenceInput.state==='loaded'){try{await video.play();}catch(error){pause();message(`Playback is paused: ${errorText(error)}. Use Play to retry.`,true);return;}}
1129
1572
  if(intent!==playbackIntent||!desiredPlay){if(!desiredPlay)video?.pause();return;}playing=true;lastFrame=0;player?.hold(false);player?.resume();button('play').textContent='Ⅱ';button('play').setAttribute('aria-label','Pause');
1130
1573
  }
1131
- function localDraft():boolean{return !!comments?.draft()||dirty||!!input('feedback-summary').value.trim()||!!input('feedback-start').value.trim()||!!input('feedback-end').value.trim()||!!select('feedback-category').value||!!input('feedback-target-name').value.trim()&&input('feedback-target-name').value!==data.manifest.id;}
1574
+ function localDraft():boolean{return !!comments?.draft()||dirty||!!input('feedback-start').value.trim()||!!input('feedback-end').value.trim()||!!select('feedback-category').value||!!input('feedback-target-name').value.trim()&&input('feedback-target-name').value!==data.manifest.id;}
1132
1575
  function controlState():ControlInspection {
1133
1576
  const box=assets?.stage??player?.bounds(),center=viewport.paneFrame('rig')?.center??(box?{x:box.x+box.width/2,y:box.y+box.height/2}:null);
1134
1577
  return {part:parts?.value()??null,partGeneration:parts?.observation()?.generation??null,view:numericView(),theme:appearance?.get()??'system',layout:'auto',effectiveLayout:el('stage-layout').dataset.orientation==='vertical'?'column':'row',cameras:{rig:{zoom:player?viewport.state.zoom:1,pan:{x:center&&viewport.state.cameraCenter?(center.x-viewport.state.cameraCenter.x)*viewport.state.rigScale:0,y:center&&viewport.state.cameraCenter?(viewport.state.cameraCenter.y-center.y)*viewport.state.rigScale:0}},reference:{zoom:referenceSize?viewport.state.referenceZoom:1,pan:{x:referenceSize&&viewport.state.referenceCenter?(referenceSize.width/2-viewport.state.referenceCenter.x)*viewport.state.referenceScale:0,y:referenceSize&&viewport.state.referenceCenter?(referenceSize.height/2-viewport.state.referenceCenter.y)*viewport.state.referenceScale:0}}},animation:animation||null,time,playing,loop:canRepeatIdle()?'idle':'off',layers:{images:!!player&&layers.images,meshes:!!player&&layers.mesh,bones:!!player&&layers.bones},ready:!!data,seeking:seekingControl||!!video?.seeking||!!persistence?.restoring(),dirty:localDraft(),busy:saving||stripBusy||!!persistence?.restoring(),feedbackEligible:!persistence?.restoring(),comparison:controlComparison(layoutEligibility()),capabilities:{camera:!!player,referenceCamera:!!referenceSize,animation:!!player,time:duration>0,playback:duration>0,layers:{images:!!player,meshes:!!player,bones:!!player}}};
@@ -1156,15 +1599,15 @@ async function inspectControlTime(target:number,signal:AbortSignal,preserveSecon
1156
1599
  if(signal.aborted)throw new Error('CONTROL_SUPERSEDED');
1157
1600
  // #191: a control seek is a clip move like the transport's: a seek to 0 restarts the wind clock while the exported world is in use.
1158
1601
  clipMoved({kind:'seek',to:target});
1159
- const media=video;
1160
- if(!media){if(player){player.seek(target);drawRig(()=>player!.draw());}time=target;renderSequenceFrame();renderTransport();return;}
1602
+ const media=activeScene()?null:video;
1603
+ if(!media){time=target;if(player?.current){player.seek(activeScene()?takeSample(activeScene()!,target).sourceTime:target);drawRig(()=>player!.draw());}renderSequenceFrame();renderTransport();return;}
1161
1604
  if(media.readyState<1||target>media.duration)throw new Error('CONTROL_REFERENCE_UNAVAILABLE');
1162
1605
  const previousPosition=media.currentTime;
1163
1606
  const commit=(actual:number)=>{
1164
1607
  if(signal.aborted||media!==video)throw new Error('CONTROL_SUPERSEDED');
1165
1608
  if(!Number.isFinite(actual)||actual<0||actual>duration)throw new Error('CONTROL_TIME_OUTSIDE_DOMAIN');
1166
1609
  const seconds=preserveSeconds?target:actual;
1167
- if(player){player.seek(seconds);drawRig(()=>player!.draw());}time=seconds;
1610
+ if(player?.current){player.seek(seconds);drawRig(()=>player!.draw());}time=seconds;
1168
1611
  controlledVideoSample={media,position:media.currentTime,time:actual};if(axisInspection&&duration>0){const axis=data.manifest.axes.find(item=>item.id===select('axis-select').value&&item.animation===animation);if(axis){const value=axis.min+actual/duration*(axis.max-axis.min);input('axis-value').value=String(value);text('axis-value-label',value.toFixed(3));}}renderSequenceFrame();renderTransport();
1169
1612
  };
1170
1613
  try{const actual=await decodedControlTime(media,target,signal);if(signal.aborted||media!==video)throw new Error('CONTROL_SUPERSEDED');commit(actual);if(Math.abs(actual-target)>1e-6)message(`Reference decoded ${actual.toFixed(4)} s · requested ${target.toFixed(4)} s. The rig and saved view use the decoded timestamp.`);}
@@ -1194,9 +1637,9 @@ async function decodedControlTime(media:HTMLVideoElement,target:number,signal:Ab
1194
1637
  function numericView():ControlView {return viewport.numericView();}
1195
1638
  function inspectionBinding():InspectionBinding{return {mode:'single',sourceHash:data.sourceHash,rigs:[data.reviewedSource.rig?.sha256??null]};}
1196
1639
  // Persist the displayed inspection clock; the runtime clock accumulates across idle loops for physics.
1197
- function inspectionBookmark():InspectionBookmark {return {schema:'rig-review-inspection/1',binding:inspectionBinding(),animation:animation||null,time,theme:appearance?.get()??'system',layers:{images:layers.images,meshes:layers.mesh,bones:layers.bones},view:numericView(),selection:{...(turnPad?{turn:turnPad.snapshot()}:{}),part:parts?.value()??null,view,checkpoint:checkpoint?.id??null,reference:select('reference-select').value||null,person:selectedPerson||null,inspector:selectedInspector()??'view',partSet:select('part-set').disabled?null:select('part-set').value,axis:axisInspection?{id:select('axis-select').value,value:Number(input('axis-value').value)}:null}};}
1198
- async function restoreInspection(bookmark:InspectionBookmark,signal:AbortSignal,preserveSeconds=false):Promise<void> {
1199
- await restoreTransaction(()=>prepareInspection(bookmark,signal),()=>({bookmark:inspectionBookmark(),inputs:captureInputs()}),()=>applyInspection(bookmark,signal,preserveSeconds),async previous=>{await applyInspection(previous.bookmark,new AbortController().signal);restoreInputs(previous.inputs);renderFeedbackRange();});
1640
+ function inspectionBookmark():InspectionBookmark {if(rigDifference)return structuredClone(rigDifference.bookmark);return {schema:'rig-review-inspection/1',binding:inspectionBinding(),animation:animation||null,time,theme:appearance?.get()??'system',layers:{images:layers.images,meshes:layers.mesh,bones:layers.bones},view:numericView(),selection:{...(turnPad?{turn:turnPad.snapshot()}:{}),part:parts?.value()??null,view,checkpoint:checkpoint?.id??null,reference:select('reference-select').value||null,person:selectedPerson||null,inspector:document.querySelector<HTMLElement>('[data-mode][aria-pressed="true"]')?.dataset.mode??selectedInspector()??'rig',partSet:select('part-set').disabled?null:select('part-set').value,axis:axisInspection?{id:select('axis-select').value,value:Number(input('axis-value').value)}:null}};}
1641
+ async function restoreInspection(bookmark:InspectionBookmark,signal:AbortSignal,preserveSeconds=false,keepCamera=true):Promise<void> {
1642
+ await restoreTransaction(()=>prepareInspection(bookmark,signal),()=>({bookmark:inspectionBookmark(),inputs:captureInputs()}),()=>applyInspection(bookmark,signal,preserveSeconds,keepCamera),async previous=>{await applyInspection(previous.bookmark,new AbortController().signal);restoreInputs(previous.inputs);renderFeedbackRange();});
1200
1643
  }
1201
1644
  /** Read the SELECTED reference without replacing the currently inspected DOM/player. */
1202
1645
  async function inspectionReferenceInfo(id:string|null,signal:AbortSignal):Promise<{width:number;height:number;duration:number|null;people:string[]}> {
@@ -1208,11 +1651,18 @@ async function inspectionReferenceInfo(id:string|null,signal:AbortSignal):Promis
1208
1651
  const media=document.createElement('video');media.preload='metadata';media.muted=true;
1209
1652
  try{media.src=referenceUrl(reference);await waitReferenceMetadata(media,signal);return {width:media.videoWidth,height:media.videoHeight,duration:media.duration,people:[]};}finally{media.pause();media.removeAttribute('src');media.load();}
1210
1653
  }
1654
+ /** One duration bound for validation and carried publication navigation. */
1655
+ function inspectionTimeLimit(bookmark:InspectionBookmark,info:{duration:number|null}):number {
1656
+ const selection=bookmark.selection;
1657
+ if(activeScene()&&bookmark.animation===data.scene?.animation)return activeScene()!.take.duration;
1658
+ const clipDuration=bookmark.animation?assets?.animations.find(a=>a.name===bookmark.animation)?.duration:undefined,referenceId=selection.reference===undefined?select('reference-select').value:selection.reference,isVideo=data.manifest.references.find(r=>r.id===referenceId)?.type==='video';
1659
+ return clipDuration===undefined?info.duration??0:isVideo&&info.duration!==null?Math.min(clipDuration,info.duration):clipDuration;
1660
+ }
1211
1661
  async function prepareInspection(bookmark:InspectionBookmark,signal:AbortSignal):Promise<void> {
1212
1662
  const selection=bookmark.selection;
1213
1663
  if(selection.turn){if(!turnPad)throw new Error('TURN_UNAVAILABLE');turnPad.state.validate(selection.turn);}
1214
1664
  parts?.validate(selection.part);
1215
- if(player&&!bookmark.animation||bookmark.animation&&!assets?.animations.some(a=>a.name===bookmark.animation))throw new Error('Saved animation is absent from this rig');
1665
+ if(bookmark.animation&&!assets?.animations.some(a=>a.name===bookmark.animation))throw new Error('Saved animation is absent from this rig');
1216
1666
  if(selection.reference&&!data.manifest.references.some(r=>r.id===selection.reference))throw new Error('Saved reference is not declared');
1217
1667
  if(selection.checkpoint&&!data.manifest.checkpoints.some(c=>c.id===selection.checkpoint))throw new Error('Saved checkpoint is absent');
1218
1668
  const axis=selection.axis?data.manifest.axes.find(a=>a.id===selection.axis!.id):null;
@@ -1221,7 +1671,7 @@ async function prepareInspection(bookmark:InspectionBookmark,signal:AbortSignal)
1221
1671
  if(bookmark.view.cameras.a||bookmark.view.cameras.b||bookmark.view.cameras.rig&&!player)throw new Error('Saved camera is unavailable in this single review');
1222
1672
  const info=await inspectionReferenceInfo(selection.reference===undefined?select('reference-select').value:selection.reference,signal);
1223
1673
  if(selection.person&&!info.people.includes(selection.person))throw new Error('Saved pose person is absent');
1224
- const clipDuration=bookmark.animation?assets?.animations.find(a=>a.name===bookmark.animation)?.duration:undefined,referenceId=selection.reference===undefined?select('reference-select').value:selection.reference,isVideo=data.manifest.references.find(r=>r.id===referenceId)?.type==='video';const limit=clipDuration===undefined?info.duration??0:isVideo&&info.duration!==null?Math.min(clipDuration,info.duration):clipDuration;
1674
+ const limit=inspectionTimeLimit(bookmark,info);
1225
1675
  if(bookmark.time!==null&&(bookmark.time<0||bookmark.time>limit&&limit>=0))throw new Error('Saved inspection time is outside the selected clip/reference');
1226
1676
  const rig=bookmark.view.cameras.rig,ref=bookmark.view.cameras.reference;
1227
1677
  if(rig&&!player)throw new Error('Saved rig camera is unavailable');
@@ -1230,7 +1680,7 @@ async function prepareInspection(bookmark:InspectionBookmark,signal:AbortSignal)
1230
1680
  // Range fitting belongs to the transactional apply after that layout is measured.
1231
1681
  if(signal.aborted)throw new Error('Inspection restore superseded');
1232
1682
  }
1233
- async function applyInspection(bookmark:InspectionBookmark,signal:AbortSignal,preserveSeconds=false):Promise<void> {
1683
+ async function applyInspection(bookmark:InspectionBookmark,signal:AbortSignal,preserveSeconds=false,keepCamera=true):Promise<void> {
1234
1684
  viewport.state.cameraRestoring=true;try{
1235
1685
  const selection=bookmark.selection;
1236
1686
  if(turnPad){if(selection.turn)turnPad.restore(selection.turn);else{turnPad.state.reset();turnPad.restore(turnPad.snapshot());}}
@@ -1239,6 +1689,7 @@ async function applyInspection(bookmark:InspectionBookmark,signal:AbortSignal,pr
1239
1689
  if(selection.checkpoint!==undefined){checkpoint=data.manifest.checkpoints.find(c=>c.id===selection.checkpoint);renderCheckpoint();renderCheckpoints();}
1240
1690
  if(selection.reference!==undefined&&select('reference-select').value!==(selection.reference??'')){select('reference-select').value=selection.reference??'';await showReference(selection.reference??'');if(selection.reference&&!referenceSize&& !video)throw new Error('Saved reference did not load');}
1241
1691
  if(bookmark.animation&&player)chooseAnimation(bookmark.animation);
1692
+ else if(player){restartSetupPlayer(true);player!.clear();animation='';duration=0;time=0;select('animation-select').value='';}
1242
1693
  if(selection.axis){select('axis-select').value=selection.axis.id;chooseAxis();input('axis-value').value=String(selection.axis.value);applyAxis();}
1243
1694
  if(selection.partSet!==undefined&&player){if(selection.partSet||player.sets().length)player.setSet(selection.partSet||null);select('part-set').value=selection.partSet??'';}
1244
1695
  if(bookmark.time!==null){if(video&&video.readyState<1)await waitReferenceMetadata(video,signal);await inspectControlTime(bookmark.time,signal,preserveSeconds);}
@@ -1253,16 +1704,22 @@ async function applyInspection(bookmark:InspectionBookmark,signal:AbortSignal,pr
1253
1704
  const camera=bookmark.view.cameras.rig,ref=bookmark.view.cameras.reference,rigViewport=el('rig-viewport'),referenceViewport=el('reference-viewport');
1254
1705
  const nextZoom=camera&&player&&rigViewport.clientWidth&&rigViewport.clientHeight?restoredZoom(camera,viewport.state.rigScale/viewport.state.zoom,rigViewport.clientWidth,rigViewport.clientHeight):camera?.zoom??null;
1255
1706
  const nextReferenceZoom=ref&&referenceSize&&referenceViewport.clientWidth&&referenceViewport.clientHeight?restoredZoom(ref,viewport.state.referenceScale/viewport.state.referenceZoom,referenceViewport.clientWidth,referenceViewport.clientHeight):ref?.zoom??null;
1707
+ // A job rig subject opens at Fit (#709): the bookmark camera was saved at another window size, so opening requests the Fit instead.
1708
+ if(keepCamera){viewport.cancelFit();
1256
1709
  if(nextZoom!==null&&camera){viewport.state.zoom=nextZoom;viewport.state.cameraCenter={...camera.center};}
1257
- if(nextReferenceZoom!==null&&ref){viewport.state.referenceZoom=nextReferenceZoom;viewport.state.referenceCenter={...ref.center};}
1710
+ if(nextReferenceZoom!==null&&ref){viewport.state.referenceZoom=nextReferenceZoom;viewport.state.referenceCenter={...ref.center};}}
1258
1711
  viewport.state.cameraSync=bookmark.view.cameraSync??false;viewport.state.activeCamera=bookmark.view.activeCamera==='reference'?'reference':'rig';
1259
1712
  if(player)drawRig(()=>player!.draw());if(selection.part)parts?.assertIdentity(selection.part);fitCamera();redrawOverlay(false);pause();renderTransport();renderCameraControls();
1260
1713
  }finally{viewport.state.cameraRestoring=false;}
1714
+ if(!keepCamera){viewport.requestFit();fitCamera();}
1261
1715
  }
1262
1716
  async function waitReferenceMetadata(media:HTMLVideoElement,signal:AbortSignal):Promise<void> {if(media.readyState>=1)return;await new Promise<void>((resolve,reject)=>{const clean=()=>{clearTimeout(timer);media.removeEventListener('loadedmetadata',ready);media.removeEventListener('error',fail);signal.removeEventListener('abort',fail);};const ready=()=>{clean();resolve();},fail=()=>{clean();reject(new Error('Saved reference metadata unavailable'));};const timer=setTimeout(fail,10000);media.addEventListener('loadedmetadata',ready,{once:true});media.addEventListener('error',fail,{once:true});signal.addEventListener('abort',fail,{once:true});});}
1263
- async function setupPersistence():Promise<boolean> {
1264
- persistence=await connectInspectionPersistence({scope:'single:'+data.manifest.id+':'+data.sourceHash,binding:inspectionBinding(),baseline:submittedBaseline!,session:()=>session,reviewDirty:()=>dirty,restoreSession:(value,isDirty)=>{session=value;dirty=isDirty;select('review-status').value=session.status;renderProposals();renderCheckpoint();renderCheckpoints();renderProvenance();updateSavedState();},bookmark:inspectionBookmark,restoreBookmark:(b,s)=>restoreInspection(b,s,session.feedback.some(f=>isTimeOnlyFeedback(f)&&JSON.stringify((f.context as any).comment.bookmark)===JSON.stringify(b))),
1265
- ui:()=>({inspectorScroll:workspace?.scroll()??'{}',...(inspectorBlocks?activeBlocksUI(inspectorBlocks.state()):{}),reportCategory:select('report-category').value,reportPage,reportEvent:selectedReportEvent?.id??null,reportTime:selectedReportTime??null,reportTarget:selectedReportTarget??null}),restoreUI:value=>{if(typeof value.reportCategory==='string'&&[...select('report-category').options].some(o=>o.value===value.reportCategory))select('report-category').value=value.reportCategory;if(typeof value.reportPage==='number'&&Number.isSafeInteger(value.reportPage)&&value.reportPage>=0)reportPage=value.reportPage;selectedReportEvent=typeof value.reportEvent==='string'?data.report?.categories.flatMap(c=>c.events).find(e=>e.id===value.reportEvent)??null:null;selectedReportTime=typeof value.reportTime==='number'?value.reportTime:undefined;selectedReportTarget=typeof value.reportTarget==='number'?value.reportTarget:undefined;renderReportEvents();renderReportSelection();inspectorBlocks?.restore(restoreActiveBlocksUI(value));workspace?.restoreScroll(value.inspectorScroll);},afterInputs:()=>{const target=input('feedback-target-name').value;renderFeedbackTargets(true);if(select('feedback-target-kind').value!=='rig')input('feedback-target-name').value=target;renderFeedbackRange();text('audio-volume-label',`${Math.round(Number(input('audio-volume').value)*100)}%`);},onConflict:value=>{draftConflict=value;updateSavedState();},onStatus:value=>{text('draft-state',value);el('draft-state').title=value;text('review-draft-state',value);}});
1717
+ let inspectionOpening=false;
1718
+ async function setupPersistence(keepCameraOnResume=false):Promise<boolean> {
1719
+ inspectionOpening=true;try{
1720
+ persistence=await connectInspectionPersistence({scope:'single:'+data.manifest.id+':'+data.sourceHash,binding:inspectionBinding(),baseline:submittedBaseline!,session:()=>session,reviewDirty:()=>dirty,restoreSession:(value,isDirty)=>{session=value;dirty=isDirty;select('review-status').value=session.status;renderProposals();renderCheckpoint();renderCheckpoints();renderProvenance();updateSavedState();},bookmark:inspectionBookmark,restoreBookmark:(b,s)=>restoreInspection(b,s,session.feedback.some(f=>isTimeOnlyFeedback(f)&&JSON.stringify((f.context as any).comment.bookmark)===JSON.stringify(b)),keepCameraOnResume||bookmarkCameraKept(inspectionOpening,!!host)),
1721
+ ui:()=>({inspectorScroll:workspace?.scroll()??'{}',...(inspectorBlocks?activeBlocksUI(inspectorBlocks.state()):{}),reportCategory:select('report-category').value,reportPage,reportEvent:selectedReportEvent?.id??null,reportTime:selectedReportTime??null,reportTarget:selectedReportTarget??null}),restoreUI:value=>{if(typeof value.reportCategory==='string'&&[...select('report-category').options].some(o=>o.value===value.reportCategory))select('report-category').value=value.reportCategory;if(typeof value.reportPage==='number'&&Number.isSafeInteger(value.reportPage)&&value.reportPage>=0)reportPage=value.reportPage;selectedReportEvent=typeof value.reportEvent==='string'?data.report?.categories.flatMap(c=>c.events).find(e=>e.id===value.reportEvent)??null:null;selectedReportTime=typeof value.reportTime==='number'?value.reportTime:undefined;selectedReportTarget=typeof value.reportTarget==='number'?value.reportTarget:undefined;renderReportEvents();renderReportSelection();inspectorBlocks?.restore(restoreActiveBlocksUI(value));workspace?.restoreScroll(value.inspectorScroll);},afterInputs:()=>{const target=input('feedback-target-name').value;renderFeedbackTargets(true);if(select('feedback-target-kind').value!=='rig')input('feedback-target-name').value=target;renderFeedbackRange();text('audio-volume-label',`${Math.round(Number(input('audio-volume').value)*100)}%`);},onConflict:value=>{draftConflict=value;updateSavedState();},onStatus:value=>{draftStatus=value;renderDraftState();}});
1722
+ }finally{inspectionOpening=false;}
1266
1723
  return persistence.restored;
1267
1724
  }
1268
1725
  /** Setup's Chest regions tool: designation values, an overlay and a two-file client download. Nothing reaches the session's feedback or the package. */
@@ -1826,7 +2283,7 @@ async function applyPatch(patch:ConfigPatch,world:StageWorld|null=null):Promise<
1826
2283
  finally{rebuildBusy=false;rebuildState();}
1827
2284
  }
1828
2285
  /** The client's edit entry point for automation and the edit cards to come: apply a patch, return to the inspected build, read the stage. */
1829
- (window as unknown as {rigReviewEditor:unknown}).rigReviewEditor={
2286
+ (window as unknown as {rigReviewEditor:unknown}).rigReviewEditor=publicEditor={
1830
2287
  applyPatch,reset:()=>resetRebuild(),
1831
2288
  /** #166: undo the last Apply, and the applied records as the server holds them. */
1832
2289
  undo:()=>undoApply(),history:()=>appliedHistory?JSON.parse(JSON.stringify(appliedHistory)):null,
@@ -2278,10 +2735,9 @@ async function swapRig(modelUrl:string,prefix:string,sha256:string,world:StageWo
2278
2735
  inspectionSourceState='pending';partModel=null;pause();refreshAnimationInspection();
2279
2736
  const next=await loadModel({modelUrl,...stageLoadInputs(modelUrl,sha256),resolvePage:(name,url)=>{const target=new URL(name,url);if(target.origin!==location.origin||!target.pathname.startsWith(prefix))throw new Error(`Model page escapes its build: ${name}`);return target.href;}}).catch(error=>{inspectionSourceState='failed';refreshAnimationInspection();throw error;});
2280
2737
  physicsPanel?.clearPreview();
2281
- pause();player?.dispose();assets?.dispose();assets=next;player=new RigPlayer(el('rig-root'),assets);setupChestWorld=readSetupChest(player);stageModelHash=sha256;stageSource={url:modelUrl,prefix,hash:sha256};
2738
+ pause();player?.dispose();assets?.dispose();assets=next;player=createInspectionPlayer(el('rig-root'),assets);setupChestWorld=readSetupChest(player);stageModelHash=sha256;stageSource={url:modelUrl,prefix,hash:sha256};
2282
2739
  // A scratch build may hold another set of animations (a retarget adds one, #114): the picker lists what this build has.
2283
2740
  {const animations=select('animation-select');animations.replaceChildren(...assets.animations.map(item=>option(item.name,data.manifest.animations.find(a=>a.id===item.name)?.label??item.name)));animations.disabled=assets.animations.length===0;}
2284
- player.on('event',event=>{text('event-log',`Runtime event: ${event.name} · ${event.time.toFixed(2)} s`);});
2285
2741
  try{const catalog=await loadPartModel(modelUrl,sha256,data.feedbackCatalog.slots??[]);inspectionSourceState='ready';partModel=catalog.model;configureTurnPad(catalog.model);refreshAnimationInspection();weightsView?.refresh();meshEditor?.selectionChanged();parts?.register('single',catalog.entries,player,new PartThumbnails(pageRegionTable(catalog.model),assets.pageImages));}catch(error){inspectionSourceState='failed';partModel=null;refreshAnimationInspection();parts?.refuseCatalog('single',error);}
2286
2742
  configurePartSets(keepSet);
2287
2743
  // The same world before the first pose: a physics Apply resumes the wind (clock and pulse), the pending jolts, gravity and
@@ -2448,6 +2904,7 @@ void start();
2448
2904
 
2449
2905
  /** Only live, unrecorded authoring effects block capture; unsent form ops alone do not. */
2450
2906
  function commentCaptureRefusal():string|null {
2907
+ if(rigDifference)return 'RIG_DIFFERENCE_COMMENT_UNAVAILABLE: return to Rig or Reference before adding a comment.';
2451
2908
  if(appliedOnStage)return 'COMMENT_APPLIED_BUILD_UNSUPPORTED: return to the inspected source before commenting on this applied scratch build';
2452
2909
  if(rebuildBusy)return 'COMMENT_SOURCE_BUSY: wait for the rebuild or candidate model replacement before commenting';
2453
2910
  const preview=idleAdjust?'Idle tracks':typeof animAdjust!=='undefined'&&animAdjust?'Keyed animation preview':dialAdjust?'Rig fields turn dial':physicsPreview.read().length?'Physics live overrides':stripPending?'Density strip candidate':
@@ -2458,15 +2915,16 @@ function commentCaptureRefusal():string|null {
2458
2915
  return preview?`COMMENT_UNAPPLIED_PREVIEW: ${preview} is active; leave or disable that preview before commenting (nothing is cleared or applied automatically)`:null;
2459
2916
  }
2460
2917
  function setupComments():void {
2461
- comments=bindStageComments({toolbar:el('stage-comment').parentElement!,viewports:{rig:el('rig-viewport'),reference:el('reference-viewport')},
2918
+ if(host?.direction||host?.record){restoreRecordComments();liveIssueCount=()=>recordComments.length;if(host?.direction)dirty=dirty||recordComments.length>0;}
2919
+ 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'),toolbar:el('stage-comment').parentElement!,viewports:host?.record&&!host.record.hasPicture?{}:{rig:el('rig-viewport'),reference:el('reference-viewport')},
2462
2920
  pose:view=>{
2463
2921
  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;
2464
2922
  const renderer=player?.renderer;const current=time,index=frameAtTime(activeFrameClock(),current),referenceId=view==='reference'?select('reference-select').value||null:null,referenceHash=referenceId?data.referenceHashes?.[referenceId]??(data.explicitReference?.id===referenceId?data.explicitReference.sha256:null):null;
2465
2923
  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;
2466
2924
  },
2467
- 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:()=>session.feedback,
2468
- locked:id=>!!submittedBaseline?.updatedAt&&submittedBaseline.feedback.some(f=>f.id===id),add:f=>session.feedback.push(f),changed:()=>{markDirty();renderProposals();persistence?.save();},error:value=>message(value,true),
2469
- refusal:commentCaptureRefusal,blocked:()=>saving||!!persistence?.restoring()||seekingControl||!!video?.seeking||!!rebuildBusy||!!appliedOnStage,shortcutBlocked:()=>!!meshEditor?.active()
2925
+ 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,
2926
+ 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();persistence?.save();},error:value=>message(value,true),
2927
+ refusal:()=>host?.record&&!host.record.hasPicture?null:commentCaptureRefusal(),blocked:()=>saving||!!persistence?.restoring()||seekingControl||!!video?.seeking||!!rebuildBusy||!!appliedOnStage,shortcutBlocked:()=>!!meshEditor?.active()
2470
2928
  });
2471
2929
  }
2472
2930
 
@@ -2608,7 +3066,7 @@ async function prepareStageDraftBuild(
2608
3066
  // Release the previous renderer's root clip while retaining its pose and views for rollback.
2609
3067
  prevPlayer?.renderer.render({order:[]});
2610
3068
  rigRoot.replaceChildren();
2611
- nextPlayer=new RigPlayer(rigRoot,nextAssets);
3069
+ nextPlayer=createInspectionPlayer(rigRoot,nextAssets);
2612
3070
  // A fresh player's draw has no held pose. Clearing track 0 publicly poses Setup.
2613
3071
  nextPlayer.clear();
2614
3072
  const nextSetupChest=readSetupChest(nextPlayer);
@@ -2645,7 +3103,6 @@ async function prepareStageDraftBuild(
2645
3103
  animSelect.disabled=nextAssets.animations.length===0;
2646
3104
  animSelect.value='';
2647
3105
  }
2648
- nextPlayer.on('event',event=>{text('event-log',`Runtime event: ${event.name} · ${event.time.toFixed(2)} s`);});
2649
3106
  if(partSetNode)configurePartSets(keepSet);
2650
3107
  if(options?.world){
2651
3108
  wind.resume(options.world.wind);
@@ -2765,3 +3222,9 @@ async function openStageCorrection(request:{part:string;sourceHash:string;buildI
2765
3222
  redrawOverlay(true);
2766
3223
  message(tr('Draft rig · structure evidence only')+tr(` · ${mapping.part} · rig-parts remesh ${request.instrument==='delta'?'--delta':'--mesh'}`));
2767
3224
  }
3225
+
3226
+ return {dispose:disposeScreen};
3227
+ }
3228
+
3229
+ // Package entries mount directly; the live host invokes this same composition for each publication.
3230
+ if(!rigHost()){if(/^\/jobs\/[^/]+\/$/.test(location.pathname))void mountJobScreen(document.body);else mountRigScreen();}