@rig-c/review 2.7.1 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,19 @@
1
1
  /** Live job window transactions. Every form remains bound to its displayed publication. */
2
- import type { JobAct, JobDisplayPublication, JobDisplayReceipt, JobEvent, JobPendingAsk, JobPublication, JobResult, JobUISubmission, JobSourceBinding, } from '../src/job-contract.ts';
2
+ import { parseControlPart, type ControlPart } from '../src/control.ts';
3
+ import type {
4
+ ActV3,
5
+ DisplayPublicationV3,
6
+ EventV3,
7
+ JobDisplayReceipt,
8
+ JobInterviewDiagnostics,
9
+ JobResult,
10
+ JobUISubmission,
11
+ PendingAskV3,
12
+ PublicationV3,
13
+ RecordSource,
14
+ SourceV3,
15
+ UISubmissionV3,
16
+ } from '../src/job-contract.ts';
3
17
  import {enCatalog} from './catalog-en.ts';
4
18
  import {koCatalog} from './catalog-ko.ts';
5
19
  import {t} from './i18n.ts';
@@ -20,13 +34,13 @@ export function jobWindowRefusal(error: unknown, fallback = 'JOB_WINDOW_FAILED')
20
34
  return t(fallback);
21
35
  }
22
36
  export interface JobWindowTransport {
23
- readPublication(publicationId: string, signal?: AbortSignal): Promise<JobResult<JobDisplayPublication>>;
37
+ readPublication(publicationId: string, signal?: AbortSignal): Promise<JobResult<DisplayPublicationV3>>;
24
38
  acknowledge(input: {
25
39
  publicationId: string;
26
40
  pageId: string;
27
41
  sourceHash: string;
28
42
  }, signal: AbortSignal): Promise<JobResult<JobDisplayReceipt>>;
29
- submit(input: JobUISubmission): Promise<JobResult<JobAct>>;
43
+ submit(input: UISubmissionV3): Promise<JobResult<ActV3>>;
30
44
  }
31
45
  export interface JobPreparedCommit {
32
46
  /** Restore the previous view, including its original forms and route bindings. */
@@ -36,10 +50,10 @@ export interface JobPreparedCommit {
36
50
  }
37
51
  export interface JobWindowAdapter<Prepared> {
38
52
  /** Resolve assets, metadata, forms and publication-pinned routes before returning. */
39
- prepare(display: JobDisplayPublication, signal: AbortSignal): Promise<Prepared>;
53
+ prepare(display: DisplayPublicationV3, signal: AbortSignal): Promise<Prepared>;
40
54
  /** Called immediately before commit, so edits made during preloading are retained. */
41
55
  captureDraft(): unknown | null;
42
- commit(prepared: Prepared, display: JobDisplayPublication): JobPreparedCommit;
56
+ commit(prepared: Prepared, display: DisplayPublicationV3): JobPreparedCommit;
43
57
  painted(prepared: Prepared, signal: AbortSignal): Promise<void>;
44
58
  discard(prepared: Prepared): void;
45
59
  changed(state: JobWindowState): void;
@@ -47,19 +61,19 @@ export interface JobWindowAdapter<Prepared> {
47
61
  export interface JobRetainedDraft {
48
62
  readonly publicationId: string;
49
63
  readonly sourceHash: string;
50
- readonly source?: JobSourceBinding;
64
+ readonly source?: SourceV3;
51
65
  readonly label: string;
52
66
  readonly value: unknown;
53
67
  }
54
68
  export interface JobWindowState {
55
69
  readonly generation: number;
56
- readonly displayed: JobDisplayPublication | null;
70
+ readonly displayed: DisplayPublicationV3 | null;
57
71
  readonly receipt: JobDisplayReceipt | null;
58
72
  readonly preparing: boolean;
59
73
  readonly closed: boolean;
60
74
  readonly error: string | null;
61
75
  readonly previousLabel: string | null;
62
- readonly pending: readonly JobPendingAsk[];
76
+ readonly pending: readonly PendingAskV3[];
63
77
  readonly retainedDrafts: readonly JobRetainedDraft[];
64
78
  }
65
79
  function unwrap<Value>(result: JobResult<Value>): Value {
@@ -67,7 +81,10 @@ function unwrap<Value>(result: JobResult<Value>): Value {
67
81
  throw new Error(result.error.code);
68
82
  return result.value;
69
83
  }
70
- function sourceSnapshot(source: JobSourceBinding): string {
84
+ function isRecordSource(source: SourceV3): source is RecordSource {
85
+ return source.subject === 'option-set' || source.subject === 'plan';
86
+ }
87
+ function sourceSnapshot(source: unknown): string {
71
88
  return JSON.stringify(source, (_key, value: unknown) => {
72
89
  if (value === null || typeof value !== 'object' || Array.isArray(value))
73
90
  return value;
@@ -75,8 +92,9 @@ function sourceSnapshot(source: JobSourceBinding): string {
75
92
  return Object.fromEntries(Object.keys(record).sort().map(key => [key, record[key]]));
76
93
  });
77
94
  }
78
- function assertJobAskSource(ask: JobPendingAsk, display: JobDisplayPublication): void {
79
- const source = ask.subject.kind === 'interview-picks'
95
+ function assertJobAskSource(ask: PendingAskV3, display: DisplayPublicationV3): void {
96
+ const source: SourceV3 = ask.subject.kind === 'interview-picks' &&
97
+ !isRecordSource(display.publication.source) && !isRecordSource(ask.source)
80
98
  ? { ...ask.source, optionSet: display.publication.source.optionSet }
81
99
  : ask.source;
82
100
  if (sourceSnapshot(source) !== sourceSnapshot(display.publication.source)) {
@@ -90,9 +108,9 @@ function assertJobAskSource(ask: JobPendingAsk, display: JobDisplayPublication):
90
108
 
91
109
  /** Build pending form dependencies off-stage. A failure rejects the candidate before it is displayed. */
92
110
  export function prepareJobForms<Form>(
93
- display: JobDisplayPublication,
94
- asks: readonly JobPendingAsk[],
95
- prepare: (ask: JobPendingAsk) => Form,
111
+ display: DisplayPublicationV3,
112
+ asks: readonly PendingAskV3[],
113
+ prepare: (ask: PendingAskV3) => Form,
96
114
  ): Map<string, Form> {
97
115
  const prepared = new Map<string, Form>();
98
116
  for (const ask of asks) {
@@ -105,12 +123,12 @@ export function prepareJobForms<Form>(
105
123
 
106
124
  /** C2 publishes the plan mapping in the ask. Legacy checkpoint metadata is optional guidance. */
107
125
  export function jobCheckpointContext(
108
- ask: JobPendingAsk,
126
+ ask: PendingAskV3,
109
127
  checkpoints: readonly Pick<Checkpoint, 'id' | 'title' | 'note'>[],
110
128
  ) {
111
129
  if (ask.subject.kind !== 'checkpoint') throw new Error('JOB_ASK_INVALID');
112
130
  const checkpointId = ask.subject.checkpointId;
113
- const planStepId = ask.subject.planStepId ?? checkpointId;
131
+ const planStepId = ('planStepId' in ask.subject ? ask.subject.planStepId : undefined) ?? checkpointId;
114
132
  const step = ask.source.plan?.steps.find(item => item.id === planStepId);
115
133
  if (!step) throw new Error('JOB_ASK_INVALID');
116
134
  const checkpoint = checkpoints.find(item => item.id === checkpointId);
@@ -127,17 +145,26 @@ export function createJobWindow<Prepared>(options: {
127
145
  pageId: string;
128
146
  transport: JobWindowTransport;
129
147
  adapter: JobWindowAdapter<Prepared>;
148
+ previousDisplayed?: {
149
+ readonly publicationId: string;
150
+ readonly label: string;
151
+ readonly previousLabel: string | null;
152
+ } | null;
153
+ initialRetainedDrafts?: readonly JobRetainedDraft[];
130
154
  }) {
131
155
  const { transport, adapter, pageId } = options;
132
- const pending = new Map<string, JobPendingAsk>();
133
- const rigAttempts = new WeakSet<JobUISubmission>();
156
+ const pending = new Map<string, PendingAskV3>();
157
+ const rigAttempts = new WeakSet<UISubmissionV3>();
134
158
  const retainedDrafts: JobRetainedDraft[] = [];
159
+ let initialDrafts: readonly JobRetainedDraft[] | null = options.initialRetainedDrafts
160
+ ? [...options.initialRetainedDrafts] : null;
135
161
  let generation = 0;
136
- let displayed: JobDisplayPublication | null = null;
162
+ let displayed: DisplayPublicationV3 | null = null;
137
163
  let receipt: JobDisplayReceipt | null = null;
138
164
  let preparing = false;
139
165
  let closed = false;
140
- let error: string | null = null;
166
+ let error: string | null;
167
+ error = null;
141
168
  let previousLabel: string | null = null;
142
169
  let intent = 0;
143
170
  let stopped = false;
@@ -150,7 +177,7 @@ export function createJobWindow<Prepared>(options: {
150
177
  };
151
178
  }
152
179
  function changed(): void { adapter.changed(state()); }
153
- function replace(publication: JobPublication): Promise<void> {
180
+ function replace(publication: PublicationV3): Promise<void> {
154
181
  if (stopped)
155
182
  return Promise.resolve();
156
183
  const revision = ++intent;
@@ -166,14 +193,16 @@ export function createJobWindow<Prepared>(options: {
166
193
  let prepared: Prepared | undefined;
167
194
  let committed: JobPreparedCommit | undefined;
168
195
  try {
169
- if (publication.visual.status !== 'available')
196
+ if (publication.visual.status !== 'available' && !isRecordSource(publication.source))
170
197
  throw new Error(publication.visual.code);
171
198
  const candidate = unwrap(await transport.readPublication(publication.publicationId, abort.signal));
172
199
  if (candidate.publication.publicationId !== publication.publicationId ||
173
200
  candidate.publication.source.sourceHash !== publication.source.sourceHash ||
174
201
  candidate.publication.instanceKey !== publication.instanceKey ||
175
202
  candidate.publication.generation !== publication.generation ||
176
- sourceSnapshot(candidate.publication.source) !== sourceSnapshot(publication.source)) {
203
+ sourceSnapshot(candidate.publication.source) !== sourceSnapshot(publication.source) ||
204
+ (publication.interview !== undefined &&
205
+ sourceSnapshot(candidate.publication.interview) !== sourceSnapshot(publication.interview))) {
177
206
  throw new Error('JOB_DISPLAY_MISMATCH');
178
207
  }
179
208
  prepared = await adapter.prepare(candidate, abort.signal);
@@ -194,16 +223,42 @@ export function createJobWindow<Prepared>(options: {
194
223
  acknowledged.pageId !== pageId || !acknowledged.displayedNonce) {
195
224
  throw new Error('JOB_DISPLAY_MISMATCH');
196
225
  }
226
+ if (initialDrafts) {
227
+ for (const item of initialDrafts) {
228
+ if (item.publicationId !== candidate.publication.publicationId &&
229
+ !retainedDrafts.some(existing => existing.publicationId === item.publicationId)) {
230
+ retainedDrafts.push(structuredClone(item));
231
+ }
232
+ }
233
+ initialDrafts = null;
234
+ }
235
+ for (let index = retainedDrafts.length - 1; index >= 0; index--) {
236
+ if (retainedDrafts[index]?.publicationId === candidate.publication.publicationId)
237
+ retainedDrafts.splice(index, 1);
238
+ }
197
239
  if (displayed && draft !== null) {
198
- retainedDrafts.push({
240
+ const nextDraft: JobRetainedDraft = {
199
241
  publicationId: displayed.publication.publicationId,
200
242
  sourceHash: displayed.publication.source.sourceHash,
201
243
  source: structuredClone(displayed.publication.source),
202
244
  label: displayed.publication.label,
203
245
  value: structuredClone(draft),
204
- });
246
+ };
247
+ const existing = retainedDrafts.findIndex(item => item.publicationId === nextDraft.publicationId);
248
+ if (existing >= 0) retainedDrafts[existing] = nextDraft;
249
+ else retainedDrafts.push(nextDraft);
250
+ }
251
+ if (displayed) {
252
+ previousLabel = displayed.publication.label;
253
+ }
254
+ else if (options.previousDisplayed) {
255
+ previousLabel = options.previousDisplayed.publicationId === candidate.publication.publicationId
256
+ ? options.previousDisplayed.previousLabel
257
+ : options.previousDisplayed.label;
258
+ }
259
+ else {
260
+ previousLabel = null;
205
261
  }
206
- previousLabel = displayed?.publication.label ?? null;
207
262
  displayed = candidate;
208
263
  receipt = acknowledged;
209
264
  const cleanup = committed;
@@ -232,7 +287,7 @@ export function createJobWindow<Prepared>(options: {
232
287
  });
233
288
  return queue;
234
289
  }
235
- function event(value: JobEvent): void {
290
+ function event(value: EventV3): void {
236
291
  if (stopped || value.jobId !== options.jobId)
237
292
  return;
238
293
  generation = Math.max(generation, value.generation);
@@ -258,7 +313,7 @@ export function createJobWindow<Prepared>(options: {
258
313
  }
259
314
  changed();
260
315
  }
261
- async function submit(input: JobUISubmission): Promise<JobResult<JobAct>> {
316
+ async function submit(input: UISubmissionV3): Promise<JobResult<ActV3>> {
262
317
  if (closed)
263
318
  return { ok: false, error: { code: 'JOB_CLOSED', message: 'JOB_CLOSED' } };
264
319
  const ask = pending.get(input.askId);
@@ -334,7 +389,7 @@ export function jobWindowAccess(href: string, storage: Pick<Storage, 'getItem' |
334
389
  };
335
390
  }
336
391
  /** Resolve only the publication's explicit immutable instance routes. */
337
- export function jobPublicationRoutes(display: JobDisplayPublication, origin: string) {
392
+ export function jobPublicationRoutes(display: DisplayPublicationV3, origin: string) {
338
393
  const key = display.publication.instanceKey;
339
394
  if (!/^[a-f0-9]{64}$/.test(key))
340
395
  throw new Error('JOB_DISPLAY_MISMATCH');
@@ -408,7 +463,7 @@ export function createJobWindowTransport(access: JobWindowAccess, fetcher: typeo
408
463
  };
409
464
  }
410
465
  /** Bounded newline events. Reconnects resume after the last fully parsed event. */
411
- export async function* jobWindowEvents(access: JobWindowAccess, after: string | null, signal: AbortSignal, fetcher: typeof fetch = fetch): AsyncGenerator<JobEvent> {
466
+ export async function* jobWindowEvents(access: JobWindowAccess, after: string | null, signal: AbortSignal, fetcher: typeof fetch = fetch): AsyncGenerator<EventV3> {
412
467
  const path = 'events' + (after === null ? '' : '?after=' + encodeURIComponent(after));
413
468
  const response = await fetcher(access.route(path), { signal, headers: access.headers() });
414
469
  if (!response.ok || !response.body)
@@ -431,7 +486,7 @@ export async function* jobWindowEvents(access: JobWindowAccess, after: string |
431
486
  while (newline >= 0) {
432
487
  if (newline > limit)
433
488
  throw new Error('JOB_BODY_LIMIT');
434
- const event = JSON.parse(buffered.slice(0, newline)) as JobEvent;
489
+ const event = JSON.parse(buffered.slice(0, newline)) as EventV3;
435
490
  if (!event || event.jobId !== access.jobId || typeof event.cursor !== 'string' ||
436
491
  !Number.isSafeInteger(event.generation) || event.generation < 0 ||
437
492
  !['published', 'pending', 'act', 'closed'].includes(event.type))
@@ -454,7 +509,7 @@ export function startJobWindowEvents(options: {
454
509
  access: JobWindowAccess;
455
510
  signal: AbortSignal;
456
511
  member: boolean;
457
- event(value: JobEvent): void;
512
+ event(value: EventV3): void;
458
513
  refused(error: unknown): void;
459
514
  fetcher?: typeof fetch;
460
515
  }) {
@@ -512,6 +567,7 @@ import type { FeedbackCatalog } from '../src/feedback-validation.ts';
512
567
  import type { InterviewQuestion } from '../src/interview-project.ts';
513
568
  export interface JobInspectionMetadata {
514
569
  manifest: ReviewManifest;
570
+ recordSource?: undefined;
515
571
  sourceHash: string;
516
572
  reviewedSource: ReviewedSource;
517
573
  setsHash?: string;
@@ -531,6 +587,24 @@ export interface JobInspectionMetadata {
531
587
  };
532
588
  feedbackCatalog: Pick<FeedbackCatalog, 'slots'>;
533
589
  }
590
+ export interface JobRecordInspectionMetadata {
591
+ manifest?: undefined;
592
+ recordSource: RecordSource;
593
+ sourceHash: string;
594
+ reviewedSource?: undefined;
595
+ setsHash?: undefined;
596
+ initialAnimation?: null;
597
+ direction?: undefined;
598
+ referenceHashes?: undefined;
599
+ sourcePainting?: undefined;
600
+ capabilities: {
601
+ interview?: boolean;
602
+ preRig?: boolean;
603
+ playback: boolean;
604
+ };
605
+ feedbackCatalog: Pick<FeedbackCatalog, 'slots'>;
606
+ }
607
+ export type JobInspectionMetadataV3 = JobInspectionMetadata | JobRecordInspectionMetadata;
534
608
  type JobInterview = {
535
609
  questions: (Omit<InterviewQuestion, 'images'> & {
536
610
  images: {
@@ -538,6 +612,7 @@ type JobInterview = {
538
612
  url: string;
539
613
  }[];
540
614
  })[];
615
+ interview?: JobInterviewDiagnostics | null;
541
616
  };
542
617
  interface JobPartsInventory {
543
618
  sourceHash: string;
@@ -606,8 +681,8 @@ export function createJobReferenceSelection<Reference extends Pick<JobReferenceV
606
681
  }
607
682
 
608
683
  export interface JobPreparedInspection {
609
- display: JobDisplayPublication;
610
- metadata: JobInspectionMetadata;
684
+ display: DisplayPublicationV3;
685
+ metadata: JobInspectionMetadataV3;
611
686
  interview: JobInterview | null;
612
687
  parts: JobPartsInventory | null;
613
688
  partImages: Map<string, HTMLImageElement>;
@@ -683,12 +758,21 @@ function mediaReady(media: HTMLVideoElement, name: 'loadeddata' | 'seeked', sign
683
758
  });
684
759
  }
685
760
  /** Prepare the real published Play model, references and every form dependency off-stage. */
686
- export async function prepareJobInspection(display: JobDisplayPublication, signal: AbortSignal): Promise<JobPreparedInspection> {
761
+ export async function prepareJobInspection(display: DisplayPublicationV3, signal: AbortSignal): Promise<JobPreparedInspection> {
687
762
  const routes = jobPublicationRoutes(display, location.origin);
688
- const metadata = await jobJson<JobInspectionMetadata>(routes.api('review'), signal);
689
- if (metadata.manifest.id !== display.publication.source.package.id ||
690
- metadata.manifest.revision !== display.publication.source.package.revision ||
691
- (metadata.reviewedSource.rig?.sha256 ?? null) !== (display.publication.source.model?.sha256 ?? null)) {
763
+ const metadata = await jobJson<JobInspectionMetadataV3>(routes.api('review'), signal);
764
+ const publishedSource = display.publication.source;
765
+ if (isRecordSource(publishedSource)) {
766
+ if (!metadata.recordSource || metadata.manifest !== undefined || metadata.reviewedSource !== undefined ||
767
+ metadata.sourceHash !== publishedSource.sourceHash ||
768
+ sourceSnapshot(metadata.recordSource) !== sourceSnapshot(publishedSource)) {
769
+ throw new Error('JOB_DISPLAY_MISMATCH');
770
+ }
771
+ }
772
+ else if (!metadata.manifest || !metadata.reviewedSource ||
773
+ metadata.manifest.id !== publishedSource.package.id ||
774
+ metadata.manifest.revision !== publishedSource.package.revision ||
775
+ (metadata.reviewedSource.rig?.sha256 ?? null) !== (publishedSource.model?.sha256 ?? null)) {
692
776
  throw new Error('JOB_DISPLAY_MISMATCH');
693
777
  }
694
778
  const objectUrls: string[] = [];
@@ -740,6 +824,10 @@ export async function prepareJobInspection(display: JobDisplayPublication, signa
740
824
  }
741
825
  try {
742
826
  const interview = metadata.capabilities.interview ? await jobJson<JobInterview>(routes.api('interview'), signal) : null;
827
+ if (interview?.interview !== undefined && display.publication.interview !== undefined &&
828
+ sourceSnapshot(interview.interview) !== sourceSnapshot(display.publication.interview)) {
829
+ throw new Error('JOB_DISPLAY_MISMATCH');
830
+ }
743
831
  const parts = metadata.capabilities.preRig ? await jobJson<JobPartsInventory>(routes.api('stage-parts'), signal) : null;
744
832
  const references: JobReferenceView[] = [];
745
833
  const partImages = new Map<string, HTMLImageElement>();
@@ -748,7 +836,7 @@ export async function prepareJobInspection(display: JobDisplayPublication, signa
748
836
  const imageSetImages: HTMLImageElement[] = [];
749
837
  const source = display.publication.source;
750
838
  if (source.subject === 'image-set') {
751
- if (metadata.sourceHash !== source.sourceHash || metadata.manifest.model)
839
+ if (metadata.sourceHash !== source.sourceHash || metadata.manifest?.model)
752
840
  throw new Error('JOB_DISPLAY_MISMATCH');
753
841
  const canonical = source.imageSet.images.map(({role, name, sha256}) => ({role, name, sha256}));
754
842
  if (source.imageSet.images.length < 2 || source.imageSet.images.length > 8 ||
@@ -761,7 +849,7 @@ export async function prepareJobInspection(display: JobDisplayPublication, signa
761
849
  }));
762
850
  }
763
851
  }
764
- for (const reference of metadata.manifest.references) {
852
+ for (const reference of metadata.manifest?.references ?? []) {
765
853
  preload.push((async () => {
766
854
  if (reference.type === 'image') {
767
855
  const element = await image(routes.asset(reference.path), metadata.referenceHashes?.[reference.id]);
@@ -877,10 +965,10 @@ export async function prepareJobInspection(display: JobDisplayPublication, signa
877
965
  const failed = preloaded.find(result => result.status === 'rejected');
878
966
  if (failed?.status === 'rejected')
879
967
  throw failed.reason;
880
- if (metadata.manifest.model) {
968
+ if (metadata.manifest?.model) {
881
969
  const runtime = await import('@rig-c/play');
882
970
  const modelUrl = routes.asset(metadata.manifest.model);
883
- const modelHash = metadata.reviewedSource.rig!.sha256;
971
+ const modelHash = metadata.reviewedSource!.rig!.sha256;
884
972
  const setsUrl = metadata.manifest.sets ? routes.asset(metadata.manifest.sets) : null;
885
973
  const checkedFetch = new Proxy(fetch, { apply: async (_target, _receiver, args: Parameters<typeof fetch>) => {
886
974
  const url = String(args[0]);
@@ -909,12 +997,12 @@ export async function prepareJobInspection(display: JobDisplayPublication, signa
909
997
  };
910
998
  resetToSetup();
911
999
  }
912
- if (!player && !references.length && !partImages.size && !imageSetImages.length)
1000
+ if (!isRecordSource(source) && !player && !references.length && !partImages.size && !imageSetImages.length)
913
1001
  throw new Error('JOB_VISUAL_UNAVAILABLE');
914
1002
  if (signal.aborted)
915
1003
  throw new Error('JOB_PRELOAD_CANCELLED');
916
1004
  // Preloads can finish out of order. Restore the producer's declared display order.
917
- const order = [metadata.sourcePainting?.id, ...metadata.manifest.references.map(reference => reference.id)];
1005
+ const order = [metadata.sourcePainting?.id, ...(metadata.manifest?.references.map(reference => reference.id) ?? [])];
918
1006
  references.sort((a, b) => order.indexOf(a.id) - order.indexOf(b.id));
919
1007
  return {
920
1008
  display, metadata, interview, parts, partImages, interviewImages, imageSetImages, references, assets, rigRoot,
@@ -986,24 +1074,142 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
986
1074
  host.replaceChildren(header, notice, workspace);
987
1075
  let current: JobPreparedInspection | null = null;
988
1076
  let currentElement: HTMLElement | null = null;
989
- let animation = '';
990
- let time = 0;
1077
+ type SavedCameraState = Pick<
1078
+ ReturnType<typeof createViewportState>,
1079
+ 'cameraSync' | 'activeCamera' | 'zoom' | 'cameraCenter' | 'referenceZoom' | 'referenceCenter'
1080
+ >;
1081
+ type SavedJobWindowState = {
1082
+ publicationId: string;
1083
+ label: string;
1084
+ sourceHash: string;
1085
+ previousLabel: string | null;
1086
+ compatibilityNotice?: boolean;
1087
+ animation?: string;
1088
+ time?: number;
1089
+ loop?: boolean;
1090
+ selectedPart?: string;
1091
+ partMode?: 'context' | 'solo';
1092
+ selectedReference?: string;
1093
+ panel?: string;
1094
+ partIdentity?: unknown;
1095
+ camera?: unknown;
1096
+ };
1097
+ const parseSavedPoint = (raw: unknown): { x: number; y: number } | null | undefined => {
1098
+ if (raw === null) return null;
1099
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;
1100
+ const point = raw as Record<string, unknown>;
1101
+ return typeof point.x === 'number' && Number.isFinite(point.x) &&
1102
+ typeof point.y === 'number' && Number.isFinite(point.y)
1103
+ ? { x: point.x, y: point.y }
1104
+ : undefined;
1105
+ };
1106
+ const parseSavedCamera = (raw: unknown): SavedCameraState | null => {
1107
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
1108
+ const value = raw as Record<string, unknown>;
1109
+ const cameraCenter = parseSavedPoint(value.cameraCenter);
1110
+ const referenceCenter = parseSavedPoint(value.referenceCenter);
1111
+ if (typeof value.cameraSync !== 'boolean' ||
1112
+ (value.activeCamera !== 'rig' && value.activeCamera !== 'reference') ||
1113
+ typeof value.zoom !== 'number' || !Number.isFinite(value.zoom) || value.zoom < 0.25 || value.zoom > 8 ||
1114
+ typeof value.referenceZoom !== 'number' || !Number.isFinite(value.referenceZoom) || value.referenceZoom < 0.25 || value.referenceZoom > 8 ||
1115
+ cameraCenter === undefined || referenceCenter === undefined) {
1116
+ return null;
1117
+ }
1118
+ return {
1119
+ cameraSync: value.cameraSync,
1120
+ activeCamera: value.activeCamera,
1121
+ zoom: value.zoom,
1122
+ cameraCenter,
1123
+ referenceZoom: value.referenceZoom,
1124
+ referenceCenter,
1125
+ };
1126
+ };
1127
+ const parseSavedPartIdentity = (raw: unknown): ControlPart | null => {
1128
+ try {
1129
+ return parseControlPart(raw);
1130
+ }
1131
+ catch {
1132
+ return null;
1133
+ }
1134
+ };
1135
+ const parseSavedDraftRecord = (raw: unknown): JobRetainedDraft | null => {
1136
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
1137
+ const draft = raw as Record<string, unknown>;
1138
+ if (!Array.isArray(draft.forms) || !draft.forms.length ||
1139
+ typeof draft.publicationId !== 'string' || !draft.publicationId ||
1140
+ typeof draft.sourceHash !== 'string' || !draft.sourceHash ||
1141
+ typeof draft.label !== 'string' || !draft.label ||
1142
+ !draft.source || typeof draft.source !== 'object' || Array.isArray(draft.source) ||
1143
+ (draft.source as { sourceHash?: unknown }).sourceHash !== draft.sourceHash) {
1144
+ return null;
1145
+ }
1146
+ const forms = draft.forms.filter((item: unknown): item is { askId: string; value: unknown } =>
1147
+ !!item && typeof item === 'object' && !Array.isArray(item) &&
1148
+ typeof (item as { askId?: unknown }).askId === 'string' && !!(item as { askId: string }).askId);
1149
+ if (!forms.length) return null;
1150
+ return {
1151
+ publicationId: draft.publicationId,
1152
+ sourceHash: draft.sourceHash,
1153
+ source: draft.source as SourceV3,
1154
+ label: draft.label,
1155
+ value: forms.map(item => ({ askId: item.askId, value: item.value })),
1156
+ };
1157
+ };
1158
+ const localWindowKey = 'rig-review-job-window/1:' + access.jobId;
1159
+ let savedWindow: SavedJobWindowState | null = null;
1160
+ try {
1161
+ const parsed = JSON.parse(localStorage.getItem(localWindowKey) ?? 'null');
1162
+ if (parsed && typeof parsed.publicationId === 'string' && typeof parsed.label === 'string' &&
1163
+ typeof parsed.sourceHash === 'string') {
1164
+ savedWindow = parsed as SavedJobWindowState;
1165
+ }
1166
+ }
1167
+ catch { /* Invalid saved window state falls back to defaults. */ }
1168
+ const initialRetainedDrafts: JobRetainedDraft[] = [];
1169
+ try {
1170
+ const draftPrefix = 'rig-review-job-draft/1:' + access.jobId + ':';
1171
+ for (let index = 0; index < localStorage.length; index++) {
1172
+ const key = localStorage.key(index);
1173
+ if (!key?.startsWith(draftPrefix)) continue;
1174
+ try {
1175
+ const parsedDraft = parseSavedDraftRecord(JSON.parse(localStorage.getItem(key) ?? 'null'));
1176
+ if (parsedDraft) initialRetainedDrafts.push(parsedDraft);
1177
+ }
1178
+ catch { /* Ignore malformed draft entries without dropping sibling drafts. */ }
1179
+ }
1180
+ }
1181
+ catch { /* In-memory standing state remains active when storage is unavailable. */ }
1182
+ const previousDisplayed = savedWindow ? {
1183
+ publicationId: savedWindow.publicationId,
1184
+ label: savedWindow.label,
1185
+ previousLabel: typeof savedWindow.previousLabel === 'string' ? savedWindow.previousLabel : null,
1186
+ } : null;
1187
+ let animation = typeof savedWindow?.animation === 'string' ? savedWindow.animation : '';
1188
+ let time = typeof savedWindow?.time === 'number' && Number.isFinite(savedWindow.time) && savedWindow.time >= 0
1189
+ ? savedWindow.time : 0;
991
1190
  let playing = false;
992
- let loop = true;
1191
+ let loop = typeof savedWindow?.loop === 'boolean' ? savedWindow.loop : true;
993
1192
  let playbackCarry = 0;
994
1193
  let rafHandle = 0;
995
1194
  let lastFrameTime = 0;
996
- let selectedPart = '';
997
- let partMode: 'context' | 'solo' = 'context';
998
- let selectedReference = '';
999
- let panel = '3';
1000
- let compatibilityNotice = false;
1195
+ let inPlaybackStep = false;
1196
+ let lastRunningSaveMs: number | null = null;
1197
+ let lastSavedWindowJson: string | null = null;
1198
+ let selectedPart = typeof savedWindow?.selectedPart === 'string' ? savedWindow.selectedPart : '';
1199
+ let partMode: 'context' | 'solo' = savedWindow?.partMode === 'solo' ? 'solo' : 'context';
1200
+ let selectedReference = typeof savedWindow?.selectedReference === 'string' ? savedWindow.selectedReference : '';
1201
+ let panel = typeof savedWindow?.panel === 'string' && ['1', '2', '3', '4'].includes(savedWindow.panel)
1202
+ ? savedWindow.panel : '3';
1203
+ let restoredPartIdentity: ControlPart | null = parseSavedPartIdentity(savedWindow?.partIdentity);
1204
+ let restoredCamera: SavedCameraState | null = parseSavedCamera(savedWindow?.camera);
1205
+ let compatibilityNotice = Boolean(savedWindow?.compatibilityNotice);
1001
1206
  type JobForm = {
1002
1207
  form: HTMLFormElement;
1003
1208
  fieldset: HTMLFieldSetElement;
1004
- read: () => JobUISubmission['value'];
1209
+ read: () => UISubmissionV3['value'];
1005
1210
  submissionId: string;
1006
1211
  dirty: boolean;
1212
+ submitting: boolean;
1007
1213
  rigSubmission: ReturnType<typeof createJobRigSubmission>;
1008
1214
  };
1009
1215
  type PreparedWindow = JobPreparedInspection & {
@@ -1014,6 +1220,59 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1014
1220
  const drawn = new WeakMap<JobPreparedInspection, JobRigDraw>();
1015
1221
  let drawGeneration = 0;
1016
1222
  const viewportState = createViewportState();
1223
+ if (restoredCamera) {
1224
+ Object.assign(viewportState, restoredCamera, { cameraRestoring: false });
1225
+ }
1226
+ function saveWindowState(nowMs?: number): void {
1227
+ if (!current)
1228
+ return;
1229
+ if (inPlaybackStep && nowMs === undefined)
1230
+ return;
1231
+ const state = window.state();
1232
+ if (state.displayed?.publication.publicationId !== current.display.publication.publicationId)
1233
+ return;
1234
+ if (nowMs !== undefined) {
1235
+ if (lastRunningSaveMs === null) {
1236
+ lastRunningSaveMs = nowMs;
1237
+ return;
1238
+ }
1239
+ if (nowMs - lastRunningSaveMs < 1000)
1240
+ return;
1241
+ lastRunningSaveMs = nowMs;
1242
+ }
1243
+ try {
1244
+ const serialized = JSON.stringify({
1245
+ publicationId: current.display.publication.publicationId,
1246
+ label: current.display.publication.label,
1247
+ sourceHash: current.display.publication.source.sourceHash,
1248
+ previousLabel: state.previousLabel,
1249
+ compatibilityNotice,
1250
+ animation,
1251
+ time,
1252
+ loop,
1253
+ selectedPart,
1254
+ partMode,
1255
+ selectedReference,
1256
+ panel,
1257
+ partIdentity: current.inspection?.value() ?? null,
1258
+ camera: {
1259
+ cameraSync: viewportState.cameraSync,
1260
+ activeCamera: viewportState.activeCamera,
1261
+ zoom: viewportState.zoom,
1262
+ cameraCenter: viewportState.cameraCenter
1263
+ ? { x: viewportState.cameraCenter.x, y: viewportState.cameraCenter.y } : null,
1264
+ referenceZoom: viewportState.referenceZoom,
1265
+ referenceCenter: viewportState.referenceCenter
1266
+ ? { x: viewportState.referenceCenter.x, y: viewportState.referenceCenter.y } : null,
1267
+ },
1268
+ });
1269
+ if (serialized === lastSavedWindowJson)
1270
+ return;
1271
+ localStorage.setItem(localWindowKey, serialized);
1272
+ lastSavedWindowJson = serialized;
1273
+ }
1274
+ catch { /* Standing state stays in memory when storage is unavailable. */ }
1275
+ }
1017
1276
  const el = <Element extends HTMLElement = HTMLElement>(id: string): Element => {
1018
1277
  const element = workspace.querySelector<HTMLElement>('#' + id);
1019
1278
  if (!element)
@@ -1034,6 +1293,7 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1034
1293
  canonicalControls(controller);
1035
1294
  const fit = el('fit');
1036
1295
  fit.textContent = t(fit.textContent ?? 'Fit');
1296
+ saveWindowState();
1037
1297
  };
1038
1298
  const viewport = createViewportController(provider, viewportState);
1039
1299
  const renderViewport = provider.render;
@@ -1130,8 +1390,10 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1130
1390
  playing = false;
1131
1391
  playbackCarry = 0;
1132
1392
  lastFrameTime = 0;
1393
+ lastRunningSaveMs = null;
1133
1394
  targetPlayer?.pause();
1134
1395
  syncTransportControls();
1396
+ saveWindowState();
1135
1397
  }
1136
1398
  function presentCurrentFrame(owner: JobPreparedInspection): void {
1137
1399
  if (!owner.player) return;
@@ -1192,13 +1454,25 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1192
1454
  }
1193
1455
  const clock = workspace.querySelector<HTMLInputElement>('#job-time');
1194
1456
  if (clock) clock.value = playbackTimeLabel(clip.duration, activeEntry.trackTime);
1195
- syncTransportControls();
1196
- presentCurrentFrame(expectedOwner);
1457
+ inPlaybackStep = true;
1458
+ try {
1459
+ syncTransportControls();
1460
+ presentCurrentFrame(expectedOwner);
1461
+ }
1462
+ finally {
1463
+ inPlaybackStep = false;
1464
+ }
1465
+ if (playing) {
1466
+ saveWindowState(now);
1467
+ } else {
1468
+ lastRunningSaveMs = null;
1469
+ saveWindowState();
1470
+ }
1197
1471
  if (playing && current === expectedOwner && current.player === expectedPlayer && hubVisible) {
1198
1472
  armPlayback(expectedOwner, expectedPlayer);
1199
1473
  }
1200
1474
  }
1201
- function copyRigVerdict(ask: JobPendingAsk, owner: JobPreparedInspection) {
1475
+ function copyRigVerdict(ask: PendingAskV3, owner: JobPreparedInspection) {
1202
1476
  if (owner !== current || ask.publicationId !== owner.display.publication.publicationId) {
1203
1477
  throw new Error('JOB_STILL_BINDING_MISMATCH');
1204
1478
  }
@@ -1234,7 +1508,7 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1234
1508
  });
1235
1509
  let unbindNavigation: (() => void) | null = null;
1236
1510
  let resize: ResizeObserver | null = null;
1237
- function localDraftKey(display: JobDisplayPublication): string {
1511
+ function localDraftKey(display: DisplayPublicationV3): string {
1238
1512
  return 'rig-review-job-draft/1:' + access.jobId + ':' + display.publication.publicationId + ':' + display.publication.source.sourceHash;
1239
1513
  }
1240
1514
  function saveDraft(): void {
@@ -1275,7 +1549,7 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1275
1549
  parent.append(inputLabel(key, input));
1276
1550
  return input;
1277
1551
  }
1278
- function formFor(ask: JobPendingAsk, prepared: JobPreparedInspection): JobForm {
1552
+ function formFor(ask: PendingAskV3, prepared: JobPreparedInspection): JobForm {
1279
1553
  if (ask.publicationId !== prepared.display.publication.publicationId)
1280
1554
  throw new Error('JOB_DISPLAY_MISMATCH');
1281
1555
  assertJobAskSource(ask, prepared.display);
@@ -1288,13 +1562,33 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1288
1562
  source.textContent = prepared.display.publication.label + ' · ' + ask.source.sourceHash;
1289
1563
  fields.append(source);
1290
1564
  const note = textArea(fields, 'interview.note');
1291
- let read: () => JobUISubmission['value'];
1565
+ let read: () => UISubmissionV3['value'];
1292
1566
  let submitKey = 'Submit review';
1293
1567
  const subject = ask.subject;
1294
1568
  if (subject.kind === 'interview-picks') {
1295
1569
  const question = prepared.interview?.questions.find(item => item.set.id === subject.setId && item.set.question === subject.questionId);
1296
1570
  if (!question || !question.editable) throw new Error('JOB_ASK_INVALID');
1297
1571
  if (question.ref.sha256 !== ask.source.optionSet?.sha256) throw new Error('JOB_ACT_SOURCE_STALE');
1572
+ const interviewState = prepared.interview?.interview ?? prepared.display.publication.interview ?? null;
1573
+ const inspectionRecord = interviewState?.records.find(
1574
+ item => item.timeKind === 'inspection' &&
1575
+ item.questionId === subject.questionId &&
1576
+ item.setId === subject.setId &&
1577
+ item.record.endsWith('.pending_options'),
1578
+ );
1579
+ const legacyDiagnostic = inspectionRecord
1580
+ ? interviewState?.diagnostics.find(
1581
+ item => item.code === 'INTERVIEW_OPTIONS_SCENE_LEGACY' &&
1582
+ item.record === inspectionRecord.record &&
1583
+ item.at === inspectionRecord.at,
1584
+ )
1585
+ : undefined;
1586
+ if (legacyDiagnostic) {
1587
+ const legacyNotice = node('p', 'INTERVIEW_OPTIONS_SCENE_LEGACY');
1588
+ legacyNotice.dataset.jobInterviewWarning = legacyDiagnostic.code;
1589
+ legacyNotice.dataset.record = legacyDiagnostic.record;
1590
+ fields.prepend(legacyNotice);
1591
+ }
1298
1592
  const heading = node('h3');
1299
1593
  heading.textContent = question.set.question;
1300
1594
  fields.prepend(heading);
@@ -1343,7 +1637,7 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1343
1637
  submitKey = 'interview.save';
1344
1638
  }
1345
1639
  else if (subject.kind === 'checkpoint') {
1346
- const checkpoint = jobCheckpointContext(ask, prepared.metadata.manifest.checkpoints);
1640
+ const checkpoint = jobCheckpointContext(ask, prepared.metadata.manifest?.checkpoints ?? []);
1347
1641
  const heading = node('h3');
1348
1642
  heading.textContent = checkpoint.title;
1349
1643
  fields.prepend(heading);
@@ -1421,6 +1715,22 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1421
1715
  read = () => ({ stage: subject.stage, decision: 'approved', words: note.value });
1422
1716
  submitKey = 'job.signoff';
1423
1717
  }
1718
+ else if (subject.kind === 'reopen') {
1719
+ if (
1720
+ !('record' in ask.source) ||
1721
+ ask.source.subject !== 'plan' ||
1722
+ typeof subject.stage !== 'string' ||
1723
+ !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(subject.stage) ||
1724
+ !ask.source.subjects.some(candidate => candidate.kind === 'reopen' && candidate.stage === subject.stage)
1725
+ ) {
1726
+ throw new Error('JOB_ASK_INVALID');
1727
+ }
1728
+ const stage = node('p');
1729
+ stage.textContent = subject.stage;
1730
+ fields.append(stage);
1731
+ read = () => ({ stage: subject.stage, words: note.value });
1732
+ submitKey = 'job.reopen';
1733
+ }
1424
1734
  else {
1425
1735
  throw new Error('JOB_ACT_KIND_DISABLED');
1426
1736
  }
@@ -1431,7 +1741,7 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1431
1741
  status.setAttribute('role', 'status');
1432
1742
  form.append(status);
1433
1743
  const entry: JobForm = { form, fieldset: fields, read, submissionId: crypto.randomUUID(), dirty: false,
1434
- rigSubmission: createJobRigSubmission() };
1744
+ submitting: false, rigSubmission: createJobRigSubmission() };
1435
1745
  try {
1436
1746
  const saved = JSON.parse(localStorage.getItem(localDraftKey(prepared.display)) ?? 'null');
1437
1747
  if (saved?.publicationId === prepared.display.publication.publicationId &&
@@ -1464,17 +1774,19 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1464
1774
  try {
1465
1775
  const input = { kind: subject.kind, publicationId: ask.publicationId,
1466
1776
  askId: ask.askId, pageId, displayedNonce: receipt.displayedNonce,
1467
- expectedGeneration: state.generation, submissionId: entry.submissionId, value: read() } as JobUISubmission;
1777
+ expectedGeneration: state.generation, submissionId: entry.submissionId, value: read() } as UISubmissionV3;
1468
1778
  const activeAsk = state.pending.find(item => item.askId === ask.askId);
1469
1779
  if (!activeAsk) throw new Error('JOB_ASK_INVALID');
1470
1780
  const pending = subject.kind === 'review-verdict' && subject.stage === 'rig-review'
1471
- ? entry.rigSubmission.prepare(input, () => copyRigVerdict(activeAsk, prepared)) : Promise.resolve(input);
1781
+ ? entry.rigSubmission.prepare(input as JobUISubmission, () => copyRigVerdict(activeAsk, prepared)) : Promise.resolve(input);
1782
+ entry.submitting = true;
1472
1783
  fields.disabled = true;
1473
1784
  const frozen = await pending;
1474
1785
  if (entry.submissionId !== frozen.submissionId) throw new Error('JOB_STILL_BINDING_MISMATCH');
1475
1786
  const result = await window.submit(frozen);
1476
1787
  if (!result.ok)
1477
1788
  throw new Error(result.error.code);
1789
+ entry.submitting = false;
1478
1790
  entry.dirty = false;
1479
1791
  entry.rigSubmission.reset();
1480
1792
  status.dataset.jobText = 'job.saved';
@@ -1482,6 +1794,7 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1482
1794
  saveDraft();
1483
1795
  }
1484
1796
  catch (error) {
1797
+ entry.submitting = false;
1485
1798
  status.dataset.jobText = error instanceof Error && Object.hasOwn(enCatalog, error.message) && Object.hasOwn(koCatalog, error.message)
1486
1799
  ? error.message : 'JOB_ACT_INVALID';
1487
1800
  status.textContent = jobWindowRefusal(error, 'JOB_ACT_INVALID');
@@ -1513,7 +1826,7 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1513
1826
  }
1514
1827
  }
1515
1828
  if (entry)
1516
- entry.fieldset.disabled = ask.status !== 'pending' || state.preparing || state.closed || !state.receipt || !access.capability;
1829
+ entry.fieldset.disabled = entry.submitting || ask.status !== 'pending' || state.closed || !state.receipt || !access.capability;
1517
1830
  }
1518
1831
  }
1519
1832
  function build(prepared: JobPreparedInspection): HTMLElement {
@@ -1534,7 +1847,7 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1534
1847
  sidebar.append(binding);
1535
1848
  const parts = node('select');
1536
1849
  parts.id = 'job-part';
1537
- parts.disabled = !prepared.metadata.manifest.model || prepared.metadata.feedbackCatalog.slots === null;
1850
+ parts.disabled = !prepared.metadata.manifest?.model || prepared.metadata.feedbackCatalog.slots === null;
1538
1851
  const whole = node('option', 'job.wholeRig');
1539
1852
  whole.value = '';
1540
1853
  parts.append(whole);
@@ -1654,6 +1967,7 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1654
1967
  playing = true;
1655
1968
  playbackCarry = 0;
1656
1969
  lastFrameTime = 0;
1970
+ lastRunningSaveMs = null;
1657
1971
  const clockInput = workspace.querySelector<HTMLInputElement>('#job-time');
1658
1972
  if (clockInput) clockInput.value = playbackTimeLabel(clip.duration, current.player.time);
1659
1973
  syncTransportControls();
@@ -1686,9 +2000,11 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1686
2000
  if (!playing) current.player.pause();
1687
2001
  syncTransportControls();
1688
2002
  presentCurrentFrame(current);
2003
+ saveWindowState();
1689
2004
  if (playing && hubVisible) armPlayback(current, current.player);
1690
2005
  } else {
1691
2006
  syncTransportControls();
2007
+ saveWindowState();
1692
2008
  }
1693
2009
  };
1694
2010
  const clock = node('input');
@@ -1775,6 +2091,36 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1775
2091
  if (child instanceof HTMLElement && child !== identity && child !== binding) child.hidden = true;
1776
2092
  }
1777
2093
  }
2094
+ else if (source.subject === 'option-set' || source.subject === 'plan') {
2095
+ const summary = node('section');
2096
+ summary.dataset.jobRecord = source.subject;
2097
+ const recordLine = node('p');
2098
+ recordLine.className = 'job-source';
2099
+ recordLine.textContent = source.record.path + ' · ' + source.record.sha256;
2100
+ summary.append(recordLine);
2101
+ if (source.subject === 'option-set') {
2102
+ const optionLine = node('p');
2103
+ optionLine.className = 'job-source';
2104
+ optionLine.textContent = source.selection.questionId + ' · ' + source.optionSet.id + ' · ' + source.optionSetFile.path + ' · ' + source.optionSet.sha256;
2105
+ summary.append(optionLine);
2106
+ }
2107
+ else {
2108
+ const list = node('ol');
2109
+ list.className = 'job-source';
2110
+ for (const step of source.plan.steps) {
2111
+ const item = node('li');
2112
+ item.textContent = step.id + ' · ' + step.hash;
2113
+ list.append(item);
2114
+ }
2115
+ summary.append(list);
2116
+ }
2117
+ stage.prepend(summary);
2118
+ controls.hidden = pair.hidden = transport.hidden = true;
2119
+ controls.style.display = pair.style.display = transport.style.display = 'none';
2120
+ for (const child of sidebar.children) {
2121
+ if (child instanceof HTMLElement && child !== identity && child !== binding) child.hidden = true;
2122
+ }
2123
+ }
1778
2124
  const formsHost = node('section');
1779
2125
  formsHost.className = 'job-forms';
1780
2126
  formsHost.dataset.jobForms = '';
@@ -1785,10 +2131,43 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1785
2131
  direction.dataset.jobDirection = '';
1786
2132
  if (prepared.metadata.direction)
1787
2133
  direction.textContent = t('job.metadata') + '\n' + JSON.stringify(prepared.metadata.direction, null, 2);
2134
+ const interviewDiagnostics = node('section');
2135
+ interviewDiagnostics.className = 'job-interview-diagnostics';
2136
+ interviewDiagnostics.dataset.jobInterviewDiagnostics = '';
2137
+ const interviewState = prepared.interview?.interview ?? prepared.display.publication.interview ?? null;
2138
+ if (interviewState && (interviewState.diagnostics.length > 0 || interviewState.records.some(record => record.timeKind !== 'inspection'))) {
2139
+ interviewDiagnostics.append(node('h3', 'interview.history'));
2140
+ for (const diagnostic of interviewState.diagnostics) {
2141
+ const item = node('div');
2142
+ item.dataset.jobInterviewDiagnostic = diagnostic.code;
2143
+ item.dataset.severity = diagnostic.severity;
2144
+ item.dataset.record = diagnostic.record;
2145
+ const summary = node('p', diagnostic.code);
2146
+ const detail = node('pre');
2147
+ detail.className = 'job-source';
2148
+ detail.textContent = JSON.stringify(diagnostic, null, 2);
2149
+ item.append(summary, detail);
2150
+ interviewDiagnostics.append(item);
2151
+ }
2152
+ for (const record of interviewState.records) {
2153
+ if (record.timeKind === 'inspection') continue;
2154
+ const item = node('div');
2155
+ item.dataset.jobInterviewRecord = record.record;
2156
+ item.dataset.timeKind = record.timeKind;
2157
+ const detail = node('pre');
2158
+ detail.className = 'job-source';
2159
+ detail.textContent = JSON.stringify(record, null, 2);
2160
+ item.append(detail);
2161
+ interviewDiagnostics.append(item);
2162
+ }
2163
+ }
2164
+ else {
2165
+ interviewDiagnostics.hidden = true;
2166
+ }
1788
2167
  const history = node('div');
1789
2168
  history.className = 'job-history';
1790
2169
  history.dataset.jobHistory = '';
1791
- formsHost.append(direction, history);
2170
+ formsHost.append(direction, interviewDiagnostics, history);
1792
2171
  root.append(sidebar, stage, formsHost);
1793
2172
  return root;
1794
2173
  }
@@ -1813,9 +2192,12 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1813
2192
  direction.hidden = panel !== '4';
1814
2193
  for (const [askId, entry] of forms) {
1815
2194
  const ask = window.state().pending.find(item => item.askId === askId);
1816
- entry.form.hidden = current?.display.publication.source.subject !== 'image-set' &&
2195
+ const currentSubject = current?.display.publication.source.subject;
2196
+ entry.form.hidden = currentSubject !== 'image-set' &&
2197
+ currentSubject !== 'option-set' && currentSubject !== 'plan' &&
1817
2198
  panel === '2' && ask?.subject.kind !== 'interview-picks';
1818
2199
  }
2200
+ saveWindowState();
1819
2201
  }
1820
2202
  function pose(seekReference = true): void {
1821
2203
  if (!current)
@@ -1879,7 +2261,9 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1879
2261
  function announceHubFrame(): void {
1880
2262
  if (hubIncarnation) globalThis.parent.postMessage({...hubBinding(), schema: JOB_HUB_READY}, location.origin);
1881
2263
  }
1882
- const window = createJobWindow({ jobId: access.jobId, pageId, transport, adapter: {
2264
+ const window = createJobWindow({ jobId: access.jobId, pageId, transport,
2265
+ previousDisplayed, initialRetainedDrafts,
2266
+ adapter: {
1883
2267
  async prepare(display, signal): Promise<PreparedWindow> {
1884
2268
  const inspection = await prepareJobInspection(display, signal);
1885
2269
  try {
@@ -1906,9 +2290,13 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1906
2290
  stopPlayback(previous?.player);
1907
2291
  const previousElement = currentElement;
1908
2292
  const previousForms = new Map(forms);
1909
- const navigation = { animation, time, selectedPart, partMode, selectedReference, panel,
1910
- partIdentity: current?.inspection?.value(), camera: structuredClone(viewportState) };
1911
- compatibilityNotice = false;
2293
+ const restoringCamera = Boolean(previous || restoredCamera);
2294
+ const navigation = { animation, time, loop, selectedPart, partMode, selectedReference, panel,
2295
+ partIdentity: previous ? (previous.inspection?.value() ?? null) : restoredPartIdentity,
2296
+ camera: structuredClone(viewportState) };
2297
+ compatibilityNotice = Boolean(!previous &&
2298
+ savedWindow?.publicationId === display.publication.publicationId &&
2299
+ savedWindow.compatibilityNotice);
1912
2300
  if (animation && !prepared.assets?.animations.some(item => item.name === animation && time <= item.duration)) {
1913
2301
  animation = '';
1914
2302
  time = 0;
@@ -1930,6 +2318,7 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1930
2318
  currentElement = previousElement;
1931
2319
  animation = navigation.animation;
1932
2320
  time = navigation.time;
2321
+ loop = navigation.loop;
1933
2322
  selectedPart = navigation.selectedPart;
1934
2323
  partMode = navigation.partMode;
1935
2324
  selectedReference = navigation.selectedReference;
@@ -1955,13 +2344,17 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1955
2344
  el<HTMLInputElement>('job-solo').checked = partMode === 'solo';
1956
2345
  el<HTMLSelectElement>('job-reference').value = selectedReference;
1957
2346
  el<HTMLSelectElement>('job-animation').value = animation;
2347
+ el<HTMLInputElement>('job-loop').checked = loop;
1958
2348
  el<HTMLSelectElement>('job-panel').value = panel;
1959
2349
  el('rig-empty').hidden = !!prepared.player;
1960
- Object.assign(viewportState, navigation.camera, { cameraRestoring: true });
2350
+ Object.assign(viewportState, navigation.camera, { cameraRestoring: restoringCamera });
1961
2351
  showReference();
1962
2352
  pose(false);
1963
2353
  if (selectedPart) {
1964
2354
  try {
2355
+ if (!navigation.partIdentity || navigation.partIdentity.slot !== selectedPart) {
2356
+ throw new Error('PART_IDENTITY_UNAVAILABLE');
2357
+ }
1965
2358
  prepared.inspection?.assertIdentity(navigation.partIdentity);
1966
2359
  }
1967
2360
  catch {
@@ -1980,12 +2373,15 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1980
2373
  return {
1981
2374
  rollback,
1982
2375
  finalize() {
2376
+ restoredPartIdentity = null;
2377
+ restoredCamera = null;
2378
+ savedWindow = null;
1983
2379
  unbindNavigation?.();
1984
2380
  resize?.disconnect();
1985
2381
  unbindNavigation = nextUnbind;
1986
2382
  resize = nextResize;
1987
2383
  previous?.dispose();
1988
- title.textContent = display.publication.source.package.id;
2384
+ title.textContent = display.publication.source.package?.id ?? display.publication.label;
1989
2385
  },
1990
2386
  };
1991
2387
  }
@@ -2018,11 +2414,12 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
2018
2414
  notice.textContent = t('job.closed');
2019
2415
  else if (state.preparing)
2020
2416
  notice.textContent = t('job.preparing');
2021
- else if (state.displayed)
2417
+ else if (state.displayed) {
2022
2418
  notice.textContent = state.previousLabel
2023
2419
  ? t('job.updated', [state.previousLabel, state.displayed.publication.label]) : state.displayed.publication.label;
2024
- if (compatibilityNotice)
2025
- notice.textContent += ' · ' + t('job.incompatible');
2420
+ if (compatibilityNotice)
2421
+ notice.textContent += ' · ' + t('job.incompatible');
2422
+ }
2026
2423
  if (state.closed) {
2027
2424
  const wasPlaying = playing;
2028
2425
  stopPlayback();
@@ -2040,18 +2437,19 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
2040
2437
  const key = localStorage.key(index);
2041
2438
  if (!key?.startsWith(prefix))
2042
2439
  continue;
2043
- const saved = JSON.parse(localStorage.getItem(key) ?? 'null');
2044
- if (!saved?.forms?.length || saved.publicationId === state.displayed?.publication.publicationId)
2045
- continue;
2046
- if (typeof saved.publicationId !== 'string' || typeof saved.sourceHash !== 'string' || typeof saved.label !== 'string')
2047
- continue;
2048
- retained.set(saved.publicationId, { publicationId: saved.publicationId, sourceHash: saved.sourceHash,
2049
- source: saved.source, label: saved.label, value: saved.forms });
2440
+ try {
2441
+ const parsedDraft = parseSavedDraftRecord(JSON.parse(localStorage.getItem(key) ?? 'null'));
2442
+ if (!parsedDraft || parsedDraft.publicationId === state.displayed?.publication.publicationId)
2443
+ continue;
2444
+ retained.set(parsedDraft.publicationId, parsedDraft);
2445
+ }
2446
+ catch { /* Ignore malformed draft entries without dropping sibling drafts. */ }
2050
2447
  }
2051
2448
  }
2052
2449
  catch { /* In-memory retained evidence remains available. */ }
2053
2450
  history.textContent = [...retained.values()].map(draft => t('job.retained', [draft.label]) + '\n' + draft.sourceHash + '\n' + JSON.stringify(draft.value, null, 2)).join('\n');
2054
2451
  }
2452
+ saveWindowState();
2055
2453
  pauseHiddenHubFrame(); announceHubFrame();
2056
2454
  if (state.receipt && !state.preparing) events?.displayed();
2057
2455
  },
@@ -2101,6 +2499,7 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
2101
2499
  resolution?.removeEventListener('change', resolutionChanged);
2102
2500
  globalThis.removeEventListener('message', hubVisibility);
2103
2501
  saveDraft();
2502
+ saveWindowState();
2104
2503
  referenceSelection.cancel();
2105
2504
  abort.abort();
2106
2505
  window.stop();