@rig-c/review 4.9.1 → 4.11.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 (51) hide show
  1. package/docs/DESIGN.md +5 -5
  2. package/docs/PANELS.md +3 -1
  3. package/docs/REVIEW_PACKAGE.md +143 -30
  4. package/docs/STABILITY.md +110 -3
  5. package/package.json +2 -2
  6. package/src/chest-landmarks.ts +9 -4
  7. package/src/cloth-recipe.ts +27 -7
  8. package/src/compare-html.ts +1 -1
  9. package/src/feedback-export.ts +2 -2
  10. package/src/feedback-validation.ts +11 -6
  11. package/src/frame-clock.ts +20 -4
  12. package/src/job-act.ts +60 -71
  13. package/src/job-api.ts +302 -46
  14. package/src/job-checkpoint-evidence.ts +17 -0
  15. package/src/job-cli.ts +3 -2
  16. package/src/job-contract.ts +107 -7
  17. package/src/job-front.ts +48 -12
  18. package/src/job-host.ts +7 -1
  19. package/src/job-session.ts +136 -26
  20. package/src/job-source.ts +133 -21
  21. package/src/job-store.ts +7 -4
  22. package/src/manifest.ts +59 -7
  23. package/src/open-workspace-state.ts +6 -1
  24. package/src/open.ts +3 -3
  25. package/src/rebuild.ts +42 -10
  26. package/src/session.ts +9 -4
  27. package/src/stage-comment.ts +2 -1
  28. package/web/catalog-en.ts +31 -6
  29. package/web/catalog-ko.ts +79 -54
  30. package/web/chest-editor.ts +236 -31
  31. package/web/cloth-panel.ts +1 -1
  32. package/web/compare.css +2 -2
  33. package/web/environment-world.ts +9 -0
  34. package/web/i18n.ts +1 -3
  35. package/web/inspection-persistence.ts +19 -6
  36. package/web/interview-panel.ts +13 -80
  37. package/web/job-rig-screen.ts +65 -37
  38. package/web/job-session.ts +204 -64
  39. package/web/label-placement.ts +25 -8
  40. package/web/main.ts +350 -114
  41. package/web/part-selection.ts +2 -1
  42. package/web/parts-viewport-provider.ts +21 -8
  43. package/web/rebuild-client.ts +3 -5
  44. package/web/rig-host.ts +5 -4
  45. package/web/rig-overlays.ts +3 -2
  46. package/web/rig-viewport-provider.ts +10 -6
  47. package/web/stage-comments.ts +24 -21
  48. package/web/styles.css +23 -51
  49. package/web/viewport-controller.ts +4 -0
  50. package/web/workspace-layout.ts +4 -4
  51. package/web/workspace-ui.ts +8 -6
@@ -7,6 +7,8 @@ import type {
7
7
  JobCheckpointEvidence,
8
8
  JobCheckpointTable,
9
9
  JobInterviewDiagnostics,
10
+ JobProgressLineV3,
11
+ JobProgressV3,
10
12
  JobResult,
11
13
  PendingAskV3,
12
14
  JobPanelComposition,
@@ -21,7 +23,7 @@ import type {
21
23
  import {enCatalog} from './catalog-en.ts';
22
24
  import {koCatalog} from './catalog-ko.ts';
23
25
  import {t,onLanguageChange} from './i18n.ts';
24
- import type {InstanceAccess} from './instance-access.ts';
26
+ import {hashCapabilityAccess, type InstanceAccess} from './instance-access.ts';
25
27
  import {JOB_PLAN_TEXT_FIELDS, parseJobPlanTextProjection, type JobPlanTextProjection} from '../src/job-contract.ts';
26
28
  import {createJobRigScreen, type JobRigScreenPrepared} from './job-rig-screen.ts';
27
29
  import type {JobRigPresentation} from './viewport-capture.ts';
@@ -121,11 +123,18 @@ function assertJobAskSource(ask: PendingAskV3, display: DisplayPublicationV3): v
121
123
  if (sourceSnapshot(source) !== sourceSnapshot(display.publication.source)) {
122
124
  throw new Error('JOB_ACT_SOURCE_STALE');
123
125
  }
126
+ const optionSet = askOptionSet(ask);
124
127
  if (ask.subject.kind === 'interview-picks' &&
125
- (ask.source.optionSet?.id !== ask.subject.setId || !/^[a-f0-9]{64}$/.test(ask.source.optionSet.sha256))) {
128
+ (optionSet?.id !== ask.subject.setId || !/^[a-f0-9]{64}$/.test(optionSet.sha256))) {
126
129
  throw new Error('JOB_ACT_SOURCE_STALE');
127
130
  }
128
131
  }
132
+ /** #1004: the set an interview ask binds: its own `optionSets` row on a several-set publication, else the one set. */
133
+ function askOptionSet(ask: PendingAskV3): {id: string; sha256: string} | null {
134
+ const subject = ask.subject, rows = 'optionSets' in ask.source ? ask.source.optionSets : undefined;
135
+ if (subject.kind !== 'interview-picks') return null;
136
+ return rows?.find(row => row.questionId === subject.questionId && row.setId === subject.setId)?.optionSet ?? ask.source.optionSet ?? null;
137
+ }
129
138
 
130
139
  /** Build pending form dependencies off-stage. A failure rejects the candidate before it is displayed. */
131
140
  export function prepareJobForms<Form>(
@@ -404,27 +413,9 @@ export function jobWindowAccess(href: string, storage: Pick<Storage, 'getItem' |
404
413
  const jobId = match[1]!;
405
414
  const base = url.pathname;
406
415
  const slot = 'rig-review-job-capability/1:' + jobId;
407
- let capability: string | null = null;
408
- if (url.hash.startsWith('#cap=')) {
409
- const value = url.hash.slice(5);
410
- if (/^[a-f0-9]{64}$/.test(value))
411
- capability = value;
412
- url.hash = '';
413
- replace(url.href);
414
- try {
415
- if (capability)
416
- storage?.setItem(slot, capability);
417
- }
418
- catch { /* Memory-only capability when storage is denied. */ }
419
- }
420
- if (!capability) {
421
- try {
422
- const saved = storage?.getItem(slot);
423
- if (saved && /^[a-f0-9]{64}$/.test(saved))
424
- capability = saved;
425
- }
426
- catch { /* A copied link remains read-only. */ }
427
- }
416
+ const capability = hashCapabilityAccess(url, slot, () => storage, replace, {
417
+ strip: 'cap-before-storage', storedValue: 'validate', fallback: null,
418
+ });
428
419
  return {
429
420
  jobId, base, capability,
430
421
  route(path) {
@@ -518,8 +509,26 @@ export function createJobWindowTransport(access: JobWindowAccess, fetcher: typeo
518
509
  submit: body => post('ui/acts', body),
519
510
  };
520
511
  }
512
+ /** A cursorless snapshot belongs to the page stream, alongside the replayable job events. */
513
+ function validateJobProgressLine(line: JobProgressLineV3, jobId: string): void {
514
+ if (line.jobId !== jobId || 'cursor' in line || typeof line.now !== 'string' || !Number.isFinite(Date.parse(line.now)))
515
+ throw new Error('JOB_STREAM_FAILED');
516
+ const value = line.progress;
517
+ if (value === null) return;
518
+ if (!value || !Number.isSafeInteger(value.seq) || value.seq < 1 ||
519
+ !Number.isSafeInteger(value.generation) || value.generation < 0 ||
520
+ !['ingest', 'build', 'measure', 'publish', 'other'].includes(value.phase) ||
521
+ typeof value.at !== 'string' || !Number.isFinite(Date.parse(value.at)))
522
+ throw new Error('JOB_STREAM_FAILED');
523
+ const {text, step} = value;
524
+ if (text !== undefined && (typeof text !== 'string' || text.length > 120 || /[\x00-\x1f\x7f\u0085\u2028\u2029]/u.test(text)))
525
+ throw new Error('JOB_STREAM_FAILED');
526
+ if (step !== undefined && (!step || !Number.isSafeInteger(step.i) || !Number.isSafeInteger(step.n) ||
527
+ step.i < 1 || step.i > step.n || step.n > 1000))
528
+ throw new Error('JOB_STREAM_FAILED');
529
+ }
521
530
  /** Bounded newline events. Reconnects resume after the last fully parsed event. */
522
- export async function* jobWindowEvents(access: JobWindowAccess, after: string | null, signal: AbortSignal, fetcher: typeof fetch = fetch, connected?: () => void): AsyncGenerator<EventV3> {
531
+ export async function* jobWindowEvents(access: JobWindowAccess, after: string | null, signal: AbortSignal, fetcher: typeof fetch = fetch, connected?: () => void, progress?: (line: JobProgressLineV3) => void): AsyncGenerator<EventV3> {
523
532
  const path = 'events' + (after === null ? '' : '?after=' + encodeURIComponent(after));
524
533
  const response = await fetcher(access.route(path), { signal, headers: access.headers() });
525
534
  if (!response.ok || !response.body)
@@ -543,12 +552,18 @@ export async function* jobWindowEvents(access: JobWindowAccess, after: string |
543
552
  while (newline >= 0) {
544
553
  if (newline > limit)
545
554
  throw new Error('JOB_BODY_LIMIT', {cause: 'client: event stream'});
546
- const event = JSON.parse(buffered.slice(0, newline)) as EventV3;
555
+ const event = JSON.parse(buffered.slice(0, newline)) as EventV3 | JobProgressLineV3;
556
+ buffered = buffered.slice(newline + 1);
557
+ if (event?.type === 'progress') {
558
+ validateJobProgressLine(event, access.jobId);
559
+ if (!signal.aborted) progress?.(event);
560
+ newline = buffered.indexOf('\n');
561
+ continue;
562
+ }
547
563
  if (!event || event.jobId !== access.jobId || typeof event.cursor !== 'string' ||
548
564
  !Number.isSafeInteger(event.generation) || event.generation < 0 ||
549
565
  !['published', 'pending', 'act', 'closed'].includes(event.type))
550
566
  throw new Error('JOB_STREAM_FAILED');
551
- buffered = buffered.slice(newline + 1);
552
567
  const crops = new Map<string, {owner: Record<string, unknown>; key: string}[]>();
553
568
  const packed = event as EventV3 & {_jobCommentCrops?: [string[], string][]};
554
569
  for (const [path, sha256] of packed._jobCommentCrops ?? []) {
@@ -603,11 +618,20 @@ export function startJobWindowEvents(options: {
603
618
  access: JobWindowAccess;
604
619
  signal: AbortSignal;
605
620
  event(value: EventV3): void;
621
+ progress?(value: JobProgressV3 | null): void;
606
622
  refused(error: unknown): void;
607
623
  connected?(): void;
608
624
  fetcher?: typeof fetch;
609
625
  }) {
610
626
  let cursor: string | null = null;
627
+ const progressState: {latest: JobProgressV3 | null} = {latest: null};
628
+ let replayGeneration = 0;
629
+ let progressGenerationFloor = 0;
630
+ function deliverProgress(value: JobProgressV3 | null): void {
631
+ if (value && value.generation < progressGenerationFloor) return;
632
+ progressState.latest = value;
633
+ options.progress?.(value);
634
+ }
611
635
  let reader: AbortController | null = null;
612
636
  let wake: (() => void) | null = null;
613
637
  let failed = false;
@@ -625,6 +649,7 @@ export function startJobWindowEvents(options: {
625
649
  try {
626
650
  while (!options.signal.aborted) {
627
651
  const current = new AbortController();
652
+ const replay: {progress: JobProgressV3 | null} = {progress: null};
628
653
  reader = current;
629
654
  try {
630
655
  for await (const event of jobWindowEvents(options.access, cursor, current.signal, options.fetcher, () => {
@@ -632,11 +657,26 @@ export function startJobWindowEvents(options: {
632
657
  failed = false;
633
658
  options.connected?.();
634
659
  }
660
+ }, ({progress}) => {
661
+ // Restore durable asks before rendering a connect snapshot taken after those asks.
662
+ replay.progress = progress && progress.generation > replayGeneration ? progress : null;
663
+ if (!replay.progress) deliverProgress(progress);
635
664
  })) {
665
+ if (event.type !== 'act') {
666
+ progressGenerationFloor = Math.max(progressGenerationFloor, event.generation);
667
+ const latestProgress = progressState.latest;
668
+ if (latestProgress && (event.type === 'closed' || latestProgress.generation < progressGenerationFloor))
669
+ deliverProgress(null);
670
+ }
636
671
  // Only complete, delivered events advance replay, including a final event racing hide.
637
672
  options.event(event);
638
673
  cursor = event.cursor;
639
674
  if (event.type === 'closed') return;
675
+ replayGeneration = Math.max(replayGeneration, event.generation);
676
+ if (replay.progress && replay.progress.generation <= replayGeneration) {
677
+ deliverProgress(replay.progress);
678
+ replay.progress = null;
679
+ }
640
680
  }
641
681
  } catch (error) {
642
682
  if (!current.signal.aborted && !options.signal.aborted) {
@@ -805,6 +845,8 @@ export interface JobPreparedInspection {
805
845
  images: readonly HTMLImageElement[];
806
846
  }[];
807
847
  references: JobReferenceView[];
848
+ /** #983: the record plan's declared picture, hash-checked and decoded; the record screen draws it first. */
849
+ planPicture?: {name: string; src: string};
808
850
  assets: ModelAssets | null;
809
851
  player: RigPlayer | null;
810
852
  rigRoot: HTMLElement;
@@ -813,10 +855,24 @@ export interface JobPreparedInspection {
813
855
  setupPose(setup?: boolean): void;
814
856
  dispose(): void;
815
857
  }
816
- async function jobBytes(url: string, signal: AbortSignal, maximum: number): Promise<Uint8Array<ArrayBuffer>> {
858
+ /** One request per resource per preparation (#1050). Every caller in one preparation passes the same signal; a
859
+ * later preparation (a republish, a reload) brings a new signal and so a new request. The URL carries the
860
+ * publication id and instance key, so a republished resource never shares an older promise. */
861
+ const jobBytesBySignal = new WeakMap<AbortSignal, Map<string, Promise<Uint8Array<ArrayBuffer>>>>();
862
+ async function jobBytes(url: string, signal: AbortSignal, maximum: number, refusal?: { status: number; code: string }): Promise<Uint8Array<ArrayBuffer>> {
863
+ let shared = jobBytesBySignal.get(signal);
864
+ if (!shared) jobBytesBySignal.set(signal, shared = new Map());
865
+ const key = `${url}\n${maximum}\n${refusal ? `${refusal.status}:${refusal.code}` : ''}`;
866
+ let pending = shared.get(key);
867
+ if (!pending) shared.set(key, pending = readJobBytes(url, signal, maximum, refusal));
868
+ return (await pending).slice();
869
+ }
870
+ async function readJobBytes(url: string, signal: AbortSignal, maximum: number, refusal?: { status: number; code: string }): Promise<Uint8Array<ArrayBuffer>> {
817
871
  const response = await fetch(url, { signal });
818
- if (!response.ok || !response.body)
819
- throw new Error('JOB_PRELOAD_FAILED');
872
+ if (!response.ok || !response.body) {
873
+ void response.body?.cancel().catch(() => {});
874
+ throw new Error(response.status === refusal?.status ? refusal.code : 'JOB_PRELOAD_FAILED');
875
+ }
820
876
  const reader = response.body.getReader();
821
877
  const chunks: Uint8Array[] = [];
822
878
  let size = 0;
@@ -847,8 +903,8 @@ async function jobDigest(bytes: Uint8Array<ArrayBuffer>): Promise<string> {
847
903
  return [...new Uint8Array(await crypto.subtle.digest('SHA-256', bytes))]
848
904
  .map(value => value.toString(16).padStart(2, '0')).join('');
849
905
  }
850
- async function jobJson<Value>(url: string, signal: AbortSignal): Promise<Value> {
851
- const bytes = await jobBytes(url, signal, 2 * 1024 * 1024);
906
+ export async function jobJson<Value>(url: string, signal: AbortSignal, refusal?: { status: number; code: string }): Promise<Value> {
907
+ const bytes = await jobBytes(url, signal, 2 * 1024 * 1024, refusal);
852
908
  return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)) as Value;
853
909
  }
854
910
  export function mediaReady(media: HTMLVideoElement, name: 'loadeddata' | 'seeked', signal: AbortSignal): Promise<void> {
@@ -960,7 +1016,7 @@ export async function prepareJobInspection(display: DisplayPublicationV3, signal
960
1016
  }
961
1017
  }
962
1018
  try {
963
- const interview = metadata.capabilities.interview ? await jobJson<JobInterview>(routes.api('interview'), signal) : null;
1019
+ const interview = metadata.capabilities.interview ? await jobJson<JobInterview>(routes.api('interview'), signal, {status: 409, code: 'JOB_SOURCE_UNRETAINABLE'}) : null;
964
1020
  if (recordRig) {
965
1021
  const {manifest, reviewedSource} = metadata;
966
1022
  const model = reviewedSource?.rig;
@@ -1158,6 +1214,13 @@ export async function prepareJobInspection(display: DisplayPublicationV3, signal
1158
1214
  preload.push(image(routes.api('stage-parts/page/' + page.index))
1159
1215
  .then(element => { partPages.set(page.index, element); }));
1160
1216
  }
1217
+ let planPicture: {name: string; src: string} | undefined;
1218
+ const declaredPlanPicture = record && publishedSource.subject === 'plan' ? publishedSource.planPicture : undefined;
1219
+ if (preloadVisuals && declaredPlanPicture) {
1220
+ preload.push(image(routes.api('plan-picture'), declaredPlanPicture.sha256).then(element => {
1221
+ planPicture = {name: declaredPlanPicture.path.split('/').at(-1)!, src: element.src};
1222
+ }));
1223
+ }
1161
1224
  const preloaded = await Promise.allSettled(preload);
1162
1225
  const failed = preloaded.find(result => result.status === 'rejected');
1163
1226
  if (failed?.status === 'rejected')
@@ -1204,6 +1267,7 @@ export async function prepareJobInspection(display: DisplayPublicationV3, signal
1204
1267
  references.sort((a, b) => order.indexOf(a.id) - order.indexOf(b.id));
1205
1268
  return {
1206
1269
  display, metadata, interview, parts, partImages, partPages, checkpointEvidence, references, assets, rigRoot,
1270
+ ...(planPicture ? {planPicture} : {}),
1207
1271
  get rigPresentation() { return rigPresentation; },
1208
1272
  set rigPresentation(value) {
1209
1273
  clearRigPresentation();
@@ -1328,11 +1392,12 @@ export function createJobFormHelpers(node: JobFormNode, t: typeof import('./i18n
1328
1392
  const issue = row.issues.find(issue => issue.field === field);
1329
1393
  if (issue) value.append(node('span', 'job.plan.field.' + issue.reason));
1330
1394
  else if (field === 'rests_on') {
1331
- const rests = node('ul');
1395
+ const rests = node('ul'), questions = projection?.status === 'projected' ? projection.questions : undefined;
1332
1396
  for (const text of row.rests_on!) {
1333
1397
  const rest = node('li'), dependency = plan.steps.find(step => step.id === text);
1398
+ const question = !dependency && questions && Object.hasOwn(questions, text) ? questions[text] : undefined;
1334
1399
  if (dependency) {planStepText(rest, dependency, projection); rest.title = text;}
1335
- else {rest.textContent = text; rest.setAttribute('translate', 'no');}
1400
+ else {rest.textContent = question ?? text; if (question !== undefined) rest.title = text; rest.setAttribute('translate', 'no');}
1336
1401
  rests.append(rest);
1337
1402
  }
1338
1403
  value.append(rests);
@@ -1357,9 +1422,51 @@ export function createJobFormHelpers(node: JobFormNode, t: typeof import('./i18n
1357
1422
  return {inputLabel, selectValues, imageGallery, planTextList, planStepText};
1358
1423
  }
1359
1424
 
1425
+ /** #1004 (owner ruling 2026-11-21): the interview asks of one several-set publication share one question list and one
1426
+ * submit at its top. Submit sends each answered set through its own form (one act per set); the rest stay pending. */
1427
+ const jobQuestionGroups = new WeakMap<JobPreparedInspection, Map<number, {entry: JobForm; action: HTMLButtonElement; redraw(): void}>>();
1428
+ function jobQuestionSet(ask: JobWindowAsk, prepared: JobPreparedInspection, t: typeof import('./i18n.ts').t) {
1429
+ const subject = ask.subject, sets = 'optionSets' in ask.source ? ask.source.optionSets : undefined;
1430
+ if (subject.kind !== 'interview-picks' || !sets || sets.length < 2) return undefined;
1431
+ const index = sets.findIndex(row => row.questionId === subject.questionId && row.setId === subject.setId);
1432
+ let group = jobQuestionGroups.get(prepared);
1433
+ if (!group) jobQuestionGroups.set(prepared, group = new Map());
1434
+ const rows = group, answered = (entry: JobForm) => entry.form.dataset.interviewAnswered === 'true';
1435
+ // Every prompt has a pick and every required Other text is filled; a disabled fieldset does not count as filled.
1436
+ const complete = (form: HTMLFormElement) => {
1437
+ const groups = new Map<string, boolean>();
1438
+ for (const radio of form.querySelectorAll<HTMLInputElement>('input[type=radio]')) groups.set(radio.name, (groups.get(radio.name) ?? false) || radio.checked);
1439
+ return groups.size > 0 && [...groups.values()].every(Boolean) &&
1440
+ [...form.querySelectorAll<HTMLTextAreaElement>('textarea')].every(area => !area.required || !!area.value.trim());
1441
+ };
1442
+ const ready = (entry: JobForm) => !answered(entry) && !entry.submitting && complete(entry.form);
1443
+ const refresh = () => {
1444
+ const members = [...rows.values()], count = members.filter(row => answered(row.entry) || ready(row.entry)).length;
1445
+ for (const row of members) {
1446
+ row.action.textContent = t('interview.submitAnswered', [count, sets.length]);
1447
+ row.action.disabled = !members.some(item => ready(item.entry)) || members.some(item => item.entry.submitting);
1448
+ row.redraw();
1449
+ }
1450
+ };
1451
+ const action = document.createElement('button');
1452
+ action.type = 'button'; action.className = 'primary'; action.dataset.jobQuestionsSubmit = '';
1453
+ action.onclick = () => {for (const row of [...rows.values()]) if (ready(row.entry)) row.entry.form.requestSubmit();};
1454
+ return {
1455
+ list: {listAction: action, selected: index,
1456
+ questions: () => sets.map((row, i) => {const member = rows.get(i)?.entry;
1457
+ return {label: row.questionId + ' · ' + row.setId, answered: !!member && (answered(member) || ready(member))};}),
1458
+ onSelect: (i: number) => rows.get(i)?.entry.form.dispatchEvent(new Event('job-question-select', {bubbles: true}))},
1459
+ join(entry: JobForm, redraw: () => void) {
1460
+ rows.set(index, {entry, action, redraw});
1461
+ for (const type of ['input', 'change', 'job-answer-saved', 'job-answer-failed', 'job-form-language']) entry.form.addEventListener(type, refresh);
1462
+ entry.form.addEventListener('job-form-dispose', () => {if (rows.get(index)?.entry === entry) rows.delete(index); refresh();});
1463
+ refresh();
1464
+ },
1465
+ };
1466
+ }
1467
+
1360
1468
  /** The answer builder owns no page shell, transport or draft collection. */
1361
1469
  export interface JobFormDependencies {
1362
- interviewMainView?:boolean;
1363
1470
  node: JobFormNode;
1364
1471
  translate: typeof import('./i18n.ts').t;
1365
1472
  helpers: ReturnType<typeof createJobFormHelpers> & {
@@ -1400,7 +1507,7 @@ export interface JobFormDependencies {
1400
1507
  fields.append(source);
1401
1508
  const subject = ask.subject;
1402
1509
  if(subject.kind==='review-verdict')throw new Error('JOB_ACT_KIND_DISABLED');
1403
- const commentOnly = subject.kind === 'checkpoint' || subject.kind === 'signoff' || subject.kind === 'reopen';
1510
+ const commentOnly = subject.kind === 'checkpoint' || subject.kind === 'signoff';
1404
1511
  if(commentOnly)fields.append(node('p','job.commentsFromWorkspace'));
1405
1512
  let retainedCommentWords='';
1406
1513
  const commentWords=()=>form.commentWords?.()??retainedCommentWords;
@@ -1408,10 +1515,11 @@ export interface JobFormDependencies {
1408
1515
  let submitKey = 'Submit review';
1409
1516
  let disposeInterview:(()=>void)|undefined;
1410
1517
  let interviewForm:ReturnType<typeof createInterviewForm>|undefined;
1518
+ let questionSet:ReturnType<typeof jobQuestionSet>;
1411
1519
  if (subject.kind === 'interview-picks') {
1412
1520
  let question:InterviewDisplayQuestion|undefined = prepared.interview?.questions.find(item => item.set.id === subject.setId && item.set.question === subject.questionId);
1413
1521
  if (!question || !question.editable) throw new Error('JOB_ASK_INVALID');
1414
- if (question.ref.sha256 !== ask.source.optionSet?.sha256) throw new Error('JOB_ACT_SOURCE_STALE');
1522
+ if (question.ref.sha256 !== askOptionSet(ask)?.sha256) throw new Error('JOB_ACT_SOURCE_STALE');
1415
1523
  if(ask.status==='answered'&&ask.act?.kind==='interview-picks'){
1416
1524
  const value=ask.act.value;
1417
1525
  const picks=value.selections.map(selection=>({ask:selection.itemId,option_id:selection.optionId,...(selection.otherText!==null?{other_text:selection.otherText}:{})}));
@@ -1437,11 +1545,20 @@ export interface JobFormDependencies {
1437
1545
  legacyNotice.dataset.record = legacyDiagnostic.record;
1438
1546
  fields.prepend(legacyNotice);
1439
1547
  }
1440
- interviewForm=createInterviewForm({question,id:'interview-answer-'+ask.askId,node,form,fieldset:fields,source,mainView:deps.interviewMainView,
1441
- images:question.images.map(image=>({name:image.name,src:jobPublicationRoutes(prepared.display,location.origin).instance(image.url)})),answered:ask.status==='answered'});
1442
- if (deps.interviewMainView && prepared.metadata.recordSource && prepared.metadata.manifest?.model)
1443
- interviewForm.form.dataset.interviewMain = '';
1444
- disposeInterview=interviewForm.dispose;read=interviewForm.read;
1548
+ questionSet=jobQuestionSet(ask,prepared,t);
1549
+ interviewForm=createInterviewForm({question,id:'interview-answer-'+ask.askId,node,form,fieldset:fields,source,mainView:true,
1550
+ images:question.images.map(image=>({name:image.name,src:jobPublicationRoutes(prepared.display,location.origin).instance(image.url)})),answered:ask.status==='answered',
1551
+ ...questionSet?.list});
1552
+ if (prepared.metadata.recordSource && (question.missingPicture || !question.images.length) && !prepared.metadata.manifest?.model) {
1553
+ fields.prepend(node('p', question.missingPicture === 'rig'
1554
+ ? 'This question refers to a rig version that this publication does not include.'
1555
+ : question.missingPicture === 'scene'
1556
+ ? 'This question refers to a scene that this publication does not include.'
1557
+ : 'This request has no picture.'));
1558
+ }
1559
+ const {localize,dispose,read:readInterview}=interviewForm;
1560
+ const offLanguage=onLanguageChange(localize);
1561
+ disposeInterview=()=>{offLanguage();dispose();};read=readInterview;
1445
1562
  submitKey = 'interview.save';
1446
1563
  }
1447
1564
  else if (subject.kind === 'checkpoint') {
@@ -1478,20 +1595,6 @@ export interface JobFormDependencies {
1478
1595
  read = () => ({ stage: subject.stage, decision: 'approved', words: commentWords() });
1479
1596
  submitKey = 'job.signoff';
1480
1597
  }
1481
- else if (subject.kind === 'reopen') {
1482
- if (
1483
- !('record' in ask.source) ||
1484
- ask.source.subject !== 'plan' ||
1485
- typeof subject.stage !== 'string' ||
1486
- !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(subject.stage) ||
1487
- !ask.source.subjects.some(candidate => candidate.kind === 'reopen' && candidate.stage === subject.stage)
1488
- ) {
1489
- throw new Error('JOB_ASK_INVALID');
1490
- }
1491
- fields.title = subject.stage;
1492
- read = () => ({ stage: subject.stage, words: commentWords() });
1493
- submitKey = 'job.reopen';
1494
- }
1495
1598
  else {
1496
1599
  throw new Error('JOB_ACT_KIND_DISABLED');
1497
1600
  }
@@ -1512,15 +1615,38 @@ export interface JobFormDependencies {
1512
1615
  const entry: JobForm = { form, fieldset: fields, read, submissionId: crypto.randomUUID(), dirty: false,
1513
1616
  submitting: false, ...(disposeInterview?{dispose:disposeInterview}:{}) };
1514
1617
  if(disposeInterview)form.addEventListener('job-form-dispose',disposeInterview);
1618
+ if(questionSet&&interviewForm)questionSet.join(entry,interviewForm.refresh);
1515
1619
  try {
1516
- const saved = JSON.parse(draftStorage().getItem(localDraftKey(prepared.display)) ?? 'null');
1620
+ const primaryKey = localDraftKey(prepared.display);
1621
+ const legacyPrefix = 'rig-review-job-draft/1:' + (/^\/jobs\/([^/]+)\//.exec(prepared.display.routes.entry)?.[1] ?? '') + ':';
1622
+ const legacyCurrentKey = legacyPrefix + prepared.display.publication.publicationId + ':' + prepared.display.publication.source.sourceHash;
1623
+ const legacyPreviousKey = prepared.display.publication.previousPublicationId
1624
+ ? legacyPrefix + prepared.display.publication.previousPublicationId + ':' + prepared.display.publication.source.sourceHash : '';
1625
+ const primaryRaw = draftStorage().getItem(primaryKey);
1626
+ const raw = primaryRaw ?? draftStorage().getItem(legacyCurrentKey) ?? (legacyPreviousKey ? draftStorage().getItem(legacyPreviousKey) : null);
1627
+ const saved = JSON.parse(raw ?? 'null');
1628
+ const validPublication = primaryRaw !== null
1629
+ ? typeof saved?.publicationId === 'string' && saved.publicationId.length > 0
1630
+ : saved?.publicationId === prepared.display.publication.publicationId ||
1631
+ (Boolean(prepared.display.publication.previousPublicationId) && saved?.publicationId === prepared.display.publication.previousPublicationId);
1517
1632
  // A finalized answer is read back from its act; a local draft never overrides it.
1518
- if (ask.status !== 'answered' && saved?.publicationId === prepared.display.publication.publicationId &&
1633
+ if (ask.status !== 'answered' && validPublication &&
1519
1634
  saved?.sourceHash === prepared.display.publication.source.sourceHash) {
1520
1635
  assertJobAskSource({...ask, source: saved.source}, prepared.display);
1521
- const original = saved.forms?.find((item: {
1636
+ const exact = saved.forms?.find((item: {
1522
1637
  askId: string;
1523
1638
  }) => item.askId === ask.askId);
1639
+ const original = exact ?? (saved.publicationId !== prepared.display.publication.publicationId
1640
+ ? [...(saved.forms ?? [])].reverse().find((item: {
1641
+ askId: string;
1642
+ value?: Record<string, unknown>;
1643
+ }) =>
1644
+ subject.kind === 'interview-picks' ? item.value?.questionId === subject.questionId :
1645
+ subject.kind === 'checkpoint' ? item.value?.checkpointId === subject.checkpointId :
1646
+ subject.kind === 'signoff' && item.value?.stage === subject.stage &&
1647
+ !('outcome' in (item.value ?? {})) && 'decision' in (item.value ?? {})
1648
+ )
1649
+ : undefined);
1524
1650
  if(commentOnly&&typeof original?.value?.words==='string'&&original.value.words.length<=10000)retainedCommentWords=original.value.words;
1525
1651
  for (const input of form.querySelectorAll<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>('input[name],textarea[name],select[name]')) {
1526
1652
  const restored = original?.controls?.find((item: {
@@ -1580,6 +1706,8 @@ export interface JobFormDependencies {
1580
1706
  ? error.message : 'JOB_ACT_INVALID';
1581
1707
  status.textContent = jobWindowRefusal(error, 'JOB_ACT_INVALID');
1582
1708
  fields.disabled = false;
1709
+ // A shared question-set submit waits on every member; a failed one must let it re-enable for the retry.
1710
+ form.dispatchEvent(new Event('job-answer-failed'));
1583
1711
  }
1584
1712
  };
1585
1713
  return entry;
@@ -1604,10 +1732,10 @@ export async function joinedInterviewForms(access:InstanceAccess,present:(forms:
1604
1732
  const show=(index:number)=>{
1605
1733
  if(disposed)return;selected=index;
1606
1734
  const question=data.questions[index];
1607
- if(!question){const empty=node('section');empty.append(node('p','interview.empty'),interviewRecords(data.diagnostics,data.historical));present([empty]);return;}
1735
+ if(!question){const empty=node('section');empty.dataset.interviewMain='';empty.append(node('p','interview.empty'),interviewRecords(data.diagnostics,data.historical));present([empty]);return;}
1608
1736
  let entry=forms.get(index);
1609
1737
  if(!entry){
1610
- entry=createInterviewForm({question,id:'joined-interview-'+question.ref.sha256,node,
1738
+ entry=createInterviewForm({question,id:'joined-interview-'+question.ref.sha256,node,mainView:true,
1611
1739
  images:question.images.map(image=>({name:image.name,src:access.route(image.url)})),
1612
1740
  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)})),
1613
1741
  selected:index,onSelect:show,diagnostics:data.diagnostics,historical:data.historical});
@@ -1636,9 +1764,21 @@ export async function joinedInterviewForms(access:InstanceAccess,present:(forms:
1636
1764
  return ()=>{disposed=true;off();for(const entry of forms.values())entry.dispose();forms.clear();};
1637
1765
  }
1638
1766
 
1767
+ export function jobSourceDraftId(source: SourceV3): string {
1768
+ if ('record' in source)
1769
+ return source.subject === 'option-set' ? source.selection.questionId + ':' + source.selection.setId : 'plan';
1770
+ if (source.selector?.kind === 'draft')
1771
+ return source.selector.id;
1772
+ if (source.selector?.kind === 'rig')
1773
+ return source.package.id + ':rig:' + source.selector.version;
1774
+ if (source.selector?.kind === 'post')
1775
+ return source.package.id + ':post:' + source.selector.version + ':' + source.selector.rigVersion;
1776
+ return source.package.id;
1777
+ }
1778
+
1639
1779
  export function createJobFormDrafts(options:{jobId:string;current():JobPreparedInspection|null;forms():ReadonlyMap<string,JobForm>;storage():Pick<Storage,'setItem'>}) {
1640
1780
  function localDraftKey(display: DisplayPublicationV3): string {
1641
- return 'rig-review-job-draft/1:' + options.jobId + ':' + display.publication.publicationId + ':' + display.publication.source.sourceHash;
1781
+ return 'rig-review-job-draft/1:' + options.jobId + ':' + jobSourceDraftId(display.publication.source) + ':' + display.publication.source.sourceHash;
1642
1782
  }
1643
1783
  function saveDraft(): void {
1644
1784
  const current=options.current(),forms=options.forms();
@@ -1678,7 +1818,7 @@ export async function mountJobScreen(host:HTMLElement):Promise<()=>void> {
1678
1818
  let stopped=false;
1679
1819
  const dependencies:JobFormDependencies={node,translate:t,helpers:{...helpers,assertJobAskSource,jobCheckpointContext},draftStorage:()=>localStorage,...drafts,access,pageId,
1680
1820
  window:{state:()=>window.state(),submit:input=>window.submit(input)}};
1681
- const rigScreen=createJobRigScreen({host,pageId,access,translate:(key,values)=>i18n.t(key,values,'en'),refusal:jobWindowRefusal,formDependencies:dependencies,
1821
+ const rigScreen=createJobRigScreen({host,pageId,access,translate:(key,values)=>i18n.t(key,values,'en'),confirm:text=>globalThis.confirm(i18n.tr(text)),refusal:jobWindowRefusal,formDependencies:dependencies,
1682
1822
  window:{state:()=>window.state(),submit:input=>window.submit(input)},readPublication:(id,signal)=>transport.readPublication(id,signal),
1683
1823
  routes:display=>jobPublicationRoutes(display,location.origin),load:async()=>(await import('./main.ts')).mountRigScreen()});
1684
1824
  let bootstrapNotice:HTMLElement|null=null,bootstrapStream=false,bootstrapPrior:{text:string;title:string}|null=null;
@@ -1697,7 +1837,7 @@ export async function mountJobScreen(host:HTMLElement):Promise<()=>void> {
1697
1837
  }});
1698
1838
  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'));});
1699
1839
  await rigScreen.waiting();
1700
- startJobWindowEvents({access,signal:abort.signal,event:event=>window.event(event),refused:error=>report(error,'JOB_STREAM_FAILED'),connected:clear});
1840
+ startJobWindowEvents({access,signal:abort.signal,event:event=>window.event(event),progress:value=>rigScreen.progress(value),refused:error=>report(error,'JOB_STREAM_FAILED'),connected:clear});
1701
1841
  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);};
1702
1842
  globalThis.addEventListener('pagehide',stop,{once:true});return stop;
1703
1843
  }
@@ -10,7 +10,7 @@
10
10
  * placed at all, pinned or not (#186): a tag and leader for a joint that is not drawn would be a phantom annotation.
11
11
  */
12
12
  export interface LabelPoint {x:number;y:number}
13
- export interface LabelInput {at:LabelPoint;width:number;pinned?:boolean}
13
+ export interface LabelInput {at:LabelPoint;width:number;pinned?:boolean;side?:'left'|'right'}
14
14
  export interface LabelBox {x:number;y:number;w:number;h:number}
15
15
  export interface PlacedLabel {box:LabelBox;/** False: drawn only when pinned (hover / selection). */visible:boolean;/** The box left its home slot; draw a leader to the point. */moved:boolean}
16
16
  export interface LabelPlacementOptions {
@@ -25,25 +25,42 @@ export interface LabelPlacementOptions {
25
25
 
26
26
  export function boxesIntersect(a:LabelBox,b:LabelBox):boolean{return a.x<b.x+b.w&&b.x<a.x+a.w&&a.y<b.y+b.h&&b.y<a.y+a.h;}
27
27
 
28
+ function leaderBox(at:LabelPoint,box:LabelBox):LabelBox{
29
+ const ex=Math.min(Math.max(at.x,box.x),box.x+box.w),ey=Math.min(Math.max(at.y,box.y),box.y+box.h);
30
+ return {x:Math.min(at.x,ex),y:Math.min(at.y,ey),w:Math.max(1,Math.abs(ex-at.x)),h:Math.max(1,Math.abs(ey-at.y))};
31
+ }
32
+
28
33
  /** Candidate boxes for one label, in the order they are tried. The first one is the home box. */
29
34
  export function labelCandidates(input:LabelInput,options:LabelPlacementOptions={}):LabelBox[]{
30
35
  const h=options.height??15,gap=options.gap??9,rise=options.rise??2,step=options.step??h+2,rows=options.rows??4,w=input.width;
31
- const right=input.at.x+gap,left=input.at.x-gap-w,home=input.at.y-rise-h,out:LabelBox[]=[{x:right,y:home,w,h},{x:left,y:home,w,h}];
32
- for(let k=1;k<=rows;k++){const d=k*step;out.push({x:right,y:home-d,w,h},{x:right,y:home+d,w,h},{x:left,y:home-d,w,h},{x:left,y:home+d,w,h});}
36
+ const right=input.at.x+gap,left=input.at.x-gap-w,home=input.at.y-rise-h;
37
+ const first=input.side==='left'?left:right,second=input.side==='left'?right:left;
38
+ const clamp=(x:number)=>options.bounds&&w<=options.bounds.width?Math.max(0,Math.min(x,options.bounds.width-w)):x;
39
+ const xs=[...new Set([first,clamp(first),second,clamp(second)])],out:LabelBox[]=[{x:first,y:home,w,h},{x:second,y:home,w,h}];
40
+ for(let k=1;k<=rows;k++){const d=k*step;for(const x of xs){const clamped=x!==first&&x!==second;out.push({x,y:home-d,w,h},{x,y:clamped?home+d+step:home+d,w,h});}}
33
41
  return out;
34
42
  }
35
43
 
36
44
  export function placeLabels(inputs:readonly LabelInput[],options:LabelPlacementOptions={}):PlacedLabel[]{
45
+ const h=options.height??15,gap=options.gap??9,step=options.step??h+2;
37
46
  const order=inputs.map((_,i)=>i).sort((a,b)=>Number(!!inputs[b]!.pinned)-Number(!!inputs[a]!.pinned)||a-b);
38
47
  const inside=(b:LabelBox)=>!options.bounds||(b.x>=0&&b.y>=0&&b.x+b.w<=options.bounds.width&&b.y+b.h<=options.bounds.height);
39
48
  const onCanvas=(p:LabelPoint)=>!options.bounds||(p.x>=0&&p.y>=0&&p.x<=options.bounds.width&&p.y<=options.bounds.height);
40
- const placed:LabelBox[]=[...(options.obstacles??[])],out:PlacedLabel[]=new Array(inputs.length);
49
+ const active=inputs.filter(x=>onCanvas(x.at));
50
+ const inferSide=(input:LabelInput):'left'|'right'=>{
51
+ if(input.side)return input.side;
52
+ const right=input.at.x+gap,left=input.at.x-gap-input.width,band=active.filter(o=>o!==input&&Math.abs(o.at.y-input.at.y)<=step);
53
+ return band.filter(o=>o.at.x>=right&&o.at.x<=right+input.width).length>band.filter(o=>o.at.x>=left&&o.at.x<=left+input.width).length?'left':'right';
54
+ };
55
+ const placed:LabelBox[]=[...(options.obstacles??[])],labels:LabelBox[]=[],out:PlacedLabel[]=new Array(inputs.length);
41
56
  for(const i of order){
42
- const input=inputs[i]!,candidates=labelCandidates(input,options),home=candidates[0]!;
57
+ const raw=inputs[i]!,input:LabelInput={...raw,side:inferSide(raw)},candidates=labelCandidates(input,options),home=candidates[0]!;
43
58
  if(!onCanvas(input.at)){out[i]={box:home,visible:false,moved:false};continue;}
44
- const index=candidates.findIndex(b=>inside(b)&&!placed.some(p=>boxesIntersect(b,p)));
45
- if(index>=0){const box=candidates[index]!;placed.push(box);out[i]={box,visible:true,moved:index>0};}
46
- else if(input.pinned){placed.push(home);out[i]={box:home,visible:true,moved:false};}
59
+ const free=(b:LabelBox)=>inside(b)&&!placed.some(p=>boxesIntersect(b,p));
60
+ let index=candidates.findIndex(b=>free(b)&&!labels.some(p=>boxesIntersect(leaderBox(input.at,b),p)));
61
+ if(index<0)index=candidates.findIndex(free);
62
+ if(index>=0){const box=candidates[index]!;placed.push(box);labels.push(box);out[i]={box,visible:true,moved:index>0};}
63
+ else if(input.pinned){placed.push(home);labels.push(home);out[i]={box:home,visible:true,moved:false};}
47
64
  else out[i]={box:home,visible:false,moved:false};
48
65
  }
49
66
  return out;