@rig-c/review 3.7.0 → 4.0.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.
Files changed (109) hide show
  1. package/README.md +1 -1
  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 +445 -99
  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 +157 -58
  30. package/src/job-host.ts +23 -4
  31. package/src/job-session.ts +109 -24
  32. package/src/job-source.ts +209 -57
  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 +337 -0
  68. package/web/job-session.ts +611 -1437
  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
@@ -1,14 +1,18 @@
1
1
  /** Live job window transactions. Every form remains bound to its displayed publication. */
2
- import { parseControlPart, type ControlPart } from '../src/control.ts';
3
2
  import type {
4
3
  ActV3,
5
4
  DisplayPublicationV3,
6
5
  EventV3,
7
6
  JobDisplayReceipt,
7
+ JobCheckpointEvidence,
8
+ JobCheckpointTable,
8
9
  JobInterviewDiagnostics,
9
10
  JobResult,
10
- JobUISubmission,
11
11
  PendingAskV3,
12
+ JobPanelComposition,
13
+ PanelComponent,
14
+ PanelSlot,
15
+ PartsVerdictValue,
12
16
  PublicationV3,
13
17
  RecordSource,
14
18
  SourceV3,
@@ -16,13 +20,15 @@ import type {
16
20
  } from '../src/job-contract.ts';
17
21
  import {enCatalog} from './catalog-en.ts';
18
22
  import {koCatalog} from './catalog-ko.ts';
19
- import {t} from './i18n.ts';
20
- import {JOB_HUB_READY, jobHubMessageMatches, type JobHubBinding} from './job-hub.ts';
21
- import {recordJobRigDraw, freezeJobRigCapture, copyJobRigViewport, createJobRigSubmission, jobRigPixelPlacement,
22
- type JobRigDraw, type JobRigDrawState} from './job-rig-capture.ts';
23
- import {advancePlayback} from './playback-clock.ts';
24
- import {presentJobRigViewport, type JobRigPresentation} from './viewport-capture.ts';
25
- import {CanvasRenderer} from '@rig-c/play';
23
+ import {t,onLanguageChange} from './i18n.ts';
24
+ import type {InstanceAccess} from './instance-access.ts';
25
+ import {JOB_PLAN_TEXT_FIELDS, parseJobPlanTextProjection, type JobPlanTextProjection} from '../src/job-contract.ts';
26
+ import {createJobRigScreen, type JobRigScreenPrepared} from './job-rig-screen.ts';
27
+ import type {JobRigPresentation} from './viewport-capture.ts';
28
+ import {labelledControl} from './view-controls.ts';
29
+ import {createInterviewForm,interviewPicksRecord,interviewRecords,interviewErrors,type InterviewDisplayQuestion} from './interview-panel.ts';
30
+ import {JOB_COMMENTS_ACT_SCHEMA, JOB_PANEL_COMPOSITION_SCHEMA, JOB_PARTS_VERDICT_ACT_SCHEMA, parsePanelComposition} from '../src/job-contract.ts';
31
+ import type {PartsIssue} from '../src/parts-comment.ts';
26
32
 
27
33
  /** Imported runtimes may throw arbitrary prose. Only registered refusal copy reaches the window. */
28
34
  export function jobWindowRefusal(error: unknown, fallback = 'JOB_WINDOW_FAILED'): string {
@@ -33,6 +39,17 @@ export function jobWindowRefusal(error: unknown, fallback = 'JOB_WINDOW_FAILED')
33
39
  }
34
40
  return t(fallback);
35
41
  }
42
+ /** Submission copy and its diagnostic title share the existing catalog refusal registry. */
43
+ export function jobSubmissionRefusal(error: unknown): {code: string; text: string; title: string} {
44
+ const message = error instanceof Error ? error.message : error;
45
+ const code = typeof message === 'string' && /^JOB_[A-Z_]+$/.test(message) ? message : 'JOB_ACT_INVALID';
46
+ const key = 'job.submit.' + code;
47
+ const reason = Object.hasOwn(enCatalog, key) && Object.hasOwn(koCatalog, key) ? key : 'job.submit.refused';
48
+ const origin = error instanceof Error && typeof error.cause === 'string' ? error.cause : 'client: submission';
49
+ const title = code + ' · ' + origin;
50
+ if (code === 'JOB_BODY_LIMIT' || reason === 'job.submit.refused') console.warn(title);
51
+ return {code, title, text: t('Review was not submitted: {0}', [t(reason)])};
52
+ }
36
53
  export interface JobWindowTransport {
37
54
  readPublication(publicationId: string, signal?: AbortSignal): Promise<JobResult<DisplayPublicationV3>>;
38
55
  acknowledge(input: {
@@ -44,7 +61,7 @@ export interface JobWindowTransport {
44
61
  }
45
62
  export interface JobPreparedCommit {
46
63
  /** Restore the previous view, including its original forms and route bindings. */
47
- rollback(): void;
64
+ rollback(): void | Promise<void>;
48
65
  /** Dispose the old view only after the new displayed nonce is acknowledged. */
49
66
  finalize(): void;
50
67
  }
@@ -65,6 +82,7 @@ export interface JobRetainedDraft {
65
82
  readonly label: string;
66
83
  readonly value: unknown;
67
84
  }
85
+ export type JobWindowAsk = PendingAskV3 & {readonly act?: ActV3};
68
86
  export interface JobWindowState {
69
87
  readonly generation: number;
70
88
  readonly displayed: DisplayPublicationV3 | null;
@@ -72,13 +90,14 @@ export interface JobWindowState {
72
90
  readonly preparing: boolean;
73
91
  readonly closed: boolean;
74
92
  readonly error: string | null;
93
+ readonly errorOrigin?: string;
75
94
  readonly previousLabel: string | null;
76
- readonly pending: readonly PendingAskV3[];
95
+ readonly pending: readonly JobWindowAsk[];
77
96
  readonly retainedDrafts: readonly JobRetainedDraft[];
78
97
  }
79
98
  function unwrap<Value>(result: JobResult<Value>): Value {
80
99
  if (!result.ok)
81
- throw new Error(result.error.code);
100
+ throw new Error(result.error.code, {cause: (result.error as {cause?: unknown}).cause});
82
101
  return result.value;
83
102
  }
84
103
  function isRecordSource(source: SourceV3): source is RecordSource {
@@ -121,6 +140,23 @@ export function prepareJobForms<Form>(
121
140
  return prepared;
122
141
  }
123
142
 
143
+ /** Association checks for normal daemon-authoritative plan text metadata. */
144
+ export function jobPlanTextForSource(value: unknown, source: SourceV3): JobPlanTextProjection | undefined {
145
+ if (value === undefined) return undefined;
146
+ const projection = parseJobPlanTextProjection(value);
147
+ const mismatch = () => {throw new Error('PLAN_TEXT_SOURCE_MISMATCH');};
148
+ if (!source.plan) return mismatch();
149
+ if (projection.record && (projection.record.sha256 !== source.projectHash ||
150
+ isRecordSource(source) && (source.record.path !== projection.record.path ||
151
+ source.record.sha256 !== projection.record.sha256 ||
152
+ !source.files.some(file => file.path === projection.record!.path && file.sha256 === projection.record!.sha256))))
153
+ return mismatch();
154
+ if (projection.status === 'projected' && (projection.steps.length !== source.plan.steps.length ||
155
+ projection.steps.some((row, index) => row.id !== source.plan!.steps[index]?.id || row.hash !== source.plan!.steps[index]?.hash)))
156
+ return mismatch();
157
+ return projection;
158
+ }
159
+
124
160
  /** C2 publishes the plan mapping in the ask. Legacy checkpoint metadata is optional guidance. */
125
161
  export function jobCheckpointContext(
126
162
  ask: PendingAskV3,
@@ -153,7 +189,7 @@ export function createJobWindow<Prepared>(options: {
153
189
  initialRetainedDrafts?: readonly JobRetainedDraft[];
154
190
  }) {
155
191
  const { transport, adapter, pageId } = options;
156
- const pending = new Map<string, PendingAskV3>();
192
+ const pending = new Map<string, JobWindowAsk>();
157
193
  const rigAttempts = new WeakSet<UISubmissionV3>();
158
194
  const retainedDrafts: JobRetainedDraft[] = [];
159
195
  let initialDrafts: readonly JobRetainedDraft[] | null = options.initialRetainedDrafts
@@ -164,6 +200,7 @@ export function createJobWindow<Prepared>(options: {
164
200
  let preparing = false;
165
201
  let closed = false;
166
202
  let error: string | null;
203
+ let errorOrigin: string | undefined;
167
204
  error = null;
168
205
  let previousLabel: string | null = null;
169
206
  let intent = 0;
@@ -172,7 +209,7 @@ export function createJobWindow<Prepared>(options: {
172
209
  let queue = Promise.resolve();
173
210
  function state(): JobWindowState {
174
211
  return {
175
- generation, displayed, receipt, preparing, closed, error, previousLabel,
212
+ generation, displayed, receipt, preparing, closed, error, previousLabel, ...(errorOrigin ? {errorOrigin} : {}),
176
213
  pending: [...pending.values()], retainedDrafts: [...retainedDrafts],
177
214
  };
178
215
  }
@@ -186,6 +223,7 @@ export function createJobWindow<Prepared>(options: {
186
223
  controller = abort;
187
224
  preparing = true;
188
225
  error = null;
226
+ errorOrigin = undefined;
189
227
  changed();
190
228
  queue = queue.then(async () => {
191
229
  if (revision !== intent || stopped)
@@ -193,7 +231,8 @@ export function createJobWindow<Prepared>(options: {
193
231
  let prepared: Prepared | undefined;
194
232
  let committed: JobPreparedCommit | undefined;
195
233
  try {
196
- if (publication.visual.status !== 'available' && !isRecordSource(publication.source))
234
+ if (publication.visual.status !== 'available' && !isRecordSource(publication.source) &&
235
+ (publication.source.model||publication.source.parts))
197
236
  throw new Error(publication.visual.code);
198
237
  const candidate = unwrap(await transport.readPublication(publication.publicationId, abort.signal));
199
238
  if (candidate.publication.publicationId !== publication.publicationId ||
@@ -272,11 +311,13 @@ export function createJobWindow<Prepared>(options: {
272
311
  }
273
312
  }
274
313
  catch (failure) {
275
- if (revision === intent && !stopped)
314
+ if (revision === intent && !stopped) {
276
315
  error = failure instanceof Error ? failure.message : 'JOB_DISPLAY_MISMATCH';
316
+ errorOrigin = failure instanceof Error && typeof failure.cause === 'string' ? failure.cause : undefined;
317
+ }
277
318
  }
278
319
  finally {
279
- committed?.rollback();
320
+ await committed?.rollback();
280
321
  if (prepared !== undefined)
281
322
  adapter.discard(prepared);
282
323
  if (revision === intent) {
@@ -301,12 +342,13 @@ export function createJobWindow<Prepared>(options: {
301
342
  void replace(value.publication);
302
343
  }
303
344
  else if (value.type === 'pending') {
304
- pending.set(value.ask.askId, value.ask);
345
+ const previous = pending.get(value.ask.askId);
346
+ pending.set(value.ask.askId, previous?.act ? {...value.ask, status: 'answered', act: previous.act} : value.ask);
305
347
  }
306
348
  else if (value.type === 'act') {
307
349
  const ask = pending.get(value.act.askId);
308
350
  if (ask)
309
- pending.set(ask.askId, { ...ask, status: 'answered' });
351
+ pending.set(ask.askId, { ...ask, status: 'answered', act: value.act });
310
352
  }
311
353
  else if (value.type === 'closed') {
312
354
  closed = true;
@@ -327,7 +369,12 @@ export function createJobWindow<Prepared>(options: {
327
369
  }
328
370
  // The backend authenticates the actual Request and validates the semantic value.
329
371
  if (input.capture !== undefined) rigAttempts.add(input);
330
- return transport.submit(input);
372
+ const result = await transport.submit(input);
373
+ if (result.ok && ask) {
374
+ pending.set(ask.askId, {...ask, status: 'answered', act: result.value});
375
+ changed();
376
+ }
377
+ return result;
331
378
  }
332
379
  return {
333
380
  event, replace, submit, state, refresh: changed,
@@ -415,6 +462,7 @@ export function jobPublicationRoutes(display: DisplayPublicationV3, origin: stri
415
462
  }
416
463
  return {
417
464
  entry: entry.href,
465
+ jobId: match[1]!,
418
466
  api(path: string) {
419
467
  if (!/^[A-Za-z0-9][A-Za-z0-9/._-]*$/.test(path) || path.includes('..'))
420
468
  throw new Error('JOB_DISPLAY_MISMATCH');
@@ -451,6 +499,8 @@ export function createJobWindowTransport(access: JobWindowAccess, fetcher: typeo
451
499
  throw new Error('JOB_REQUEST_INVALID');
452
500
  if (!response.ok && value.ok)
453
501
  throw new Error('JOB_REQUEST_INVALID');
502
+ if (!value.ok) Object.defineProperty(value.error, 'cause', {value:
503
+ `${init?.method ?? 'GET'} ${new URL(access.route(path), 'http://127.0.0.1').pathname} · ${typeof init?.body === 'string' ? new TextEncoder().encode(init.body).byteLength : 0} bytes · HTTP ${response.status}`});
454
504
  return value;
455
505
  }
456
506
  function post<Value>(path: string, body: unknown, signal?: AbortSignal) {
@@ -485,18 +535,55 @@ export async function* jobWindowEvents(access: JobWindowAccess, after: string |
485
535
  let newline = buffered.indexOf('\n');
486
536
  while (newline >= 0) {
487
537
  if (newline > limit)
488
- throw new Error('JOB_BODY_LIMIT');
538
+ throw new Error('JOB_BODY_LIMIT', {cause: 'client: event stream'});
489
539
  const event = JSON.parse(buffered.slice(0, newline)) as EventV3;
490
540
  if (!event || event.jobId !== access.jobId || typeof event.cursor !== 'string' ||
491
541
  !Number.isSafeInteger(event.generation) || event.generation < 0 ||
492
542
  !['published', 'pending', 'act', 'closed'].includes(event.type))
493
543
  throw new Error('JOB_STREAM_FAILED');
494
544
  buffered = buffered.slice(newline + 1);
545
+ const crops = new Map<string, {owner: Record<string, unknown>; key: string}[]>();
546
+ const packed = event as EventV3 & {_jobCommentCrops?: [string[], string][]};
547
+ for (const [path, sha256] of packed._jobCommentCrops ?? []) {
548
+ if (!Array.isArray(path) || !path.every(key => typeof key === 'string') || path.at(-1) !== 'png' ||
549
+ typeof sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(sha256)) throw new Error('JOB_STREAM_FAILED');
550
+ let owner: any = event;
551
+ for (const key of path.slice(0, -1)) {
552
+ if (!owner || typeof owner !== 'object' || !Object.hasOwn(owner, key)) throw new Error('JOB_STREAM_FAILED');
553
+ owner = owner[key];
554
+ }
555
+ if (owner?.png !== 'job-crop:' + sha256 || owner.sha256 !== sha256 ||
556
+ owner.path !== `comment-crops/${sha256}.png`) throw new Error('JOB_STREAM_FAILED');
557
+ const reference = 'job-crop:' + sha256, refs = crops.get(reference) ?? [];
558
+ refs.push({owner, key: 'png'}); crops.set(reference, refs);
559
+ }
560
+ delete packed._jobCommentCrops;
561
+ for (const [reference, refs] of crops) {
562
+ try {
563
+ const crop = await fetcher(access.route('comment-crops/' + reference.slice(9) + '.png'),
564
+ {signal: AbortSignal.any([signal, AbortSignal.timeout(5000)]), headers: access.headers()});
565
+ if (!crop.ok) throw new Error('JOB_STREAM_FAILED');
566
+ const bytes = new Uint8Array(await crop.arrayBuffer());
567
+ const digest = Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)),
568
+ byte => byte.toString(16).padStart(2, '0')).join('');
569
+ if (digest !== reference.slice(9)) throw new Error('JOB_STREAM_FAILED');
570
+ let binary = '';
571
+ for (const byte of bytes) binary += String.fromCharCode(byte);
572
+ for (const ref of refs) ref.owner[ref.key] = 'data:image/png;base64,' + btoa(binary);
573
+ } catch {
574
+ if (signal.aborted) return;
575
+ // A missing image is local presentation state, never a reason to replay an immutable act forever.
576
+ for (const ref of refs) {
577
+ ref.owner[ref.key] = null;
578
+ ref.owner.unavailable = 'COMMENT_CROP_STATE_UNAVAILABLE: stored crop cannot be read';
579
+ }
580
+ }
581
+ }
495
582
  yield event;
496
583
  newline = buffered.indexOf('\n');
497
584
  }
498
585
  if (buffered.length > limit)
499
- throw new Error('JOB_BODY_LIMIT');
586
+ throw new Error('JOB_BODY_LIMIT', {cause: 'client: event stream'});
500
587
  }
501
588
  }
502
589
  finally {
@@ -504,25 +591,17 @@ export async function* jobWindowEvents(access: JobWindowAccess, after: string |
504
591
  reader.releaseLock();
505
592
  }
506
593
  }
507
- /** One reader per window. Hub members bootstrap before visibility can suspend transport. */
594
+ /** One persistent reader per window, resumed from the last delivered cursor. */
508
595
  export function startJobWindowEvents(options: {
509
596
  access: JobWindowAccess;
510
597
  signal: AbortSignal;
511
- member: boolean;
512
598
  event(value: EventV3): void;
513
599
  refused(error: unknown): void;
514
600
  fetcher?: typeof fetch;
515
601
  }) {
516
- let bootstrap = options.member;
517
- let visible = !options.member;
518
602
  let cursor: string | null = null;
519
603
  let reader: AbortController | null = null;
520
604
  let wake: (() => void) | null = null;
521
- const enabled = () => bootstrap || visible;
522
- function changed() {
523
- if (!enabled()) reader?.abort();
524
- wake?.();
525
- }
526
605
  const stopped = () => { reader?.abort(); wake?.(); };
527
606
  options.signal.addEventListener('abort', stopped, {once: true});
528
607
  function wait(milliseconds?: number): Promise<void> {
@@ -536,7 +615,6 @@ export function startJobWindowEvents(options: {
536
615
  const done = (async () => {
537
616
  try {
538
617
  while (!options.signal.aborted) {
539
- if (!enabled()) { await wait(); continue; }
540
618
  const current = new AbortController();
541
619
  reader = current;
542
620
  try {
@@ -549,14 +627,12 @@ export function startJobWindowEvents(options: {
549
627
  } catch (error) {
550
628
  if (!current.signal.aborted && !options.signal.aborted) options.refused(error);
551
629
  } finally { reader = null; }
552
- if (!options.signal.aborted && enabled() && !current.signal.aborted) await wait(500);
630
+ if (!options.signal.aborted && !current.signal.aborted) await wait(500);
553
631
  }
554
632
  } finally { options.signal.removeEventListener('abort', stopped); }
555
633
  })();
556
634
  return {
557
635
  done,
558
- visibility(value: boolean) { if (options.member) { bootstrap = false; visible = value; changed(); } },
559
- displayed() { if (options.member) { bootstrap = false; changed(); } },
560
636
  };
561
637
  }
562
638
  import type { ModelAssets, RigPlayer } from '@rig-c/play';
@@ -565,7 +641,13 @@ import type { Checkpoint, ReviewManifest, ReviewedSource } from '../src/manifest
565
641
  import type { DirectionInspection } from '../src/direction-inspection.ts';
566
642
  import type { FeedbackCatalog } from '../src/feedback-validation.ts';
567
643
  import type { InterviewQuestion } from '../src/interview-project.ts';
644
+ type JobCheckpointEvidenceMetadata = Omit<JobCheckpointEvidence, 'tiles' | 'table'> & {
645
+ tiles: readonly (JobCheckpointEvidence['tiles'][number] & {url: string})[];
646
+ table: JobCheckpointEvidence['table'] & JobCheckpointTable & {url: string};
647
+ };
568
648
  export interface JobInspectionMetadata {
649
+ checkpointEvidence?: readonly JobCheckpointEvidenceMetadata[];
650
+ planText?: JobPlanTextProjection;
569
651
  manifest: ReviewManifest;
570
652
  recordSource?: undefined;
571
653
  sourceHash: string;
@@ -585,9 +667,11 @@ export interface JobInspectionMetadata {
585
667
  preRig?: boolean;
586
668
  playback: boolean;
587
669
  };
588
- feedbackCatalog: Pick<FeedbackCatalog, 'slots'>;
670
+ feedbackCatalog: Pick<FeedbackCatalog, 'slots'> & Partial<Pick<FeedbackCatalog, 'bones'>>;
589
671
  }
590
672
  export interface JobRecordInspectionMetadata {
673
+ checkpointEvidence?: readonly JobCheckpointEvidenceMetadata[];
674
+ planText?: JobPlanTextProjection;
591
675
  manifest?: undefined;
592
676
  recordSource: RecordSource;
593
677
  sourceHash: string;
@@ -602,7 +686,7 @@ export interface JobRecordInspectionMetadata {
602
686
  preRig?: boolean;
603
687
  playback: boolean;
604
688
  };
605
- feedbackCatalog: Pick<FeedbackCatalog, 'slots'>;
689
+ feedbackCatalog: Pick<FeedbackCatalog, 'slots'> & Partial<Pick<FeedbackCatalog, 'bones'>>;
606
690
  }
607
691
  export type JobInspectionMetadataV3 = JobInspectionMetadata | JobRecordInspectionMetadata;
608
692
  type JobInterview = {
@@ -614,22 +698,7 @@ type JobInterview = {
614
698
  })[];
615
699
  interview?: JobInterviewDiagnostics | null;
616
700
  };
617
- interface JobPartsInventory {
618
- sourceHash: string;
619
- rigSize: [
620
- number,
621
- number
622
- ] | null;
623
- items: {
624
- name: string;
625
- index: number;
626
- x: number;
627
- y: number;
628
- w: number;
629
- h: number;
630
- imageHash?: string;
631
- }[];
632
- }
701
+ type JobPartsInventory = import('./parts-viewport-provider.ts').PartsSubjectData;
633
702
  interface JobReferenceView {
634
703
  id: string;
635
704
  label: string;
@@ -639,6 +708,42 @@ interface JobReferenceView {
639
708
  seek(time: number, signal: AbortSignal): Promise<void>;
640
709
  }
641
710
 
711
+ /** Read composition at the host boundary. Unknown IDs remain local to their slot. */
712
+ export function resolveJobPanels(metadata: JobInspectionMetadataV3, source: SourceV3) {
713
+ const parts: JobPanelComposition = {schema: JOB_PANEL_COMPOSITION_SCHEMA, left: ['parts.list'],
714
+ stage: ['parts.canvas'], toolbar: ['parts.layers'], side: ['parts.issues', 'act.submit']};
715
+ const stage: PanelComponent = isRecordSource(source) ? source.subject === 'plan' ? 'plan.body' : 'interview.picks' :
716
+ source.direction ? 'scene.composite' : 'rig.playback';
717
+ const fallback: JobPanelComposition = metadata.capabilities.preRig ? parts :
718
+ {schema: JOB_PANEL_COMPOSITION_SCHEMA, stage: [stage], side: ['act.submit']};
719
+ const raw: unknown = metadata.manifest?.panels;
720
+ if (raw === undefined) return {composition: fallback, invalid: false};
721
+ try { return {composition: parsePanelComposition(raw), invalid: false}; }
722
+ catch { return {composition: fallback, invalid: true}; }
723
+ }
724
+
725
+ /** Derived only from finalized asks, including cursor replay after reload. */
726
+ export function jobPartsReviewState(asks: readonly JobWindowAsk[], publicationId: string) {
727
+ const bound = asks.filter(ask => ask.publicationId === publicationId);
728
+ const verdict = bound.filter(ask => ask.subject.kind === 'parts-verdict').at(-1);
729
+ const act = verdict?.act;
730
+ if (act?.kind !== 'parts-verdict' || (act.schema !== JOB_PARTS_VERDICT_ACT_SCHEMA && act.schema !== JOB_COMMENTS_ACT_SCHEMA)) return 'reviewing';
731
+ if (act.value.verdict === 'changes-requested') return 'sent';
732
+ const approved = bound.some(ask => ask.subject.kind === 'signoff' && ask.subject.stage === 'parts-review' &&
733
+ ask.act?.kind === 'signoff' && ask.act.value.decision === 'approved');
734
+ return approved ? 'approved' : 'retry-signoff';
735
+ }
736
+
737
+ /** A declared painting identity takes precedence over manifest reference order. */
738
+ export function jobPartsPainting(prepared: Pick<JobPreparedInspection, 'metadata' | 'display' | 'references'>) {
739
+ const declared = prepared.metadata.sourcePainting;
740
+ if (declared) return prepared.references.find(reference => reference.id === declared.id) ?? null;
741
+ const source = prepared.display.publication.source;
742
+ if (isRecordSource(source)) return null;
743
+ const painting = source.parts?.images.find(image => image.role === 'painting');
744
+ return painting ? prepared.references.find(reference => reference.label === painting.role + ' ' + painting.path) ?? null : null;
745
+ }
746
+
642
747
  /** A reference stays off-stage until its seek matches the latest inspection time. */
643
748
  export function createJobReferenceSelection<Reference extends Pick<JobReferenceView, 'seek'>>(options: {
644
749
  current(): {owner: object | null; time: number};
@@ -686,8 +791,13 @@ export interface JobPreparedInspection {
686
791
  interview: JobInterview | null;
687
792
  parts: JobPartsInventory | null;
688
793
  partImages: Map<string, HTMLImageElement>;
794
+ partPages?: Map<number, HTMLImageElement>;
689
795
  interviewImages: Map<string, HTMLImageElement>;
690
- imageSetImages?: readonly HTMLImageElement[];
796
+ checkpointEvidence?: readonly {
797
+ packet: JobCheckpointEvidence;
798
+ table: JobCheckpointTable;
799
+ images: readonly HTMLImageElement[];
800
+ }[];
691
801
  references: JobReferenceView[];
692
802
  assets: ModelAssets | null;
693
803
  player: RigPlayer | null;
@@ -711,7 +821,7 @@ async function jobBytes(url: string, signal: AbortSignal, maximum: number): Prom
711
821
  break;
712
822
  size += next.value.length;
713
823
  if (size > maximum)
714
- throw new Error('JOB_BODY_LIMIT');
824
+ throw new Error('JOB_BODY_LIMIT', {cause: 'client: preload'});
715
825
  chunks.push(next.value);
716
826
  }
717
827
  }
@@ -735,7 +845,7 @@ async function jobJson<Value>(url: string, signal: AbortSignal): Promise<Value>
735
845
  const bytes = await jobBytes(url, signal, 2 * 1024 * 1024);
736
846
  return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)) as Value;
737
847
  }
738
- function mediaReady(media: HTMLVideoElement, name: 'loadeddata' | 'seeked', signal: AbortSignal): Promise<void> {
848
+ export function mediaReady(media: HTMLVideoElement, name: 'loadeddata' | 'seeked', signal: AbortSignal): Promise<void> {
739
849
  return new Promise((resolve, reject) => {
740
850
  const finish = (error?: Error) => {
741
851
  clearTimeout(timer);
@@ -758,7 +868,7 @@ function mediaReady(media: HTMLVideoElement, name: 'loadeddata' | 'seeked', sign
758
868
  });
759
869
  }
760
870
  /** Prepare the real published Play model, references and every form dependency off-stage. */
761
- export async function prepareJobInspection(display: DisplayPublicationV3, signal: AbortSignal): Promise<JobPreparedInspection> {
871
+ export async function prepareJobInspection(display: DisplayPublicationV3, signal: AbortSignal, formsOnly=false): Promise<JobPreparedInspection> {
762
872
  const routes = jobPublicationRoutes(display, location.origin);
763
873
  const metadata = await jobJson<JobInspectionMetadataV3>(routes.api('review'), signal);
764
874
  const publishedSource = display.publication.source;
@@ -777,6 +887,7 @@ export async function prepareJobInspection(display: DisplayPublicationV3, signal
777
887
  }
778
888
  const objectUrls: string[] = [];
779
889
  const media: HTMLVideoElement[] = [];
890
+ if (metadata.planText !== undefined) metadata.planText = jobPlanTextForSource(metadata.planText, publishedSource);
780
891
  const rigRoot = document.createElement('div');
781
892
  rigRoot.id = 'rig-root';
782
893
  let assets: ModelAssets | null = null;
@@ -805,22 +916,40 @@ export async function prepareJobInspection(display: DisplayPublicationV3, signal
805
916
  for (const url of objectUrls)
806
917
  URL.revokeObjectURL(url);
807
918
  };
808
- async function visualBytes(url: string, hash?: string) {
809
- const bytes = await jobBytes(url, signal, 128 * 1024 * 1024);
919
+ async function visualBytes(url: string, hash?: string, maximum = 128 * 1024 * 1024,
920
+ hashRefusal = 'JOB_SOURCE_MISMATCH') {
921
+ const bytes = await jobBytes(url, signal, maximum);
810
922
  if (hash && await jobDigest(bytes) !== hash)
811
- throw new Error('JOB_SOURCE_MISMATCH');
923
+ throw new Error(hashRefusal);
924
+ if (disposed || signal.aborted) throw new Error('JOB_PRELOAD_CANCELLED');
812
925
  return bytes;
813
926
  }
814
- async function image(url: string, hash?: string): Promise<HTMLImageElement> {
815
- const bytes = await visualBytes(url, hash);
927
+ async function image(url: string, hash?: string, evidence = false): Promise<HTMLImageElement> {
928
+ const bytes = await visualBytes(url, hash, evidence ? 8 * 1024 * 1024 : undefined,
929
+ evidence ? 'CHECKPOINT_EVIDENCE_HASH_MISMATCH' : undefined);
930
+ if (disposed || signal.aborted) throw new Error('JOB_PRELOAD_CANCELLED');
816
931
  const blob = URL.createObjectURL(new Blob([bytes.slice().buffer]));
817
932
  objectUrls.push(blob);
818
933
  const image = new Image();
819
934
  image.src = blob;
820
- await image.decode();
821
- if (!image.naturalWidth || !image.naturalHeight || signal.aborted)
822
- throw new Error('JOB_VISUAL_UNAVAILABLE');
823
- return image;
935
+ let cancel: () => void = () => {};
936
+ const cancelled = new Promise<never>((_resolve, reject) => {
937
+ cancel = () => reject(new Error('JOB_PRELOAD_CANCELLED'));
938
+ signal.addEventListener('abort', cancel, {once: true});
939
+ if (signal.aborted) cancel();
940
+ });
941
+ try {
942
+ await Promise.race([image.decode().catch(error => {
943
+ if (evidence) throw new Error('CHECKPOINT_EVIDENCE_PNG_INVALID');
944
+ throw error;
945
+ }), cancelled]);
946
+ if (disposed || signal.aborted) throw new Error('JOB_PRELOAD_CANCELLED');
947
+ if (!image.naturalWidth || !image.naturalHeight)
948
+ throw new Error(evidence ? 'CHECKPOINT_EVIDENCE_PNG_INVALID' : 'JOB_VISUAL_UNAVAILABLE');
949
+ return image;
950
+ } finally {
951
+ signal.removeEventListener('abort', cancel);
952
+ }
824
953
  }
825
954
  try {
826
955
  const interview = metadata.capabilities.interview ? await jobJson<JobInterview>(routes.api('interview'), signal) : null;
@@ -828,31 +957,64 @@ export async function prepareJobInspection(display: DisplayPublicationV3, signal
828
957
  sourceSnapshot(interview.interview) !== sourceSnapshot(display.publication.interview)) {
829
958
  throw new Error('JOB_DISPLAY_MISMATCH');
830
959
  }
831
- const parts = metadata.capabilities.preRig ? await jobJson<JobPartsInventory>(routes.api('stage-parts'), signal) : null;
960
+ const parts = metadata.capabilities.preRig && 'parts' in publishedSource && publishedSource.parts ? await jobJson<JobPartsInventory>(routes.api('stage-parts'), signal) : null;
961
+ if (metadata.sourceHash !== publishedSource.sourceHash || parts && parts.sourceHash !== publishedSource.sourceHash)
962
+ throw new Error('JOB_SOURCE_MISMATCH');
832
963
  const references: JobReferenceView[] = [];
833
964
  const partImages = new Map<string, HTMLImageElement>();
834
965
  const interviewImages = new Map<string, HTMLImageElement>();
966
+ const partPages = new Map<number, HTMLImageElement>();
835
967
  const preload: Promise<void>[] = [];
836
- const imageSetImages: HTMLImageElement[] = [];
837
968
  const source = display.publication.source;
838
- if (source.subject === 'image-set') {
839
- if (metadata.sourceHash !== source.sourceHash || metadata.manifest?.model)
840
- throw new Error('JOB_DISPLAY_MISMATCH');
841
- const canonical = source.imageSet.images.map(({role, name, sha256}) => ({role, name, sha256}));
842
- if (source.imageSet.images.length < 2 || source.imageSet.images.length > 8 ||
843
- await jobDigest(new TextEncoder().encode(JSON.stringify(canonical))) !== source.imageSetDigest)
844
- throw new Error('JOB_SOURCE_MISMATCH');
845
- for (const [index, entry] of source.imageSet.images.entries()) {
846
- preload.push(image(routes.api('image-set/' + index), entry.sha256).then(element => {
847
- element.alt = entry.name;
848
- imageSetImages[index] = element;
849
- }));
969
+ const checkpointEvidence: NonNullable<JobPreparedInspection['checkpointEvidence']>[number][] = [];
970
+ if (Object.hasOwn(metadata, 'checkpointEvidence') !== Object.hasOwn(source, 'checkpointEvidence') ||
971
+ source.checkpointEvidence !== undefined && (!Array.isArray(metadata.checkpointEvidence) ||
972
+ metadata.checkpointEvidence.length !== source.checkpointEvidence.length)) {
973
+ throw new Error('CHECKPOINT_EVIDENCE_INVALID');
974
+ }
975
+ for (const [index, packet] of (source.checkpointEvidence ?? []).entries()) {
976
+ const projection = metadata.checkpointEvidence?.[index];
977
+ const tableUrl = `/api/checkpoint-evidence/${packet.checkpointId}/table`;
978
+ if (!projection?.table || !source.plan?.steps.some(step => step.id === packet.planStepId) ||
979
+ source.subject === 'plan' && !source.subjects.some(subject => subject.kind === 'checkpoint' &&
980
+ subject.checkpointId === packet.checkpointId && packet.planStepId === packet.checkpointId) ||
981
+ sourceSnapshot(projection) !== sourceSnapshot({...packet,
982
+ tiles: packet.tiles.map((tile, tileIndex) => ({...tile,
983
+ url: `/api/checkpoint-evidence/${packet.checkpointId}/tiles/${tileIndex}`})),
984
+ table: {...packet.table, url: tableUrl, schema: projection.table.schema,
985
+ columns: projection.table.columns, rows: projection.table.rows}})) {
986
+ throw new Error('CHECKPOINT_EVIDENCE_INVALID');
850
987
  }
851
988
  }
989
+ for (const [index, packet] of (source.checkpointEvidence ?? []).entries()) {
990
+ preload.push((async () => {
991
+ const bytes = await visualBytes(routes.api(`checkpoint-evidence/${packet.checkpointId}/table`),
992
+ packet.table.sha256, 256 * 1024, 'CHECKPOINT_EVIDENCE_HASH_MISMATCH');
993
+ let table: JobCheckpointTable;
994
+ try {
995
+ table = JSON.parse(new TextDecoder('utf-8', {fatal: true}).decode(bytes));
996
+ const projection = metadata.checkpointEvidence![index]!.table;
997
+ if (sourceSnapshot(table) !== sourceSnapshot({schema: projection.schema,
998
+ columns: projection.columns, rows: projection.rows})) throw new Error();
999
+ } catch {
1000
+ throw new Error('CHECKPOINT_EVIDENCE_TABLE_INVALID');
1001
+ }
1002
+ const images = await Promise.all(packet.tiles.map(async (tile, tileIndex) => {
1003
+ const element = await image(routes.api(`checkpoint-evidence/${packet.checkpointId}/tiles/${tileIndex}`),
1004
+ tile.sha256, true);
1005
+ element.alt = tile.label;
1006
+ return element;
1007
+ }));
1008
+ checkpointEvidence[index] = {packet, table, images};
1009
+ })());
1010
+ }
852
1011
  for (const reference of metadata.manifest?.references ?? []) {
1012
+ if (reference.id === metadata.sourcePainting?.id) continue;
853
1013
  preload.push((async () => {
854
1014
  if (reference.type === 'image') {
855
- const element = await image(routes.asset(reference.path), metadata.referenceHashes?.[reference.id]);
1015
+ const painting = !isRecordSource(source) ? source.parts?.images.find(entry =>
1016
+ entry.role === 'painting' && reference.label === entry.role + ' ' + entry.path) : null;
1017
+ const element = await image(routes.asset(reference.path), painting?.sha256 ?? metadata.referenceHashes?.[reference.id]);
856
1018
  element.alt = reference.label;
857
1019
  references.push({ id: reference.id, label: reference.label, element,
858
1020
  width: element.naturalWidth, height: element.naturalHeight, seek: async () => { } });
@@ -957,6 +1119,10 @@ export async function prepareJobInspection(display: DisplayPublicationV3, signal
957
1119
  preload.push(image(routes.api('stage-parts/image/' + part.index), part.imageHash)
958
1120
  .then(element => { element.alt = part.name; partImages.set(part.name, element); }));
959
1121
  }
1122
+ for (const page of parts?.pages ?? []) {
1123
+ preload.push(image(routes.api('stage-parts/page/' + page.index))
1124
+ .then(element => { partPages.set(page.index, element); }));
1125
+ }
960
1126
  for (const question of interview?.questions ?? [])
961
1127
  for (const asset of question.images) {
962
1128
  preload.push(image(routes.instance(asset.url)).then(element => { element.alt = asset.name; interviewImages.set(asset.url, element); }));
@@ -965,7 +1131,7 @@ export async function prepareJobInspection(display: DisplayPublicationV3, signal
965
1131
  const failed = preloaded.find(result => result.status === 'rejected');
966
1132
  if (failed?.status === 'rejected')
967
1133
  throw failed.reason;
968
- if (metadata.manifest?.model) {
1134
+ if (!formsOnly && metadata.manifest?.model) {
969
1135
  const runtime = await import('@rig-c/play');
970
1136
  const modelUrl = routes.asset(metadata.manifest.model);
971
1137
  const modelHash = metadata.reviewedSource!.rig!.sha256;
@@ -997,7 +1163,7 @@ export async function prepareJobInspection(display: DisplayPublicationV3, signal
997
1163
  };
998
1164
  resetToSetup();
999
1165
  }
1000
- if (!isRecordSource(source) && !player && !references.length && !partImages.size && !imageSetImages.length)
1166
+ if (!formsOnly && !isRecordSource(source) && !player && !references.length && !partImages.size && !checkpointEvidence.length)
1001
1167
  throw new Error('JOB_VISUAL_UNAVAILABLE');
1002
1168
  if (signal.aborted)
1003
1169
  throw new Error('JOB_PRELOAD_CANCELLED');
@@ -1005,7 +1171,7 @@ export async function prepareJobInspection(display: DisplayPublicationV3, signal
1005
1171
  const order = [metadata.sourcePainting?.id, ...(metadata.manifest?.references.map(reference => reference.id) ?? [])];
1006
1172
  references.sort((a, b) => order.indexOf(a.id) - order.indexOf(b.id));
1007
1173
  return {
1008
- display, metadata, interview, parts, partImages, interviewImages, imageSetImages, references, assets, rigRoot,
1174
+ display, metadata, interview, parts, partImages, partPages, interviewImages, checkpointEvidence, references, assets, rigRoot,
1009
1175
  get rigPresentation() { return rigPresentation; },
1010
1176
  set rigPresentation(value) {
1011
1177
  clearRigPresentation();
@@ -1022,517 +1188,22 @@ export async function prepareJobInspection(display: DisplayPublicationV3, signal
1022
1188
  throw error;
1023
1189
  }
1024
1190
  }
1025
- /** Browser mount is explicit so importing transaction helpers never starts an app. */
1026
- export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1027
- const [{ createViewportController, createViewportState }, { createRigViewportProvider }, { mountViewportPair }, i18n] = await Promise.all([
1028
- import('./viewport-controller.ts'), import('./rig-viewport-provider.ts'),
1029
- import('./viewport-pair.ts'), import('./i18n.ts'),
1030
- ]);
1031
- let storage: Storage | null = null;
1032
- try {
1033
- storage = sessionStorage;
1034
- }
1035
- catch { /* Capability stays in memory. */ }
1036
- const access = jobWindowAccess(location.href, storage, href => history.replaceState(history.state, '', href));
1037
- const hubIncarnation = new URL(location.href).searchParams.get('hub');
1038
- let hubVisible = !hubIncarnation;
1039
- let events: ReturnType<typeof startJobWindowEvents> | undefined;
1040
- const pageId = crypto.randomUUID();
1041
- const transport = createJobWindowTransport(access);
1042
- const abort = new AbortController();
1043
- const language = new URL(location.href).searchParams.get('lang');
1044
- if (language === 'en' || language === 'ko')
1045
- i18n.setLanguagePreference(language);
1046
- const t = i18n.t;
1047
- const node = <Tag extends keyof HTMLElementTagNameMap>(tag: Tag, key?: string) => {
1048
- const value = document.createElement(tag);
1049
- if (key) {
1050
- value.dataset.jobText = key;
1051
- value.textContent = t(key);
1052
- }
1053
- return value;
1054
- };
1055
- const title = node('h1', 'job.title');
1056
- const languages = node('select');
1057
- for (const value of ['en', 'ko']) {
1058
- const option = node('option');
1059
- option.value = value;
1060
- option.textContent = value;
1061
- languages.append(option);
1062
- }
1063
- languages.value = i18n.getLanguage();
1064
- languages.setAttribute('aria-label', t('interview.language'));
1065
- languages.onchange = () => { i18n.setLinkLanguage(null); i18n.setLanguagePreference(languages.value === 'ko' ? 'ko' : 'en'); };
1066
- const header = node('header');
1067
- header.className = 'job-header';
1068
- header.append(title, languages);
1069
- const notice = node('p', 'job.waiting');
1070
- notice.className = 'job-notice';
1071
- notice.setAttribute('role', 'status');
1072
- const workspace = node('main');
1073
- host.classList.add('job-window');
1074
- host.replaceChildren(header, notice, workspace);
1075
- let current: JobPreparedInspection | null = null;
1076
- let currentElement: HTMLElement | null = null;
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;
1190
- let playing = false;
1191
- let loop = typeof savedWindow?.loop === 'boolean' ? savedWindow.loop : true;
1192
- let playbackCarry = 0;
1193
- let rafHandle = 0;
1194
- let lastFrameTime = 0;
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);
1206
- type JobForm = {
1207
- form: HTMLFormElement;
1208
- fieldset: HTMLFieldSetElement;
1209
- read: () => UISubmissionV3['value'];
1210
- submissionId: string;
1211
- dirty: boolean;
1212
- submitting: boolean;
1213
- rigSubmission: ReturnType<typeof createJobRigSubmission>;
1214
- };
1215
- type PreparedWindow = JobPreparedInspection & {
1216
- element: HTMLElement;
1217
- forms: Map<string, JobForm>;
1218
- };
1219
- const forms = new Map<string, JobForm>();
1220
- const drawn = new WeakMap<JobPreparedInspection, JobRigDraw>();
1221
- let drawGeneration = 0;
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
- }
1276
- const el = <Element extends HTMLElement = HTMLElement>(id: string): Element => {
1277
- const element = workspace.querySelector<HTMLElement>('#' + id);
1278
- if (!element)
1279
- throw new Error('JOB_WINDOW_ELEMENT_MISSING');
1280
- return element as Element;
1281
- };
1282
- const reference = () => current?.references.find(item => item.id === selectedReference) ?? null;
1283
- const setText = (id: string, value: string) => { const element = workspace.querySelector('#' + id); if (element)
1284
- element.textContent = i18n.tr(value); };
1285
- const provider = createRigViewportProvider({
1286
- el, player: () => current?.player ?? null, assets: () => current?.assets ?? null,
1287
- referenceSize: () => reference(), view: () => 'compare', referenceGeneration: () => current?.display.publication.generation ?? 0,
1288
- parts: () => current?.inspection ?? null, text: setText,
1289
- message: value => { notice.textContent = jobWindowRefusal(value); }, redrawOverlay: () => { },
1290
- }, viewportState);
1291
- const canonicalControls = provider.renderControls;
1292
- provider.renderControls = controller => {
1293
- canonicalControls(controller);
1294
- const fit = el('fit');
1295
- fit.textContent = t(fit.textContent ?? 'Fit');
1296
- saveWindowState();
1297
- };
1298
- const viewport = createViewportController(provider, viewportState);
1299
- const renderViewport = provider.render;
1300
- provider.render = controller => {
1301
- try {renderViewport(controller); rememberDraw();}
1302
- catch (error) {
1303
- if (current) {
1304
- drawn.delete(current);
1305
- current.rigPresentation = undefined;
1306
- }
1307
- throw error;
1308
- }
1309
- };
1310
- function rigDrawState(): JobRigDrawState {
1311
- const owner = current, player = owner?.player;
1312
- if (!owner || !player || !hubVisible) throw new Error('JOB_STILL_CAPTURE_FAILED');
1313
- const pane = el('rig-viewport'), root = owner.rigRoot, rect = pane.getBoundingClientRect();
1314
- const ratio = globalThis.devicePixelRatio || 1;
1315
- const frame = viewport.paneFrame('rig'), camera = viewport.numericView().cameras.rig;
1316
- if (!frame || !camera || !pane.isConnected || !root.isConnected || el('rig-pane').hidden ||
1317
- rect.width <= 0 || rect.height <= 0) throw new Error('JOB_STILL_CAPTURE_FAILED');
1318
- const style = getComputedStyle(root), paneStyle = getComputedStyle(pane);
1319
- const plain = style.filter === 'none' && style.perspective === 'none' && style.opacity === '1' &&
1320
- paneStyle.filter === 'none' && paneStyle.transform === 'none' && paneStyle.perspective === 'none' && paneStyle.opacity === '1';
1321
- const presentation = owner.rigPresentation;
1322
- const canvas = presentation?.canvas;
1323
- const pixels = canvas?.getBoundingClientRect();
1324
- const canvasStyle = canvas ? getComputedStyle(canvas) : null;
1325
- if (canvas && (!canvas.isConnected || canvasStyle?.visibility !== 'visible' ||
1326
- canvasStyle.display === 'none' || canvasStyle.opacity !== '1' || canvasStyle.filter !== 'none' ||
1327
- canvasStyle.transform !== 'none')) throw new Error('JOB_STILL_CAPTURE_FAILED');
1328
- return {player, presentation, frameGeneration: owner.inspection?.frame('single')?.generation,
1329
- source: {pageId, publicationId: owner.display.publication.publicationId,
1330
- instanceKey: owner.display.publication.instanceKey, sourceHash: owner.display.publication.source.sourceHash},
1331
- layout: JSON.stringify([
1332
- pane.clientWidth, pane.clientHeight, rect.width, rect.height, ratio,
1333
- root.getAttribute('style'), style.transform, camera, presentation?.area, presentation?.ratio,
1334
- pixels ? jobRigPixelPlacement(rect, pixels, ratio) : null,
1335
- pixels?.width, pixels?.height, canvas?.width, canvas?.height, canvas?.getAttribute('style'),
1336
- ]),
1337
- defaultCamera: plain && camera.zoom === 1 && camera.center.x === frame.center.x && camera.center.y === frame.center.y,
1338
- wholeRig: !selectedPart && !owner.inspection?.value() && player.slots === null,
1339
- playing};
1340
- }
1341
- function rememberDraw(): void {
1342
- const owner = current;
1343
- if (!owner) return;
1344
- try {
1345
- const player = owner.player;
1346
- const posed = owner.inspection?.frame('single');
1347
- const camera = viewport.numericView().cameras.rig;
1348
- if (!hubVisible || !player || !owner.assets || !posed || !camera) {
1349
- throw new Error('JOB_STILL_CAPTURE_FAILED');
1350
- }
1351
- const renderer = player.renderer;
1352
- const pane = el('rig-viewport');
1353
- const presentation = presentJobRigViewport({pane, root: owner.rigRoot, images: true,
1354
- canvas: renderer instanceof CanvasRenderer ? renderer.canvas : undefined,
1355
- backend: renderer instanceof CanvasRenderer ? renderer.backendActive : renderer.meshBackendActive},
1356
- {camera, posed, assets: owner.assets});
1357
- pane.append(presentation.canvas);
1358
- owner.rigPresentation = presentation;
1359
- pane.dataset.jobRigCanonical = '';
1360
- drawn.set(owner, recordJobRigDraw(rigDrawState(), ++drawGeneration));
1361
- } catch {
1362
- drawn.delete(owner);
1363
- owner.rigPresentation = undefined;
1364
- }
1365
- }
1366
- function drawInspection(owner: JobPreparedInspection): void {
1367
- drawn.delete(owner);
1368
- owner.rigPresentation = undefined;
1369
- owner.player?.draw();
1370
- owner.inspection?.present('single');
1371
- }
1372
- function syncTransportControls(): void {
1373
- const playBtn = workspace.querySelector<HTMLButtonElement>('#job-play');
1374
- if (playBtn) {
1375
- const clip = current?.assets?.animations.find(item => item.name === animation);
1376
- playBtn.disabled = !animation || !clip || !(clip.duration > 0) || !current?.player;
1377
- const key = playing ? 'Pause' : 'Play';
1378
- playBtn.dataset.jobText = key;
1379
- playBtn.textContent = t(key);
1380
- playBtn.setAttribute('aria-pressed', String(playing));
1381
- }
1382
- const loopInput = workspace.querySelector<HTMLInputElement>('#job-loop');
1383
- if (loopInput) loopInput.checked = loop;
1384
- }
1385
- function stopPlayback(targetPlayer = current?.player): void {
1386
- if (rafHandle) {
1387
- cancelAnimationFrame(rafHandle);
1388
- rafHandle = 0;
1389
- }
1390
- playing = false;
1391
- playbackCarry = 0;
1392
- lastFrameTime = 0;
1393
- lastRunningSaveMs = null;
1394
- targetPlayer?.pause();
1395
- syncTransportControls();
1396
- saveWindowState();
1397
- }
1398
- function presentCurrentFrame(owner: JobPreparedInspection): void {
1399
- if (!owner.player) return;
1400
- drawInspection(owner);
1401
- owner.inspection?.select(selectedPart ? { side: 'single', slot: selectedPart, mode: partMode } : null);
1402
- setText('job-part-observation', selectedPart ? JSON.stringify(owner.inspection?.observation(), null, 2) : '');
1403
- viewport.fitCamera();
1404
- }
1405
- function armPlayback(expectedOwner: JobPreparedInspection, expectedPlayer: RigPlayer): void {
1406
- if (rafHandle) {
1407
- cancelAnimationFrame(rafHandle);
1408
- rafHandle = 0;
1409
- }
1410
- const handle = requestAnimationFrame(now => stepPlayback(handle, expectedOwner, expectedPlayer, now));
1411
- rafHandle = handle;
1412
- }
1413
- function playbackTimeLabel(duration: number, trackTime: number): string {
1414
- // A one-second 1/60 replay leaves six epsilons after modulo. Limit display snapping
1415
- // to eight duration-scaled epsilons. The public time and captured frame stay raw.
1416
- if (trackTime < duration) return String(time);
1417
- const residue = 8 * Number.EPSILON * duration;
1418
- if (time <= residue) return '0';
1419
- if (duration - time <= residue) return String(duration);
1420
- return String(time);
1421
- }
1422
- function stepPlayback(handle: number, expectedOwner: JobPreparedInspection, expectedPlayer: RigPlayer, now: number): void {
1423
- if (current !== expectedOwner || current?.player !== expectedPlayer) {
1424
- expectedPlayer.pause();
1425
- return;
1426
- }
1427
- if (handle !== rafHandle) return;
1428
- rafHandle = 0;
1429
- const clip = expectedOwner.assets?.animations.find(item => item.name === animation);
1430
- if (!playing || !hubVisible || !animation || !clip || !(clip.duration > 0)) {
1431
- stopPlayback(expectedPlayer);
1432
- return;
1433
- }
1434
- const dt = lastFrameTime > 0 ? Math.min(Math.max(0, (now - lastFrameTime) / 1000), 0.1) : 0;
1435
- lastFrameTime = now;
1436
- const next = advancePlayback({ time, duration: clip.duration, carry: playbackCarry, elapsed: dt, repeat: loop });
1437
- for (const step of next.steps) expectedPlayer.advance(step);
1438
- const activeEntry = expectedPlayer.entry(0);
1439
- if (!activeEntry || activeEntry.animation !== animation || activeEntry.loop !== loop ||
1440
- !Number.isFinite(activeEntry.animationTime) || activeEntry.animationTime < 0 ||
1441
- activeEntry.animationTime > activeEntry.duration) {
1442
- stopPlayback(expectedPlayer);
1443
- return;
1444
- }
1445
- playbackCarry = next.carry;
1446
- if (next.ended) {
1447
- playing = false;
1448
- playbackCarry = 0;
1449
- lastFrameTime = 0;
1450
- expectedPlayer.pause();
1451
- time = clip.duration;
1452
- } else {
1453
- time = activeEntry.animationTime;
1454
- }
1455
- const clock = workspace.querySelector<HTMLInputElement>('#job-time');
1456
- if (clock) clock.value = playbackTimeLabel(clip.duration, activeEntry.trackTime);
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
- }
1471
- if (playing && current === expectedOwner && current.player === expectedPlayer && hubVisible) {
1472
- armPlayback(expectedOwner, expectedPlayer);
1473
- }
1474
- }
1475
- function copyRigVerdict(ask: PendingAskV3, owner: JobPreparedInspection) {
1476
- if (owner !== current || ask.publicationId !== owner.display.publication.publicationId) {
1477
- throw new Error('JOB_STILL_BINDING_MISMATCH');
1478
- }
1479
- assertJobAskSource(ask, owner.display);
1480
- return freezeJobRigCapture(drawn.get(owner), rigDrawState(), ask.askId, () => {
1481
- if (!owner.rigPresentation) throw new Error('JOB_STILL_CAPTURE_FAILED');
1482
- return copyJobRigViewport(owner.rigPresentation);
1483
- });
1484
- }
1485
- const referenceSelection = createJobReferenceSelection<JobReferenceView>({
1486
- current: () => ({owner: current, time}),
1487
- present(value) {
1488
- const previous = selectedReference;
1489
- const camera = structuredClone(viewportState);
1490
- selectedReference = value.id;
1491
- try {
1492
- showReference();
1493
- el<HTMLSelectElement>('job-reference').value = value.id;
1494
- viewport.fitCamera();
1495
- } catch (error) {
1496
- selectedReference = previous;
1497
- Object.assign(viewportState, camera);
1498
- showReference();
1499
- el<HTMLSelectElement>('job-reference').value = previous;
1500
- viewport.fitCamera();
1501
- throw error;
1502
- }
1503
- },
1504
- refused(error) {
1505
- el<HTMLSelectElement>('job-reference').value = selectedReference;
1506
- notice.textContent = jobWindowRefusal(error, 'JOB_VISUAL_UNAVAILABLE');
1507
- },
1508
- });
1509
- let unbindNavigation: (() => void) | null = null;
1510
- let resize: ResizeObserver | null = null;
1511
- function localDraftKey(display: DisplayPublicationV3): string {
1512
- return 'rig-review-job-draft/1:' + access.jobId + ':' + display.publication.publicationId + ':' + display.publication.source.sourceHash;
1513
- }
1514
- function saveDraft(): void {
1515
- if (!current)
1516
- return;
1517
- try {
1518
- localStorage.setItem(localDraftKey(current.display), JSON.stringify({
1519
- publicationId: current.display.publication.publicationId,
1520
- sourceHash: current.display.publication.source.sourceHash,
1521
- source: current.display.publication.source,
1522
- label: current.display.publication.label,
1523
- forms: [...forms].filter(([, item]) => item.dirty).map(([askId, item]) => ({
1524
- askId, value: item.read(),
1525
- controls: [...item.form.querySelectorAll<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>('input[name],textarea[name],select[name]')]
1526
- .map(input => ({ name: input.name, value: input.value })),
1527
- })),
1528
- }));
1529
- }
1530
- catch { /* The in-memory retained draft remains source-bound. */ }
1531
- }
1191
+ export type JobForm = {
1192
+ form: HTMLFormElement & {commentWords?:()=>string};
1193
+ fieldset: HTMLFieldSetElement;
1194
+ read: () => UISubmissionV3['value'];
1195
+ submissionId: string;
1196
+ dirty: boolean;
1197
+ submitting: boolean;
1198
+ dispose?():void;
1199
+ };
1200
+
1201
+ type JobFormNode = <Tag extends keyof HTMLElementTagNameMap>(tag: Tag, key?: string) => HTMLElementTagNameMap[Tag];
1202
+
1203
+ /** Existing form and inspection helpers, without a workspace mount. */
1204
+ export function createJobFormHelpers(node: JobFormNode, t: typeof import('./i18n.ts').t) {
1532
1205
  function inputLabel(key: string, input: HTMLElement): HTMLElement {
1533
- const label = node('label');
1534
- label.append(node('span', key), input);
1535
- return label;
1206
+ return labelledControl(node('span', key), input);
1536
1207
  }
1537
1208
  function selectValues(values: readonly string[], labels: readonly string[]): HTMLSelectElement {
1538
1209
  const select = node('select');
@@ -1543,28 +1214,167 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1543
1214
  });
1544
1215
  return select;
1545
1216
  }
1546
- function textArea(parent: HTMLElement, key: string, name = 'note'): HTMLTextAreaElement {
1547
- const input = node('textarea');
1548
- input.name = name;
1549
- parent.append(inputLabel(key, input));
1550
- return input;
1217
+ function imageGallery(images: readonly {name: string; sha256: string; element?: HTMLImageElement;
1218
+ role?: string; duplicate?: boolean}[], titleOnly = false, native = false): HTMLElement {
1219
+ const gallery = node('section');
1220
+ gallery.style.display = 'grid';
1221
+ gallery.style.gridAutoFlow = 'column';
1222
+ gallery.style.gridAutoColumns = 'minmax(180px, 1fr)';
1223
+ gallery.style.gap = '16px';
1224
+ gallery.style.overflow = 'auto';
1225
+ gallery.style.minHeight = '0';
1226
+ gallery.style.flex = '1';
1227
+ if(native){gallery.style.gridAutoColumns='max-content';gallery.style.overflow='visible';gallery.style.width='max-content';gallery.style.color='var(--rv-stage-fg)';}
1228
+ for (const image of images) {
1229
+ const element = image.element;
1230
+ if (!element) throw new Error('JOB_VISUAL_UNAVAILABLE');
1231
+ const figure = node('figure');
1232
+ figure.style.margin = '0';
1233
+ figure.style.minWidth = '0';
1234
+ figure.dataset.imageName = image.name;
1235
+ const name = node('h3');
1236
+ name.textContent = image.name;
1237
+ name.setAttribute('translate', 'no');
1238
+ name.style.overflowWrap = 'anywhere';
1239
+ const role = image.role ? node('p', 'job.imageRole.' + image.role) : node('p');
1240
+ const hash = node('code');
1241
+ hash.className = 'job-source';
1242
+ hash.style.display = 'block';
1243
+ hash.style.overflowWrap = 'anywhere';
1244
+ if (titleOnly || native) hash.title = image.sha256;
1245
+ else hash.textContent = image.sha256;
1246
+ element.style.width = '100%';
1247
+ element.style.height = 'auto';
1248
+ element.style.maxHeight = '70vh';
1249
+ element.style.objectFit = 'contain';
1250
+ if(native){element.style.width=element.naturalWidth+'px';element.style.maxHeight='none';figure.style.width=element.naturalWidth+'px';}
1251
+ if(native){figure.title=image.sha256;figure.append(name,element);}else figure.append(name, role, element, hash);
1252
+ if (image.duplicate)
1253
+ figure.append(node('p', 'job.identicalImages'));
1254
+ gallery.append(figure);
1255
+ }
1256
+ return gallery;
1257
+ }
1258
+ function planStepText(element: HTMLElement, step: NonNullable<SourceV3['plan']>['steps'][number],
1259
+ projection: JobPlanTextProjection | undefined): void {
1260
+ const row = projection?.status === 'projected' ? projection.steps.find(row => row.id === step.id && row.hash === step.hash) : undefined;
1261
+ const key = row?.does === undefined ? 'job.plan.field.' + (row?.issues.find(issue => issue.field === 'does')?.reason ?? 'absent') : undefined;
1262
+ // Producer identities stay raw; absence keys still follow the job form's own language binding.
1263
+ element.setAttribute('translate', 'no');
1264
+ if (key) element.dataset.jobText = key;
1265
+ else delete element.dataset.jobText;
1266
+ element.textContent = key ? t(key) : row!.does!;
1267
+ }
1268
+ function planTextList(plan: NonNullable<SourceV3['plan']>, projection: JobPlanTextProjection | undefined,
1269
+ selectedId?: string): HTMLElement {
1270
+ const section = node('section');
1271
+ section.className = 'job-plan-text';
1272
+ if (!projection || projection.status === 'unavailable') {
1273
+ section.append(node('p', 'job.plan.noText'));
1274
+ if (projection) section.append(node('p', projection.reason));
1275
+ }
1276
+ const list = node('ol');
1277
+ list.className = 'job-plan-steps';
1278
+ for (const step of plan.steps) {
1279
+ if (selectedId !== undefined && step.id !== selectedId) continue;
1280
+ const item = node('li');
1281
+ item.dataset.jobPlanStep = step.id;
1282
+ const details = node('details');
1283
+ details.open = true;
1284
+ const title = node('summary');
1285
+ planStepText(title, step, projection);
1286
+ title.title = step.id + ' · ' + step.hash;
1287
+ details.append(title);
1288
+ const row = projection?.status === 'projected' ? projection.steps.find(row => row.id === step.id && row.hash === step.hash) : undefined;
1289
+ if (row) {
1290
+ const fields = node('dl');
1291
+ for (const field of JOB_PLAN_TEXT_FIELDS) {
1292
+ if (field === 'does') continue;
1293
+ const term = node('dt', 'job.plan.' + field);
1294
+ const value = node('dd');
1295
+ value.dataset.jobPlanField = field;
1296
+ const issue = row.issues.find(issue => issue.field === field);
1297
+ if (issue) value.append(node('span', 'job.plan.field.' + issue.reason));
1298
+ else if (field === 'rests_on') {
1299
+ const rests = node('ul');
1300
+ for (const text of row.rests_on!) {
1301
+ const rest = node('li'), dependency = plan.steps.find(step => step.id === text);
1302
+ if (dependency) {planStepText(rest, dependency, projection); rest.title = text;}
1303
+ else {rest.textContent = text; rest.setAttribute('translate', 'no');}
1304
+ rests.append(rest);
1305
+ }
1306
+ value.append(rests);
1307
+ } else {value.textContent = row[field]!; value.setAttribute('translate', 'no');}
1308
+ fields.append(term, value);
1309
+ }
1310
+ details.append(fields);
1311
+ }
1312
+ item.append(details); list.append(item);
1313
+ }
1314
+ list.addEventListener('keydown', event => {
1315
+ const key = event as KeyboardEvent;
1316
+ if (!['ArrowUp', 'ArrowDown'].includes(key.key) || !(key.target instanceof HTMLElement) || key.target.tagName !== 'SUMMARY') return;
1317
+ const summaries = [...list.querySelectorAll<HTMLElement>('summary')];
1318
+ const index = summaries.indexOf(key.target);
1319
+ const next = summaries[index + (key.key === 'ArrowDown' ? 1 : -1)];
1320
+ if (next) {key.preventDefault(); next.focus();}
1321
+ });
1322
+ section.append(list);
1323
+ return section;
1551
1324
  }
1552
- function formFor(ask: PendingAskV3, prepared: JobPreparedInspection): JobForm {
1325
+ return {inputLabel, selectValues, imageGallery, planTextList, planStepText};
1326
+ }
1327
+
1328
+ /** The answer builder owns no page shell, transport or draft collection. */
1329
+ export interface JobFormDependencies {
1330
+ node: JobFormNode;
1331
+ translate: typeof import('./i18n.ts').t;
1332
+ helpers: ReturnType<typeof createJobFormHelpers> & {
1333
+ assertJobAskSource: typeof assertJobAskSource;
1334
+ jobCheckpointContext: typeof jobCheckpointContext;
1335
+ };
1336
+ draftStorage(): Pick<Storage, 'getItem'>;
1337
+ localDraftKey(display: DisplayPublicationV3): string;
1338
+ saveDraft(): void;
1339
+ window: {
1340
+ state(): Pick<JobWindowState, 'receipt' | 'preparing' | 'closed' | 'generation' | 'pending'>;
1341
+ submit(input: UISubmissionV3): Promise<JobResult<ActV3>>;
1342
+ };
1343
+ access: Pick<JobWindowAccess, 'capability'>;
1344
+ pageId: string;
1345
+ }
1346
+
1347
+ /** Build the existing answer form with explicit host dependencies. */
1348
+ function formFor(ask: PendingAskV3, prepared: JobPreparedInspection, deps: JobFormDependencies): JobForm {
1349
+ const {node, translate: t, helpers: {selectValues, imageGallery, planTextList, planStepText, assertJobAskSource, jobCheckpointContext},
1350
+ draftStorage, localDraftKey, saveDraft, window, access, pageId} = deps;
1553
1351
  if (ask.publicationId !== prepared.display.publication.publicationId)
1554
1352
  throw new Error('JOB_DISPLAY_MISMATCH');
1555
1353
  assertJobAskSource(ask, prepared.display);
1556
- const form = node('form');
1354
+ // Rig verdicts belong to the shared screen; unsupported combinations have no job-window form.
1355
+ if (ask.subject.kind === 'review-verdict' && ask.subject.stage === 'rig-review')
1356
+ throw new Error('JOB_ACT_KIND_DISABLED');
1357
+ const form = node('form') as JobForm['form'];
1557
1358
  form.dataset.jobAsk = ask.askId;
1359
+ form.dataset.jobPublication = ask.publicationId;
1558
1360
  const fields = node('fieldset');
1559
1361
  form.append(fields);
1560
1362
  const source = node('p');
1561
1363
  source.className = 'job-source';
1562
- source.textContent = prepared.display.publication.label + ' · ' + ask.source.sourceHash;
1364
+ source.textContent = ask.subject.kind === 'review-verdict'
1365
+ ? prepared.display.publication.label + ' · ' + ask.source.sourceHash : prepared.display.publication.label;
1366
+ if (ask.subject.kind !== 'review-verdict') {source.title = ask.source.sourceHash; source.setAttribute('translate', 'no');}
1563
1367
  fields.append(source);
1564
- const note = textArea(fields, 'interview.note');
1368
+ const subject = ask.subject;
1369
+ if(subject.kind==='review-verdict')throw new Error('JOB_ACT_KIND_DISABLED');
1370
+ const commentOnly = subject.kind === 'checkpoint' || subject.kind === 'signoff' || subject.kind === 'reopen';
1371
+ if(commentOnly)fields.append(node('p','job.commentsFromWorkspace'));
1372
+ let retainedCommentWords='';
1373
+ const commentWords=()=>form.commentWords?.()??retainedCommentWords;
1565
1374
  let read: () => UISubmissionV3['value'];
1566
1375
  let submitKey = 'Submit review';
1567
- const subject = ask.subject;
1376
+ let disposeInterview:(()=>void)|undefined;
1377
+ let interviewForm:ReturnType<typeof createInterviewForm>|undefined;
1568
1378
  if (subject.kind === 'interview-picks') {
1569
1379
  const question = prepared.interview?.questions.find(item => item.set.id === subject.setId && item.set.question === subject.questionId);
1570
1380
  if (!question || !question.editable) throw new Error('JOB_ASK_INVALID');
@@ -1589,130 +1399,92 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1589
1399
  legacyNotice.dataset.record = legacyDiagnostic.record;
1590
1400
  fields.prepend(legacyNotice);
1591
1401
  }
1592
- const heading = node('h3');
1593
- heading.textContent = question.set.question;
1594
- fields.prepend(heading);
1595
- const answers = question.set.asks.map(item => {
1596
- const group = node('fieldset');
1597
- const legend = node('legend');
1598
- legend.textContent = item.prompt;
1599
- group.append(legend);
1600
- const pick = node('select');
1601
- pick.required = true;
1602
- pick.name = 'choice.' + item.id;
1603
- const empty = node('option', 'job.choose');
1604
- empty.value = '';
1605
- pick.append(empty);
1606
- for (const choice of item.options) {
1607
- const option = node('option');
1608
- option.value = choice.id;
1609
- option.textContent = choice.label + ' · ' + choice.effect;
1610
- pick.append(option);
1611
- }
1612
- const other = node('textarea');
1613
- other.hidden = true;
1614
- other.name = 'other.' + item.id;
1615
- const warning = node('p');
1616
- warning.hidden = true;
1617
- pick.onchange = () => {
1618
- const choice = item.options.find(option => option.id === pick.value);
1619
- other.hidden = choice?.kind !== 'other';
1620
- other.required = choice?.kind === 'other';
1621
- warning.hidden = choice?.kind === 'value';
1622
- warning.textContent = t(choice?.kind === 'other' ? 'interview.otherPending' : 'interview.autoPending');
1623
- };
1624
- group.append(pick, other, warning);
1625
- fields.append(group);
1626
- return { item, pick, other };
1627
- });
1628
- for (const image of question.images) {
1629
- const visual = prepared.interviewImages.get(image.url);
1630
- if (!visual)
1631
- throw new Error('JOB_VISUAL_UNAVAILABLE');
1632
- fields.append(visual.cloneNode(true));
1633
- }
1634
- read = () => ({ questionId: subject.questionId,
1635
- selections: answers.map(({ item, pick, other }) => ({ itemId: item.id, optionId: pick.value,
1636
- otherText: item.options.find(option => option.id === pick.value)?.kind === 'other' ? other.value : null })), note: note.value });
1402
+ interviewForm=createInterviewForm({question,id:'interview-answer-'+ask.askId,node,form,fieldset:fields,source,
1403
+ images:question.images.map(image=>{const visual=prepared.interviewImages.get(image.url);if(!visual)throw new Error('JOB_VISUAL_UNAVAILABLE');return {name:image.name,src:visual.src};}),answered:ask.status==='answered'});
1404
+ disposeInterview=interviewForm.dispose;read=interviewForm.read;
1637
1405
  submitKey = 'interview.save';
1638
1406
  }
1639
1407
  else if (subject.kind === 'checkpoint') {
1640
1408
  const checkpoint = jobCheckpointContext(ask, prepared.metadata.manifest?.checkpoints ?? []);
1641
1409
  const heading = node('h3');
1642
1410
  heading.textContent = checkpoint.title;
1411
+ heading.title = subject.checkpointId;
1412
+ heading.setAttribute('translate', 'no');
1413
+ if (prepared.metadata.manifest?.checkpoints.find(item => item.id === subject.checkpointId)?.title == null)
1414
+ planStepText(heading, checkpoint.step, prepared.metadata.planText);
1643
1415
  fields.prepend(heading);
1644
1416
  const guidance = node('p');
1645
1417
  guidance.textContent = checkpoint.note;
1646
- const planStep = node('p');
1647
- planStep.className = 'job-source';
1648
- planStep.textContent = checkpoint.step.id + ' · ' + checkpoint.step.hash;
1649
- fields.append(planStep, guidance);
1418
+ guidance.setAttribute('translate', 'no');
1419
+ fields.append(guidance, planTextList(ask.source.plan!, prepared.metadata.planText, checkpoint.step.id));
1420
+ const evidence = prepared.checkpointEvidence?.find(item => item.packet.checkpointId === subject.checkpointId);
1421
+ const declared = ask.source.checkpointEvidence?.find(item => item.checkpointId === subject.checkpointId);
1422
+ if (Boolean(declared) !== Boolean(evidence) || evidence &&
1423
+ (JSON.stringify(evidence.packet) !== JSON.stringify(declared) || evidence.packet.planStepId !== checkpoint.step.id)) {
1424
+ throw new Error('CHECKPOINT_EVIDENCE_INVALID');
1425
+ }
1426
+ if (evidence) {
1427
+ const section = node('section');
1428
+ section.dataset.jobCheckpointEvidence = subject.checkpointId;
1429
+ section.append(node('h4', 'job.checkpointEvidence'));
1430
+ section.append(imageGallery(evidence.packet.tiles.map((tile, index) => ({name: tile.label,
1431
+ sha256: tile.sha256, element: evidence.images[index]?.cloneNode(true) as HTMLImageElement})), true));
1432
+ const tableHost = node('div');
1433
+ tableHost.style.overflow = 'auto';
1434
+ tableHost.style.maxHeight = '50dvh';
1435
+ const table = node('table');
1436
+ table.dataset.jobCheckpointTable = '';
1437
+ const caption = node('caption', 'job.checkpointTable');
1438
+ if (evidence.packet.table.label !== undefined) {
1439
+ delete caption.dataset.jobText;
1440
+ caption.textContent = evidence.packet.table.label;
1441
+ caption.setAttribute('translate', 'no');
1442
+ }
1443
+ const head = node('thead');
1444
+ head.setAttribute('translate', 'no');
1445
+ const columns = node('tr');
1446
+ for (const column of evidence.table.columns) {
1447
+ const cell = node('th');
1448
+ cell.scope = 'col';
1449
+ cell.textContent = column;
1450
+ columns.append(cell);
1451
+ }
1452
+ head.append(columns);
1453
+ const body = node('tbody');
1454
+ body.setAttribute('translate', 'no');
1455
+ for (const row of evidence.table.rows) {
1456
+ const cells = node('tr');
1457
+ for (const value of row) {
1458
+ const cell = node('td');
1459
+ cell.textContent = String(value);
1460
+ cells.append(cell);
1461
+ }
1462
+ body.append(cells);
1463
+ }
1464
+ table.append(caption, head, body);
1465
+ tableHost.append(table);
1466
+ const routes = node('pre');
1467
+ routes.textContent = evidence.packet.routesText;
1468
+ routes.setAttribute('translate', 'no');
1469
+ const recommendation = node('pre');
1470
+ recommendation.textContent = evidence.packet.recommendationText;
1471
+ recommendation.setAttribute('translate', 'no');
1472
+ section.append(tableHost, node('h4', 'job.checkpointRoutes'), routes,
1473
+ node('h4', 'job.checkpointRecommendation'), recommendation);
1474
+ fields.append(section, node('p', 'job.checkpointRouteMapping'));
1475
+ }
1650
1476
  const outcome = selectValues(['', 'pass', 'fail'], ['Pending', 'Pass', 'job.fail']);
1651
1477
  outcome.required = true;
1652
1478
  outcome.name = 'outcome';
1653
1479
  fields.append(outcome);
1654
- read = () => ({ checkpointId: subject.checkpointId, outcome: outcome.value as 'pass' | 'fail', words: note.value });
1480
+ read = () => ({ checkpointId: subject.checkpointId, outcome: outcome.value as 'pass' | 'fail', words: commentWords() });
1655
1481
  submitKey = 'job.saveCheckpoint';
1656
1482
  }
1657
- else if (subject.kind === 'parts-verdict') {
1658
- if (!prepared.parts)
1659
- throw new Error('JOB_ASK_INVALID');
1660
- const verdict = selectValues(['pending', 'approved', 'changes-requested'], ['Pending', 'Approved', 'Changes requested']);
1661
- verdict.name = 'verdict';
1662
- fields.append(verdict);
1663
- const parts = prepared.parts.items.map(part => {
1664
- const group = node('fieldset');
1665
- const legend = node('legend');
1666
- legend.textContent = part.name;
1667
- group.append(legend);
1668
- const partOutcome = selectValues(['pending', 'clean', 'flagged'], ['Pending', 'Clean', 'Flagged']);
1669
- const meshOutcome = selectValues(['pending', 'clean', 'flagged'], ['Pending', 'Clean', 'Flagged']);
1670
- partOutcome.name = 'parts.' + part.name + '.outcome';
1671
- meshOutcome.name = 'mesh.' + part.name + '.outcome';
1672
- group.append(inputLabel('Parts', partOutcome));
1673
- const partNote = textArea(group, 'Note', 'parts.' + part.name + '.note');
1674
- group.append(inputLabel('Mesh', meshOutcome));
1675
- const meshNote = textArea(group, 'Note', 'mesh.' + part.name + '.note');
1676
- fields.append(group);
1677
- return { partId: part.name, partOutcome, meshOutcome, partNote, meshNote };
1678
- });
1679
- read = () => ({ verdict: verdict.value as 'pending' | 'approved' | 'changes-requested', words: note.value,
1680
- parts: parts.map(part => ({ partId: part.partId,
1681
- part: { outcome: part.partOutcome.value as 'pending' | 'clean' | 'flagged', note: part.partNote.value },
1682
- mesh: { outcome: part.meshOutcome.value as 'pending' | 'clean' | 'flagged', note: part.meshNote.value } })) });
1683
- submitKey = 'job.savePartsVerdict';
1684
- }
1685
- else if (subject.kind === 'review-verdict') {
1686
- const verdict = selectValues(['pending', 'approved', 'changes-requested'], ['Pending', 'Approved', 'Changes requested']);
1687
- verdict.name = 'verdict';
1688
- fields.append(verdict);
1689
- const stage = subject.stage;
1690
- if (stage === 'image-review') {
1691
- const source = ask.source;
1692
- if (source.subject !== 'image-set') throw new Error('JOB_ACT_SOURCE_STALE');
1693
- const imageNotes = source.imageSet.images.map((image, index) => {
1694
- const group = node('fieldset');
1695
- const name = node('legend');
1696
- name.textContent = image.name;
1697
- group.append(name);
1698
- fields.append(group);
1699
- return {name: image.name, input: textArea(group, 'job.imageNote', 'image-note-' + index)};
1700
- });
1701
- read = () => {
1702
- const notes = imageNotes.filter(note => note.input.value !== '')
1703
- .map(note => ({name: note.name, words: note.input.value}));
1704
- return {stage, verdict: verdict.value as 'pending' | 'approved' | 'changes-requested', words: note.value,
1705
- ...(notes.length ? {imageNotes: notes} : {})};
1706
- };
1707
- } else {
1708
- read = () => ({ stage, verdict: verdict.value as 'pending' | 'approved' | 'changes-requested', words: note.value });
1709
- }
1710
- }
1483
+ else if(subject.kind==='parts-verdict')throw new Error('JOB_ACT_KIND_DISABLED');
1711
1484
  else if (subject.kind === 'signoff') {
1712
- const stage = node('p');
1713
- stage.textContent = subject.stage;
1714
- fields.append(stage);
1715
- read = () => ({ stage: subject.stage, decision: 'approved', words: note.value });
1485
+ fields.title = subject.stage;
1486
+ if (ask.source.plan) fields.append(planTextList(ask.source.plan, prepared.metadata.planText));
1487
+ read = () => ({ stage: subject.stage, decision: 'approved', words: commentWords() });
1716
1488
  submitKey = 'job.signoff';
1717
1489
  }
1718
1490
  else if (subject.kind === 'reopen') {
@@ -1725,46 +1497,53 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1725
1497
  ) {
1726
1498
  throw new Error('JOB_ASK_INVALID');
1727
1499
  }
1728
- const stage = node('p');
1729
- stage.textContent = subject.stage;
1730
- fields.append(stage);
1731
- read = () => ({ stage: subject.stage, words: note.value });
1500
+ fields.title = subject.stage;
1501
+ read = () => ({ stage: subject.stage, words: commentWords() });
1732
1502
  submitKey = 'job.reopen';
1733
1503
  }
1734
1504
  else {
1735
1505
  throw new Error('JOB_ACT_KIND_DISABLED');
1736
1506
  }
1737
- const submit = node('button', submitKey);
1507
+ const submit = interviewForm?.submit??node('button', submitKey);
1738
1508
  submit.type = 'submit';
1739
1509
  fields.append(submit);
1740
- const status = node('p');
1510
+ const status = interviewForm?.status??node('p');
1741
1511
  status.setAttribute('role', 'status');
1742
1512
  form.append(status);
1743
1513
  const entry: JobForm = { form, fieldset: fields, read, submissionId: crypto.randomUUID(), dirty: false,
1744
- submitting: false, rigSubmission: createJobRigSubmission() };
1514
+ submitting: false, ...(disposeInterview?{dispose:disposeInterview}:{}) };
1515
+ if(disposeInterview)form.addEventListener('job-form-dispose',disposeInterview);
1745
1516
  try {
1746
- const saved = JSON.parse(localStorage.getItem(localDraftKey(prepared.display)) ?? 'null');
1517
+ const saved = JSON.parse(draftStorage().getItem(localDraftKey(prepared.display)) ?? 'null');
1747
1518
  if (saved?.publicationId === prepared.display.publication.publicationId &&
1748
1519
  saved?.sourceHash === prepared.display.publication.source.sourceHash) {
1520
+ assertJobAskSource({...ask, source: saved.source}, prepared.display);
1749
1521
  const original = saved.forms?.find((item: {
1750
1522
  askId: string;
1751
1523
  }) => item.askId === ask.askId);
1524
+ if(commentOnly&&typeof original?.value?.words==='string'&&original.value.words.length<=10000)retainedCommentWords=original.value.words;
1752
1525
  for (const input of form.querySelectorAll<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>('input[name],textarea[name],select[name]')) {
1753
1526
  const restored = original?.controls?.find((item: {
1754
1527
  name: string;
1755
1528
  value: string;
1756
1529
  }) => item.name === input.name);
1757
1530
  if (restored && typeof restored.value === 'string') {
1758
- input.value = restored.value;
1759
- if (input instanceof HTMLSelectElement)
1760
- input.dispatchEvent(new Event('change'));
1531
+ if(input instanceof HTMLInputElement&&input.type==='radio'){
1532
+ input.checked=input.value===restored.value;
1533
+ if(input.checked)input.dispatchEvent(new Event('change'));
1534
+ }else{
1535
+ input.value = restored.value;
1536
+ if (input instanceof HTMLSelectElement)input.dispatchEvent(new Event('change'));
1537
+ }
1761
1538
  }
1762
1539
  }
1763
1540
  entry.dirty = !!original;
1541
+ if(subject.kind==='interview-picks')form.dispatchEvent(new Event('change'));
1764
1542
  }
1765
1543
  }
1766
1544
  catch { /* Invalid or unavailable local drafts grant no submission authority. */ }
1767
- form.oninput = () => { entry.dirty = true; entry.submissionId = crypto.randomUUID(); entry.rigSubmission.reset(); saveDraft(); };
1545
+ form.oninput = () => { entry.dirty = true; entry.submissionId = crypto.randomUUID(); saveDraft(); };
1546
+ let attemptedValue:string|undefined;
1768
1547
  form.onsubmit = async (event) => {
1769
1548
  event.preventDefault();
1770
1549
  const state = window.state();
@@ -1772,25 +1551,26 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1772
1551
  if (!receipt || state.preparing || state.closed || !access.capability || !form.reportValidity())
1773
1552
  return;
1774
1553
  try {
1554
+ const value=read(),key=JSON.stringify(value);
1555
+ if(commentOnly&&attemptedValue!==undefined&&attemptedValue!==key)entry.submissionId=crypto.randomUUID();
1556
+ attemptedValue=key;
1775
1557
  const input = { kind: subject.kind, publicationId: ask.publicationId,
1776
1558
  askId: ask.askId, pageId, displayedNonce: receipt.displayedNonce,
1777
- expectedGeneration: state.generation, submissionId: entry.submissionId, value: read() } as UISubmissionV3;
1559
+ expectedGeneration: state.generation, submissionId: entry.submissionId, value } as UISubmissionV3;
1778
1560
  const activeAsk = state.pending.find(item => item.askId === ask.askId);
1779
1561
  if (!activeAsk) throw new Error('JOB_ASK_INVALID');
1780
- const pending = subject.kind === 'review-verdict' && subject.stage === 'rig-review'
1781
- ? entry.rigSubmission.prepare(input as JobUISubmission, () => copyRigVerdict(activeAsk, prepared)) : Promise.resolve(input);
1782
1562
  entry.submitting = true;
1783
1563
  fields.disabled = true;
1784
- const frozen = await pending;
1564
+ const frozen = await Promise.resolve(input);
1785
1565
  if (entry.submissionId !== frozen.submissionId) throw new Error('JOB_STILL_BINDING_MISMATCH');
1786
1566
  const result = await window.submit(frozen);
1787
1567
  if (!result.ok)
1788
1568
  throw new Error(result.error.code);
1789
1569
  entry.submitting = false;
1790
1570
  entry.dirty = false;
1791
- entry.rigSubmission.reset();
1792
1571
  status.dataset.jobText = 'job.saved';
1793
1572
  status.textContent = t('job.saved');
1573
+ if(subject.kind==='interview-picks'){form.dataset.interviewAnswered='true';form.dispatchEvent(new Event('change'));}
1794
1574
  saveDraft();
1795
1575
  }
1796
1576
  catch (error) {
@@ -1803,719 +1583,113 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1803
1583
  };
1804
1584
  return entry;
1805
1585
  }
1806
- function updateForms(state: JobWindowState): void {
1807
- if (!current)
1808
- return;
1809
- const host = workspace.querySelector<HTMLElement>('[data-job-forms]');
1810
- if (!host)
1811
- return;
1812
- for (const ask of state.pending) {
1813
- if (ask.publicationId !== current.display.publication.publicationId)
1814
- continue;
1815
- let entry = forms.get(ask.askId);
1816
- if (!entry && ask.status === 'pending') {
1817
- try {
1818
- entry = formFor(ask, current);
1819
- forms.set(ask.askId, entry);
1820
- host.append(entry.form);
1821
- }
1822
- catch (error) {
1823
- const refusal = node('p');
1824
- refusal.textContent = jobWindowRefusal(error, 'JOB_ASK_INVALID');
1825
- host.append(refusal);
1826
- }
1827
- }
1828
- if (entry)
1829
- entry.fieldset.disabled = entry.submitting || ask.status !== 'pending' || state.closed || !state.receipt || !access.capability;
1830
- }
1831
- }
1832
- function build(prepared: JobPreparedInspection): HTMLElement {
1833
- const root = node('div');
1834
- root.className = 'job-inspection';
1835
- const sidebar = node('section');
1836
- sidebar.className = 'job-sidebar';
1837
- const identity = node('p');
1838
- identity.className = 'job-source';
1839
- identity.textContent = prepared.display.publication.label + '\n' + prepared.display.publication.source.sourceHash;
1840
- sidebar.append(identity);
1841
- const binding = node('details');
1842
- const bindingTitle = node('summary', 'job.binding');
1843
- const sourceBinding = node('pre');
1844
- sourceBinding.className = 'job-source';
1845
- sourceBinding.textContent = JSON.stringify(prepared.display.publication.source, null, 2);
1846
- binding.append(bindingTitle, sourceBinding);
1847
- sidebar.append(binding);
1848
- const parts = node('select');
1849
- parts.id = 'job-part';
1850
- parts.disabled = !prepared.metadata.manifest?.model || prepared.metadata.feedbackCatalog.slots === null;
1851
- const whole = node('option', 'job.wholeRig');
1852
- whole.value = '';
1853
- parts.append(whole);
1854
- for (const slot of prepared.metadata.feedbackCatalog.slots ?? []) {
1855
- const option = node('option');
1856
- option.value = slot;
1857
- option.textContent = slot;
1858
- parts.append(option);
1859
- }
1860
- parts.onchange = () => { selectedPart = parts.value; selectPart(); };
1861
- sidebar.append(inputLabel('Parts', parts));
1862
- const solo = node('input');
1863
- solo.type = 'checkbox';
1864
- solo.id = 'job-solo';
1865
- solo.onchange = () => { partMode = solo.checked ? 'solo' : 'context'; selectPart(); };
1866
- sidebar.append(inputLabel('Solo', solo));
1867
- const observation = node('pre');
1868
- observation.id = 'job-part-observation';
1869
- observation.className = 'job-source';
1870
- sidebar.append(observation);
1871
- const referenceSelect = node('select');
1872
- referenceSelect.id = 'job-reference';
1873
- for (const reference of prepared.references) {
1874
- const option = node('option');
1875
- option.value = reference.id;
1876
- option.textContent = reference.label;
1877
- referenceSelect.append(option);
1878
- }
1879
- referenceSelect.onchange = () => {
1880
- const next = prepared.references.find(item => item.id === referenceSelect.value);
1881
- if (current === prepared && next) void referenceSelection.select(next);
1882
- };
1883
- sidebar.append(inputLabel('Reference', referenceSelect));
1884
- const images = node('div');
1885
- images.className = 'job-part-images';
1886
- for (const [name, image] of prepared.partImages) {
1887
- const label = node('label');
1888
- const title = node('span');
1889
- title.textContent = name;
1890
- label.append(title, image);
1891
- images.append(label);
1892
- }
1893
- sidebar.append(images);
1894
- const stage = node('section');
1895
- stage.className = 'job-stage';
1896
- const controls = node('div');
1897
- controls.className = 'viewbar';
1898
- for (const [id, key] of [['zoom-in', 'job.zoomIn'], ['zoom-out', 'job.zoomOut'], ['fit', 'Fit']]) {
1899
- const button = node('button', key);
1900
- button.id = id!;
1901
- button.type = 'button';
1902
- controls.append(button);
1903
- }
1904
- const sync = node('input');
1905
- sync.id = 'camera-sync';
1906
- sync.type = 'checkbox';
1907
- controls.append(inputLabel('job.cameraSync', sync));
1908
- const zoom = node('span');
1909
- zoom.id = 'zoom-value';
1910
- controls.append(zoom);
1911
- const pair = node('div');
1912
- pair.id = 'stage-layout';
1913
- mountViewportPair(pair);
1914
- for (const id of ['rig-overlay', 'idle-handles', 'rig-fields-stage'])
1915
- pair.querySelector('#' + id)?.remove();
1916
- for (const [id, key] of [['reference-label', 'Reference'], ['rig-label', 'Generated rig · read only'],
1917
- ['reference-empty', 'No reference supplied.'], ['rig-empty', 'No compiled model supplied.']]) {
1918
- const label = pair.querySelector<HTMLElement>('#' + id);
1919
- if (label) {
1920
- label.dataset.jobText = key;
1921
- label.textContent = t(key!);
1922
- }
1923
- }
1924
- pair.querySelector('#reference-pane')?.setAttribute('aria-label', t('Reference'));
1925
- pair.querySelector('#rig-pane')?.setAttribute('aria-label', t('Rig'));
1926
- pair.querySelector('#rig-root')!.replaceWith(prepared.rigRoot);
1927
- const transport = node('div');
1928
- transport.className = 'job-transport';
1929
- const clips = node('select');
1930
- clips.id = 'job-animation';
1931
- const setup = node('option', 'Setup');
1932
- setup.value = '';
1933
- clips.append(setup);
1934
- for (const clip of prepared.assets?.animations ?? []) {
1935
- const option = node('option');
1936
- option.value = clip.name;
1937
- option.textContent = clip.name;
1938
- clips.append(option);
1939
- }
1940
- clips.onchange = () => { stopPlayback(); animation = clips.value; time = 0; pose(); };
1941
- const playButton = node('button', 'Play');
1942
- playButton.id = 'job-play';
1943
- playButton.type = 'button';
1944
- playButton.setAttribute('aria-pressed', 'false');
1945
- playButton.disabled = true;
1946
- playButton.onclick = () => {
1947
- const clip = current?.assets?.animations.find(item => item.name === animation);
1948
- if (!current?.player || !animation || !clip || !(clip.duration > 0)) {
1949
- stopPlayback();
1950
- return;
1951
- }
1952
- if (playing) {
1953
- stopPlayback();
1954
- presentCurrentFrame(current);
1955
- return;
1956
- }
1957
- if (current.player.composed) current.setupPose(false);
1958
- if (!loop && time >= clip.duration) {
1959
- time = 0;
1960
- current.player.play(animation, { loop });
1961
- } else if (current.player.current !== animation) {
1962
- current.player.play(animation, { loop });
1963
- if (time > 0) current.player.seek(time);
1964
- } else {
1965
- current.player.resume();
1966
- }
1967
- playing = true;
1968
- playbackCarry = 0;
1969
- lastFrameTime = 0;
1970
- lastRunningSaveMs = null;
1971
- const clockInput = workspace.querySelector<HTMLInputElement>('#job-time');
1972
- if (clockInput) clockInput.value = playbackTimeLabel(clip.duration, current.player.time);
1973
- syncTransportControls();
1974
- presentCurrentFrame(current);
1975
- if (hubVisible) armPlayback(current, current.player);
1976
- };
1977
- const loopInput = node('input');
1978
- loopInput.id = 'job-loop';
1979
- loopInput.type = 'checkbox';
1980
- loopInput.checked = loop;
1981
- loopInput.onchange = () => {
1982
- loop = loopInput.checked;
1983
- playbackCarry = 0;
1984
- lastFrameTime = 0;
1985
- const clip = current?.assets?.animations.find(item => item.name === animation);
1986
- if (current?.player && animation && clip) {
1987
- if (current.player.composed) current.setupPose(false);
1988
- current.player.play(animation, { loop });
1989
- if (time > 0) current.player.seek(time);
1990
- const activeEntry = current.player.entry(0);
1991
- if (!activeEntry || activeEntry.animation !== animation || activeEntry.loop !== loop ||
1992
- !Number.isFinite(activeEntry.animationTime) || activeEntry.animationTime < 0 ||
1993
- activeEntry.animationTime > activeEntry.duration) {
1994
- stopPlayback(current.player);
1995
- return;
1996
- }
1997
- time = activeEntry.animationTime;
1998
- const clockInput = workspace.querySelector<HTMLInputElement>('#job-time');
1999
- if (clockInput) clockInput.value = playbackTimeLabel(clip.duration, activeEntry.trackTime);
2000
- if (!playing) current.player.pause();
2001
- syncTransportControls();
2002
- presentCurrentFrame(current);
2003
- saveWindowState();
2004
- if (playing && hubVisible) armPlayback(current, current.player);
2005
- } else {
2006
- syncTransportControls();
2007
- saveWindowState();
2008
- }
2009
- };
2010
- const clock = node('input');
2011
- clock.id = 'job-time';
2012
- clock.type = 'number';
2013
- clock.min = '0';
2014
- clock.step = '0.001';
2015
- clock.oninput = () => {
2016
- if (!playing) return;
2017
- stopPlayback();
2018
- if (current) presentCurrentFrame(current);
2019
- };
2020
- clock.onchange = () => {
2021
- const value = Number(clock.value);
2022
- const duration = current?.assets?.animations.find(clip => clip.name === animation)?.duration;
2023
- if (!Number.isFinite(value) || value < 0 || duration !== undefined && value > duration) {
2024
- clock.value = String(time);
2025
- notice.textContent = t('KEY_TIME_OUT_OF_DOMAIN');
2026
- return;
2027
- }
2028
- stopPlayback();
2029
- time = value;
2030
- pose();
2031
- };
2032
- const panels = selectValues(['1', '2', '3', '4'], ['1 Parts + mesh', '2 Interview', '3 Rig + animation', '4 Direction']);
2033
- panels.id = 'job-panel';
2034
- panels.onchange = () => { panel = panels.value; showPanel(); };
2035
- transport.append(clips, playButton, inputLabel('Repeat', loopInput), inputLabel('job.time', clock), panels);
2036
- const numeric = node('pre');
2037
- numeric.id = 'view-coordinates';
2038
- numeric.hidden = true;
2039
- const coordinates = node('span');
2040
- coordinates.id = 'coordinates';
2041
- coordinates.hidden = true;
2042
- stage.append(controls, pair, transport, numeric, coordinates);
2043
- const source = prepared.display.publication.source;
2044
- if (source.subject === 'image-set') {
2045
- const heading = node('h2', 'job.imageSetTitle');
2046
- const digest = node('p');
2047
- digest.className = 'job-source';
2048
- digest.style.overflowWrap = 'anywhere';
2049
- const digestLabel = node('span', 'job.imageSetDigest');
2050
- const digestValue = node('code');
2051
- digestValue.textContent = source.imageSetDigest;
2052
- digest.append(digestLabel, document.createTextNode(' '), digestValue);
2053
- const gallery = node('section');
2054
- gallery.dataset.jobImageSet = '';
2055
- gallery.style.display = 'grid';
2056
- gallery.style.gridAutoFlow = 'column';
2057
- gallery.style.gridAutoColumns = 'minmax(180px, 1fr)';
2058
- gallery.style.gap = '16px';
2059
- gallery.style.overflow = 'auto';
2060
- gallery.style.minHeight = '0';
2061
- gallery.style.flex = '1';
2062
- for (const [index, image] of source.imageSet.images.entries()) {
2063
- const element = prepared.imageSetImages?.[index];
2064
- if (!element) throw new Error('JOB_VISUAL_UNAVAILABLE');
2065
- const figure = node('figure');
2066
- figure.style.margin = '0';
2067
- figure.style.minWidth = '0';
2068
- figure.dataset.imageName = image.name;
2069
- const name = node('h3');
2070
- name.textContent = image.name;
2071
- name.style.overflowWrap = 'anywhere';
2072
- const role = node('p', 'job.imageRole.' + image.role);
2073
- const hash = node('code');
2074
- hash.className = 'job-source';
2075
- hash.style.display = 'block';
2076
- hash.style.overflowWrap = 'anywhere';
2077
- hash.textContent = image.sha256;
2078
- element.style.width = '100%';
2079
- element.style.height = 'auto';
2080
- element.style.maxHeight = '70vh';
2081
- element.style.objectFit = 'contain';
2082
- figure.append(name, role, element, hash);
2083
- if (source.duplicateHashes.some(group => group.names.includes(image.name)))
2084
- figure.append(node('p', 'job.identicalImages'));
2085
- gallery.append(figure);
2086
- }
2087
- stage.prepend(heading, digest, gallery);
2088
- controls.hidden = pair.hidden = transport.hidden = true;
2089
- controls.style.display = pair.style.display = transport.style.display = 'none';
2090
- for (const child of sidebar.children) {
2091
- if (child instanceof HTMLElement && child !== identity && child !== binding) child.hidden = true;
2092
- }
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
- }
2124
- const formsHost = node('section');
2125
- formsHost.className = 'job-forms';
2126
- formsHost.dataset.jobForms = '';
2127
- const heading = node('h2', 'job.pending');
2128
- formsHost.append(heading);
2129
- const direction = node('pre');
2130
- direction.className = 'job-direction';
2131
- direction.dataset.jobDirection = '';
2132
- if (prepared.metadata.direction)
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
- }
2167
- const history = node('div');
2168
- history.className = 'job-history';
2169
- history.dataset.jobHistory = '';
2170
- formsHost.append(direction, interviewDiagnostics, history);
2171
- root.append(sidebar, stage, formsHost);
2172
- return root;
2173
- }
2174
- function selectPart(): void {
2175
- if (!current?.inspection)
2176
- return;
2177
- drawn.delete(current);
2178
- current.rigPresentation = undefined;
2179
- current.inspection.select(selectedPart ? { side: 'single', slot: selectedPart, mode: partMode } : null);
2180
- rememberDraw();
2181
- setText('job-part-observation', selectedPart ? JSON.stringify(current.inspection.observation(), null, 2) : '');
2182
- viewport.renderCameraControls();
2183
- }
2184
- function showReference(): void {
2185
- const value = reference();
2186
- el('reference-content').replaceChildren(...(value ? [value.element] : []));
2187
- el('reference-empty').hidden = !!value;
2188
- }
2189
- function showPanel(): void {
2190
- const direction = workspace.querySelector<HTMLElement>('[data-job-direction]');
2191
- if (direction)
2192
- direction.hidden = panel !== '4';
2193
- for (const [askId, entry] of forms) {
2194
- const ask = window.state().pending.find(item => item.askId === askId);
2195
- const currentSubject = current?.display.publication.source.subject;
2196
- entry.form.hidden = currentSubject !== 'image-set' &&
2197
- currentSubject !== 'option-set' && currentSubject !== 'plan' &&
2198
- panel === '2' && ask?.subject.kind !== 'interview-picks';
1586
+ export {formFor};
1587
+
1588
+ // Keep the form dependencies available through the existing preparation seam as well as named exports.
1589
+ prepareJobForms.formFor = formFor;
1590
+ prepareJobForms.helpers = createJobFormHelpers;
1591
+
1592
+ /** The original source-bound draft storage, shared by the legacy and single-screen hosts. */
1593
+ /** Joined inspection uses real API rows and the same answer builder; no job identities or acts are synthesized. */
1594
+ export async function joinedInterviewForms(access:InstanceAccess,present:(forms:readonly HTMLElement[])=>void):Promise<()=>void> {
1595
+ const request=async(path:string,body?:unknown)=>{
1596
+ const response=await fetch(access.route(path),body?{method:'POST',headers:access.headers({'Content-Type':'application/json'}),body:JSON.stringify(body)}:undefined);
1597
+ const value=await response.json();if(!response.ok)throw new Error(value.error);return value;
1598
+ };
1599
+ const data=await request('/api/interview') as {questions:InterviewDisplayQuestion[];diagnostics?:import('../src/interview-project.ts').InterviewDiagnostic[];historical?:import('../src/interview-project.ts').HistoricalInterview[]};
1600
+ const forms=new Map<number,ReturnType<typeof createInterviewForm>>();
1601
+ let selected=Math.max(0,data.questions.findIndex(question=>question.editable&&!question.saved)),disposed=false;
1602
+ const node:JobFormNode=(tag,key)=>{const item=document.createElement(tag);if(key){item.dataset.jobText=key;item.textContent=t(key);}return item;};
1603
+ const show=(index:number)=>{
1604
+ if(disposed)return;selected=index;
1605
+ const question=data.questions[index];
1606
+ if(!question){const empty=node('section');empty.append(node('p','interview.empty'),interviewRecords(data.diagnostics,data.historical));present([empty]);return;}
1607
+ let entry=forms.get(index);
1608
+ if(!entry){
1609
+ entry=createInterviewForm({question,id:'joined-interview-'+question.ref.sha256,node,
1610
+ images:question.images.map(image=>({name:image.name,src:access.route(image.url)})),
1611
+ questions:()=>data.questions.map((item,i)=>({label:item.set.question+' · '+item.set.id+(item.editable?'':' · '+t('interview.history')),answered:forms.get(i)?.form.dataset.interviewAnswered==='true'||Boolean(item.saved||item.answer)})),
1612
+ selected:index,onSelect:show,diagnostics:data.diagnostics,historical:data.historical});
1613
+ const answer=entry;
1614
+ entry.fieldset.disabled=!question.editable||!access.capability;
1615
+ entry.form.onsubmit=async event=>{
1616
+ event.preventDefault();if(!question.editable||!access.capability||entry!.fieldset.disabled||!entry!.form.reportValidity())return;
1617
+ answer.fieldset.disabled=true;
1618
+ try{
1619
+ const value=answer.read(),picks=value.selections.map(selection=>({ask:selection.itemId,option_id:selection.optionId,...(selection.otherText!==null?{other_text:selection.otherText}:{})}));
1620
+ const record=interviewPicksRecord(question.ref,picks,answer.retainedNote,new Date().toISOString());
1621
+ await request('/api/interview/picks',record);
1622
+ question.saved=record;answer.form.dataset.interviewAnswered='true';answer.status.dataset.jobText='interview.saved';answer.status.textContent=t('interview.saved');answer.form.dispatchEvent(new Event('change'));
1623
+ }catch(error){const code=error instanceof Error?error.message.split(':')[0]:'';answer.status.dataset.jobText=interviewErrors[code]??'interview.failed';answer.status.textContent=t(answer.status.dataset.jobText);}
1624
+ finally{answer.fieldset.disabled=!question.editable||!access.capability;}
1625
+ };
1626
+ forms.set(index,entry);
2199
1627
  }
2200
- saveWindowState();
1628
+ entry.form.dispatchEvent(new Event('change'));present([entry.form]);
1629
+ };
1630
+ const localize=()=>{for(const entry of forms.values())entry.localize();};
1631
+ try{show(selected);}catch(error){for(const entry of forms.values())entry.dispose();throw error;}
1632
+ const off=onLanguageChange(localize);
1633
+ return ()=>{disposed=true;off();for(const entry of forms.values())entry.dispose();forms.clear();};
1634
+ }
1635
+
1636
+ export function createJobFormDrafts(options:{jobId:string;current():JobPreparedInspection|null;forms():ReadonlyMap<string,JobForm>;storage():Pick<Storage,'setItem'>}) {
1637
+ function localDraftKey(display: DisplayPublicationV3): string {
1638
+ return 'rig-review-job-draft/1:' + options.jobId + ':' + display.publication.publicationId + ':' + display.publication.source.sourceHash;
2201
1639
  }
2202
- function pose(seekReference = true): void {
1640
+ function saveDraft(): void {
1641
+ const current=options.current(),forms=options.forms();
2203
1642
  if (!current)
2204
1643
  return;
2205
- const clip = current.assets?.animations.find(item => item.name === animation);
2206
- const clock = el<HTMLInputElement>('job-time');
2207
- clock.value = String(time);
2208
- if (animation && (!clip || time > clip.duration)) {
2209
- notice.textContent = t('KEY_TIME_OUT_OF_DOMAIN');
2210
- return;
2211
- }
2212
- if (!animation && current.player?.current) current.setupPose();
2213
- // Setup uses an empty composed track. Animation seek needs a fresh single track.
2214
- if (animation && current.player?.composed) current.setupPose(false);
2215
- if (current.player) {
2216
- drawn.delete(current);
2217
- current.rigPresentation = undefined;
2218
- if (animation && (current.player.current !== animation || current.player.entry(0)?.loop !== loop))
2219
- current.player.play(animation, { loop });
2220
- if (animation) {
2221
- const seekAtLoopEnd = loop && time === clip?.duration;
2222
- current.player.seek(time);
2223
- const activeEntry = current.player.entry(0);
2224
- if (!activeEntry || activeEntry.animation !== animation || activeEntry.loop !== loop ||
2225
- !Number.isFinite(activeEntry.animationTime) || activeEntry.animationTime < 0 ||
2226
- activeEntry.animationTime > activeEntry.duration) {
2227
- current.player.pause();
2228
- notice.textContent = t('JOB_VISUAL_UNAVAILABLE');
2229
- return;
2230
- }
2231
- time = activeEntry.animationTime;
2232
- clock.value = seekAtLoopEnd ? '0' : String(time);
2233
- }
2234
- current.player.pause();
2235
- drawInspection(current);
2236
- current.inspection?.select(selectedPart ? { side: 'single', slot: selectedPart, mode: partMode } : null);
2237
- setText('job-part-observation', selectedPart ? JSON.stringify(current.inspection?.observation(), null, 2) : '');
2238
- }
2239
- syncTransportControls();
2240
- if (seekReference) {
2241
- const value = reference();
2242
- const owner = current;
2243
- const at = time;
2244
- void value?.seek(at, abort.signal).catch(error => {
2245
- if (current === owner && reference() === value && time === at)
2246
- notice.textContent = jobWindowRefusal(error, 'JOB_VISUAL_UNAVAILABLE');
2247
- });
1644
+ try {
1645
+ options.storage().setItem(localDraftKey(current.display), JSON.stringify({
1646
+ publicationId: current.display.publication.publicationId,
1647
+ sourceHash: current.display.publication.source.sourceHash,
1648
+ source: current.display.publication.source,
1649
+ label: current.display.publication.label,
1650
+ forms: [...forms].filter(([, item]) => item.dirty).map(([askId, item]) => ({
1651
+ askId, value: item.read(),
1652
+ controls: [...item.form.querySelectorAll<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>('input[name],textarea[name],select[name]')]
1653
+ .filter(input=>!(input instanceof HTMLInputElement&&input.type==='radio')||input.checked)
1654
+ .map(input => ({ name: input.name, value: input.value })),
1655
+ })),
1656
+ }));
2248
1657
  }
2249
- viewport.fitCamera();
2250
- }
2251
- function hubBinding(): JobHubBinding {
2252
- return {incarnation: hubIncarnation!, jobId: access.jobId,
2253
- publicationId: current?.display.publication.publicationId ?? null,
2254
- sourceHash: current?.display.publication.source.sourceHash ?? null};
2255
- }
2256
- function pauseHiddenHubFrame(): void {
2257
- if (hubVisible) return;
2258
- stopPlayback();
2259
- for (const video of workspace.querySelectorAll('video')) video.pause();
2260
- }
2261
- function announceHubFrame(): void {
2262
- if (hubIncarnation) globalThis.parent.postMessage({...hubBinding(), schema: JOB_HUB_READY}, location.origin);
1658
+ catch { /* The in-memory retained draft remains source-bound. */ }
2263
1659
  }
2264
- const window = createJobWindow({ jobId: access.jobId, pageId, transport,
2265
- previousDisplayed, initialRetainedDrafts,
2266
- adapter: {
2267
- async prepare(display, signal): Promise<PreparedWindow> {
2268
- const inspection = await prepareJobInspection(display, signal);
2269
- try {
2270
- const element = build(inspection);
2271
- const preparedForms = prepareJobForms(display, window.state().pending, ask => formFor(ask, inspection));
2272
- return Object.assign(inspection, { element, forms: preparedForms });
2273
- }
2274
- catch (error) {
2275
- inspection.dispose();
2276
- throw error;
2277
- }
2278
- },
2279
- captureDraft() { saveDraft(); const dirty = [...forms].filter(([, item]) => item.dirty); return dirty.length ? dirty.map(([askId, item]) => ({ askId, value: item.read() })) : null; },
2280
- commit(prepared, display) {
2281
- // Pending asks can arrive while assets load. Finish their forms before the visible replacement.
2282
- const nextForms = prepareJobForms(display, window.state().pending,
2283
- ask => prepared.forms.get(ask.askId) ?? formFor(ask, prepared));
2284
- const root = prepared.element;
2285
- const formHost = root.querySelector<HTMLElement>('[data-job-forms]');
2286
- if (!formHost) throw new Error('JOB_WINDOW_ELEMENT_MISSING');
2287
- for (const entry of nextForms.values()) formHost.append(entry.form);
2288
- referenceSelection.cancel();
2289
- const previous = current;
2290
- stopPlayback(previous?.player);
2291
- const previousElement = currentElement;
2292
- const previousForms = new Map(forms);
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);
2300
- if (animation && !prepared.assets?.animations.some(item => item.name === animation && time <= item.duration)) {
2301
- animation = '';
2302
- time = 0;
2303
- compatibilityNotice = true;
2304
- }
2305
- if (selectedPart && !(prepared.metadata.feedbackCatalog.slots ?? []).includes(selectedPart)) {
2306
- selectedPart = '';
2307
- compatibilityNotice = true;
2308
- }
2309
- if (!prepared.references.some(item => item.id === selectedReference))
2310
- selectedReference = prepared.references[0]?.id ?? '';
2311
- let nextUnbind: (() => void) | null = null;
2312
- let nextResize: ResizeObserver | null = null;
2313
- const rollback = () => {
2314
- stopPlayback(prepared.player);
2315
- nextUnbind?.();
2316
- nextResize?.disconnect();
2317
- current = previous;
2318
- currentElement = previousElement;
2319
- animation = navigation.animation;
2320
- time = navigation.time;
2321
- loop = navigation.loop;
2322
- selectedPart = navigation.selectedPart;
2323
- partMode = navigation.partMode;
2324
- selectedReference = navigation.selectedReference;
2325
- panel = navigation.panel;
2326
- forms.clear();
2327
- for (const [id, item] of previousForms)
2328
- forms.set(id, item);
2329
- workspace.replaceChildren(...(previousElement ? [previousElement] : []));
2330
- Object.assign(viewportState, navigation.camera);
2331
- if (current) {
2332
- el<HTMLSelectElement>('job-reference').value = selectedReference;
2333
- syncTransportControls();
2334
- viewport.fitCamera();
2335
- }
2336
- };
2337
- try {
2338
- current = prepared;
2339
- currentElement = root;
2340
- forms.clear();
2341
- for (const [id, entry] of nextForms) forms.set(id, entry);
2342
- workspace.replaceChildren(root);
2343
- el<HTMLSelectElement>('job-part').value = selectedPart;
2344
- el<HTMLInputElement>('job-solo').checked = partMode === 'solo';
2345
- el<HTMLSelectElement>('job-reference').value = selectedReference;
2346
- el<HTMLSelectElement>('job-animation').value = animation;
2347
- el<HTMLInputElement>('job-loop').checked = loop;
2348
- el<HTMLSelectElement>('job-panel').value = panel;
2349
- el('rig-empty').hidden = !!prepared.player;
2350
- Object.assign(viewportState, navigation.camera, { cameraRestoring: restoringCamera });
2351
- showReference();
2352
- pose(false);
2353
- if (selectedPart) {
2354
- try {
2355
- if (!navigation.partIdentity || navigation.partIdentity.slot !== selectedPart) {
2356
- throw new Error('PART_IDENTITY_UNAVAILABLE');
2357
- }
2358
- prepared.inspection?.assertIdentity(navigation.partIdentity);
2359
- }
2360
- catch {
2361
- selectedPart = '';
2362
- compatibilityNotice = true;
2363
- el<HTMLSelectElement>('job-part').value = '';
2364
- }
2365
- }
2366
- selectPart();
2367
- viewportState.cameraRestoring = false;
2368
- updateForms(window.state());
2369
- showPanel();
2370
- viewport.bindControls();
2371
- nextUnbind = viewport.bindNavigation();
2372
- nextResize = viewport.observeResize();
2373
- return {
2374
- rollback,
2375
- finalize() {
2376
- restoredPartIdentity = null;
2377
- restoredCamera = null;
2378
- savedWindow = null;
2379
- unbindNavigation?.();
2380
- resize?.disconnect();
2381
- unbindNavigation = nextUnbind;
2382
- resize = nextResize;
2383
- previous?.dispose();
2384
- title.textContent = display.publication.source.package?.id ?? display.publication.label;
2385
- },
2386
- };
2387
- }
2388
- catch (error) {
2389
- rollback();
2390
- throw error;
2391
- }
2392
- },
2393
- async painted(prepared, signal) {
2394
- for (const image of prepared.imageSetImages ?? []) {
2395
- if (!image.isConnected || !image.complete || !image.naturalWidth || !image.naturalHeight)
2396
- throw new Error('JOB_VISUAL_UNAVAILABLE');
2397
- }
2398
- await reference()?.seek(time, signal);
2399
- if (prepared.player) {
2400
- drawInspection(prepared);
2401
- rememberDraw();
2402
- }
2403
- await new Promise<void>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
2404
- if (signal.aborted)
2405
- throw new Error('JOB_PRELOAD_CANCELLED');
2406
- },
2407
- discard(prepared) { prepared.dispose(); },
2408
- changed(state) {
2409
- notice.dataset.failed = String(!!state.error);
2410
- if (state.error)
2411
- notice.textContent = state.displayed && state.error !== 'JOB_WINDOW_CLEANUP_FAILED'
2412
- ? t('job.failed') + ' · ' + jobWindowRefusal(state.error) : jobWindowRefusal(state.error);
2413
- else if (state.closed)
2414
- notice.textContent = t('job.closed');
2415
- else if (state.preparing)
2416
- notice.textContent = t('job.preparing');
2417
- else if (state.displayed) {
2418
- notice.textContent = state.previousLabel
2419
- ? t('job.updated', [state.previousLabel, state.displayed.publication.label]) : state.displayed.publication.label;
2420
- if (compatibilityNotice)
2421
- notice.textContent += ' · ' + t('job.incompatible');
2422
- }
2423
- if (state.closed) {
2424
- const wasPlaying = playing;
2425
- stopPlayback();
2426
- if (wasPlaying && current) presentCurrentFrame(current);
2427
- }
2428
- updateForms(state);
2429
- if (current)
2430
- showPanel();
2431
- const history = workspace.querySelector<HTMLElement>('[data-job-history]');
2432
- if (history) {
2433
- const retained = new Map(state.retainedDrafts.map(draft => [draft.publicationId, draft]));
2434
- try {
2435
- const prefix = 'rig-review-job-draft/1:' + access.jobId + ':';
2436
- for (let index = 0; index < localStorage.length; index++) {
2437
- const key = localStorage.key(index);
2438
- if (!key?.startsWith(prefix))
2439
- continue;
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. */ }
2447
- }
2448
- }
2449
- catch { /* In-memory retained evidence remains available. */ }
2450
- history.textContent = [...retained.values()].map(draft => t('job.retained', [draft.label]) + '\n' + draft.sourceHash + '\n' + JSON.stringify(draft.value, null, 2)).join('\n');
2451
- }
2452
- saveWindowState();
2453
- pauseHiddenHubFrame(); announceHubFrame();
2454
- if (state.receipt && !state.preparing) events?.displayed();
2455
- },
2456
- } });
2457
- const localize = i18n.onLanguageChange(() => {
2458
- for (const element of host.querySelectorAll<HTMLElement>('[data-job-text]'))
2459
- element.textContent = t(element.dataset.jobText!);
2460
- languages.setAttribute('aria-label', t('interview.language'));
2461
- if (current)
2462
- viewport.renderCameraControls();
2463
- window.refresh();
2464
- });
2465
- const hubVisibility = (event: MessageEvent) => {
2466
- if (!hubIncarnation || !jobHubMessageMatches(event, location.origin, globalThis.parent, hubBinding(), 'visibility')) return;
2467
- hubVisible = event.data.visible;
2468
- host.dataset.hubVisible = String(hubVisible);
2469
- events?.visibility(hubVisible);
2470
- if (event.data.language !== i18n.getLanguage()) {
2471
- i18n.setLinkLanguage(null); i18n.setLanguagePreference(event.data.language);
2472
- }
2473
- pauseHiddenHubFrame();
2474
- if (current && !hubVisible) {
2475
- drawn.delete(current);
2476
- current.rigPresentation = undefined;
2477
- }
2478
- if (hubVisible && current?.player) {drawInspection(current); rememberDraw();}
2479
- };
2480
- if (hubIncarnation) {globalThis.addEventListener('message', hubVisibility); announceHubFrame();}
2481
- events = startJobWindowEvents({access, signal: abort.signal, member: !!hubIncarnation,
2482
- event: event => window.event(event),
2483
- refused: error => {notice.textContent = jobWindowRefusal(error, 'JOB_STREAM_FAILED');},
2484
- });
2485
- let resolution: MediaQueryList | undefined;
2486
- const resolutionChanged = () => {
2487
- resolution?.removeEventListener('change', resolutionChanged);
2488
- resolution = globalThis.matchMedia(`(resolution:${globalThis.devicePixelRatio || 1}dppx)`);
2489
- resolution.addEventListener('change', resolutionChanged);
2490
- if (current) {
2491
- drawn.delete(current);
2492
- current.rigPresentation = undefined;
2493
- viewport.fitCamera();
2494
- }
2495
- };
2496
- resolutionChanged();
2497
- const stop = () => {
2498
- stopPlayback();
2499
- resolution?.removeEventListener('change', resolutionChanged);
2500
- globalThis.removeEventListener('message', hubVisibility);
2501
- saveDraft();
2502
- saveWindowState();
2503
- referenceSelection.cancel();
2504
- abort.abort();
2505
- window.stop();
2506
- localize();
2507
- unbindNavigation?.();
2508
- resize?.disconnect();
2509
- current?.dispose();
2510
- };
2511
- globalThis.addEventListener('pagehide', stop, { once: true });
2512
- return () => { globalThis.removeEventListener('pagehide', stop); stop(); };
1660
+ return {localDraftKey,saveDraft};
2513
1661
  }
2514
- if (typeof document !== 'undefined' && document.body?.hasAttribute('data-job-window')) {
2515
- void mountJobSession(document.body).catch(error => {
2516
- const status = document.createElement('p');
2517
- status.setAttribute('role', 'alert');
2518
- status.textContent = jobWindowRefusal(error);
2519
- document.body.append(status);
2520
- });
1662
+ prepareJobForms.drafts=createJobFormDrafts;
1663
+
1664
+ /** Host supported publications through the existing transaction/stream modules before mounting any screen. */
1665
+ export async function mountJobScreen(host:HTMLElement):Promise<()=>void> {
1666
+ let storage:Storage|null=null;try{storage=sessionStorage;}catch{/* Keep the capability in memory. */}
1667
+ const access=jobWindowAccess(location.href,storage,href=>history.replaceState(history.state,'',href)),pageId=crypto.randomUUID(),abort=new AbortController();
1668
+ const language=new URL(location.href).searchParams.get('lang');
1669
+ const i18n=await import('./i18n.ts');if(language==='en'||language==='ko')i18n.setLanguagePreference(language);
1670
+ const node=<Tag extends keyof HTMLElementTagNameMap>(tag:Tag,key?:string)=>{const value=document.createElement(tag);if(key){value.dataset.jobText=key;value.textContent=t(key);}return value;};
1671
+ const helpers=createJobFormHelpers(node,t),emptyForms=new Map<string,JobForm>();
1672
+ const modalState=()=>{const prepared=rigScreen.mounted();return prepared?.record??prepared?.modals;};
1673
+ const drafts=createJobFormDrafts({jobId:access.jobId,current:()=>modalState()?.inspection??null,forms:()=>modalState()?.forms??emptyForms,storage:()=>localStorage});
1674
+ const transport=createJobWindowTransport(access);
1675
+ let stopped=false;
1676
+ const dependencies:JobFormDependencies={node,translate:t,helpers:{...helpers,assertJobAskSource,jobCheckpointContext},draftStorage:()=>localStorage,...drafts,access,pageId,
1677
+ window:{state:()=>window.state(),submit:input=>window.submit(input)}};
1678
+ const rigScreen=createJobRigScreen({host,pageId,access,translate:(key,values)=>i18n.t(key,values,'en'),refusal:jobWindowRefusal,formDependencies:dependencies,
1679
+ window:{state:()=>window.state(),submit:input=>window.submit(input)},readPublication:(id,signal)=>transport.readPublication(id,signal),
1680
+ routes:display=>jobPublicationRoutes(display,location.origin),load:async()=>(await import('./main.ts')).mountRigScreen()});
1681
+ let bootstrapNotice:HTMLElement|null=null;
1682
+ const report=(error:unknown,fallback?:string)=>{if(rigScreen.mounted()){rigScreen.report(error,fallback);return;}if(!bootstrapNotice){bootstrapNotice=node('p');bootstrapNotice.setAttribute('role','status');host.append(bootstrapNotice);}bootstrapNotice.textContent=jobWindowRefusal(error,fallback);};
1683
+ const window=createJobWindow<JobRigScreenPrepared|null>({jobId:access.jobId,pageId,transport,adapter:{
1684
+ async prepare(display,signal){return rigScreen.prepare(display,signal);},
1685
+ captureDraft(){drafts.saveDraft();const forms=modalState()?.forms;const dirty=forms?[...forms].filter(([,entry])=>entry.dirty):[];return dirty.length?dirty.map(([askId,entry])=>({askId,value:entry.read()})):null;},
1686
+ commit:prepared=>prepared?rigScreen.commit(prepared):{rollback(){},finalize(){}},
1687
+ async painted(prepared,signal){if(stopped||signal.aborted)return;if(prepared)await rigScreen.painted(prepared,signal);},
1688
+ discard:prepared=>{const modal=prepared?.record??prepared?.modals;for(const entry of modal?.forms.values()??[])entry.dispose?.();modal?.inspection.dispose();},
1689
+ changed(state){rigScreen.changed(state);if(state.error&&(!rigScreen.mounted()||rigScreen.mounted()?.record))report(state.error);},
1690
+ }});
1691
+ const localize=i18n.onLanguageChange(()=>{for(const element of host.querySelectorAll<HTMLElement>('[data-job-text]'))element.textContent=t(element.dataset.jobText!);for(const form of host.querySelectorAll('form.interview-answer'))form.dispatchEvent(new Event('job-form-language'));});
1692
+ startJobWindowEvents({access,signal:abort.signal,event:event=>window.event(event),refused:error=>report(error,'JOB_STREAM_FAILED')});
1693
+ const stop=()=>{if(stopped)return;stopped=true;drafts.saveDraft();abort.abort();window.stop();const modal=modalState();for(const entry of modal?.forms.values()??[])entry.dispose?.();modal?.inspection.dispose();localize();globalThis.removeEventListener('pagehide',stop);};
1694
+ globalThis.addEventListener('pagehide',stop,{once:true});return stop;
2521
1695
  }