@rig-c/review 4.9.1 → 4.10.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.
@@ -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,
@@ -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>(
@@ -518,8 +527,26 @@ export function createJobWindowTransport(access: JobWindowAccess, fetcher: typeo
518
527
  submit: body => post('ui/acts', body),
519
528
  };
520
529
  }
530
+ /** A cursorless snapshot belongs to the page stream, alongside the replayable job events. */
531
+ function validateJobProgressLine(line: JobProgressLineV3, jobId: string): void {
532
+ if (line.jobId !== jobId || 'cursor' in line || typeof line.now !== 'string' || !Number.isFinite(Date.parse(line.now)))
533
+ throw new Error('JOB_STREAM_FAILED');
534
+ const value = line.progress;
535
+ if (value === null) return;
536
+ if (!value || !Number.isSafeInteger(value.seq) || value.seq < 1 ||
537
+ !Number.isSafeInteger(value.generation) || value.generation < 0 ||
538
+ !['ingest', 'build', 'measure', 'publish', 'other'].includes(value.phase) ||
539
+ typeof value.at !== 'string' || !Number.isFinite(Date.parse(value.at)))
540
+ throw new Error('JOB_STREAM_FAILED');
541
+ const {text, step} = value;
542
+ if (text !== undefined && (typeof text !== 'string' || text.length > 120 || /[\x00-\x1f\x7f\u0085\u2028\u2029]/u.test(text)))
543
+ throw new Error('JOB_STREAM_FAILED');
544
+ if (step !== undefined && (!step || !Number.isSafeInteger(step.i) || !Number.isSafeInteger(step.n) ||
545
+ step.i < 1 || step.i > step.n || step.n > 1000))
546
+ throw new Error('JOB_STREAM_FAILED');
547
+ }
521
548
  /** 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> {
549
+ export async function* jobWindowEvents(access: JobWindowAccess, after: string | null, signal: AbortSignal, fetcher: typeof fetch = fetch, connected?: () => void, progress?: (line: JobProgressLineV3) => void): AsyncGenerator<EventV3> {
523
550
  const path = 'events' + (after === null ? '' : '?after=' + encodeURIComponent(after));
524
551
  const response = await fetcher(access.route(path), { signal, headers: access.headers() });
525
552
  if (!response.ok || !response.body)
@@ -543,12 +570,18 @@ export async function* jobWindowEvents(access: JobWindowAccess, after: string |
543
570
  while (newline >= 0) {
544
571
  if (newline > limit)
545
572
  throw new Error('JOB_BODY_LIMIT', {cause: 'client: event stream'});
546
- const event = JSON.parse(buffered.slice(0, newline)) as EventV3;
573
+ const event = JSON.parse(buffered.slice(0, newline)) as EventV3 | JobProgressLineV3;
574
+ buffered = buffered.slice(newline + 1);
575
+ if (event?.type === 'progress') {
576
+ validateJobProgressLine(event, access.jobId);
577
+ if (!signal.aborted) progress?.(event);
578
+ newline = buffered.indexOf('\n');
579
+ continue;
580
+ }
547
581
  if (!event || event.jobId !== access.jobId || typeof event.cursor !== 'string' ||
548
582
  !Number.isSafeInteger(event.generation) || event.generation < 0 ||
549
583
  !['published', 'pending', 'act', 'closed'].includes(event.type))
550
584
  throw new Error('JOB_STREAM_FAILED');
551
- buffered = buffered.slice(newline + 1);
552
585
  const crops = new Map<string, {owner: Record<string, unknown>; key: string}[]>();
553
586
  const packed = event as EventV3 & {_jobCommentCrops?: [string[], string][]};
554
587
  for (const [path, sha256] of packed._jobCommentCrops ?? []) {
@@ -603,11 +636,20 @@ export function startJobWindowEvents(options: {
603
636
  access: JobWindowAccess;
604
637
  signal: AbortSignal;
605
638
  event(value: EventV3): void;
639
+ progress?(value: JobProgressV3 | null): void;
606
640
  refused(error: unknown): void;
607
641
  connected?(): void;
608
642
  fetcher?: typeof fetch;
609
643
  }) {
610
644
  let cursor: string | null = null;
645
+ const progressState: {latest: JobProgressV3 | null} = {latest: null};
646
+ let replayGeneration = 0;
647
+ let progressGenerationFloor = 0;
648
+ function deliverProgress(value: JobProgressV3 | null): void {
649
+ if (value && value.generation < progressGenerationFloor) return;
650
+ progressState.latest = value;
651
+ options.progress?.(value);
652
+ }
611
653
  let reader: AbortController | null = null;
612
654
  let wake: (() => void) | null = null;
613
655
  let failed = false;
@@ -625,6 +667,7 @@ export function startJobWindowEvents(options: {
625
667
  try {
626
668
  while (!options.signal.aborted) {
627
669
  const current = new AbortController();
670
+ const replay: {progress: JobProgressV3 | null} = {progress: null};
628
671
  reader = current;
629
672
  try {
630
673
  for await (const event of jobWindowEvents(options.access, cursor, current.signal, options.fetcher, () => {
@@ -632,11 +675,26 @@ export function startJobWindowEvents(options: {
632
675
  failed = false;
633
676
  options.connected?.();
634
677
  }
678
+ }, ({progress}) => {
679
+ // Restore durable asks before rendering a connect snapshot taken after those asks.
680
+ replay.progress = progress && progress.generation > replayGeneration ? progress : null;
681
+ if (!replay.progress) deliverProgress(progress);
635
682
  })) {
683
+ if (event.type !== 'act') {
684
+ progressGenerationFloor = Math.max(progressGenerationFloor, event.generation);
685
+ const latestProgress = progressState.latest;
686
+ if (latestProgress && (event.type === 'closed' || latestProgress.generation < progressGenerationFloor))
687
+ deliverProgress(null);
688
+ }
636
689
  // Only complete, delivered events advance replay, including a final event racing hide.
637
690
  options.event(event);
638
691
  cursor = event.cursor;
639
692
  if (event.type === 'closed') return;
693
+ replayGeneration = Math.max(replayGeneration, event.generation);
694
+ if (replay.progress && replay.progress.generation <= replayGeneration) {
695
+ deliverProgress(replay.progress);
696
+ replay.progress = null;
697
+ }
640
698
  }
641
699
  } catch (error) {
642
700
  if (!current.signal.aborted && !options.signal.aborted) {
@@ -813,10 +871,12 @@ export interface JobPreparedInspection {
813
871
  setupPose(setup?: boolean): void;
814
872
  dispose(): void;
815
873
  }
816
- async function jobBytes(url: string, signal: AbortSignal, maximum: number): Promise<Uint8Array<ArrayBuffer>> {
874
+ async function jobBytes(url: string, signal: AbortSignal, maximum: number, refusal?: { status: number; code: string }): Promise<Uint8Array<ArrayBuffer>> {
817
875
  const response = await fetch(url, { signal });
818
- if (!response.ok || !response.body)
819
- throw new Error('JOB_PRELOAD_FAILED');
876
+ if (!response.ok || !response.body) {
877
+ void response.body?.cancel().catch(() => {});
878
+ throw new Error(response.status === refusal?.status ? refusal.code : 'JOB_PRELOAD_FAILED');
879
+ }
820
880
  const reader = response.body.getReader();
821
881
  const chunks: Uint8Array[] = [];
822
882
  let size = 0;
@@ -847,8 +907,8 @@ async function jobDigest(bytes: Uint8Array<ArrayBuffer>): Promise<string> {
847
907
  return [...new Uint8Array(await crypto.subtle.digest('SHA-256', bytes))]
848
908
  .map(value => value.toString(16).padStart(2, '0')).join('');
849
909
  }
850
- async function jobJson<Value>(url: string, signal: AbortSignal): Promise<Value> {
851
- const bytes = await jobBytes(url, signal, 2 * 1024 * 1024);
910
+ async function jobJson<Value>(url: string, signal: AbortSignal, refusal?: { status: number; code: string }): Promise<Value> {
911
+ const bytes = await jobBytes(url, signal, 2 * 1024 * 1024, refusal);
852
912
  return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)) as Value;
853
913
  }
854
914
  export function mediaReady(media: HTMLVideoElement, name: 'loadeddata' | 'seeked', signal: AbortSignal): Promise<void> {
@@ -960,7 +1020,7 @@ export async function prepareJobInspection(display: DisplayPublicationV3, signal
960
1020
  }
961
1021
  }
962
1022
  try {
963
- const interview = metadata.capabilities.interview ? await jobJson<JobInterview>(routes.api('interview'), signal) : null;
1023
+ const interview = metadata.capabilities.interview ? await jobJson<JobInterview>(routes.api('interview'), signal, {status: 409, code: 'JOB_SOURCE_UNRETAINABLE'}) : null;
964
1024
  if (recordRig) {
965
1025
  const {manifest, reviewedSource} = metadata;
966
1026
  const model = reviewedSource?.rig;
@@ -1357,9 +1417,51 @@ export function createJobFormHelpers(node: JobFormNode, t: typeof import('./i18n
1357
1417
  return {inputLabel, selectValues, imageGallery, planTextList, planStepText};
1358
1418
  }
1359
1419
 
1420
+ /** #1004 (owner ruling 2026-11-21): the interview asks of one several-set publication share one question list and one
1421
+ * submit at its top. Submit sends each answered set through its own form (one act per set); the rest stay pending. */
1422
+ const jobQuestionGroups = new WeakMap<JobPreparedInspection, Map<number, {entry: JobForm; action: HTMLButtonElement; redraw(): void}>>();
1423
+ function jobQuestionSet(ask: JobWindowAsk, prepared: JobPreparedInspection, t: typeof import('./i18n.ts').t) {
1424
+ const subject = ask.subject, sets = 'optionSets' in ask.source ? ask.source.optionSets : undefined;
1425
+ if (subject.kind !== 'interview-picks' || !sets || sets.length < 2) return undefined;
1426
+ const index = sets.findIndex(row => row.questionId === subject.questionId && row.setId === subject.setId);
1427
+ let group = jobQuestionGroups.get(prepared);
1428
+ if (!group) jobQuestionGroups.set(prepared, group = new Map());
1429
+ const rows = group, answered = (entry: JobForm) => entry.form.dataset.interviewAnswered === 'true';
1430
+ // Every prompt has a pick and every required Other text is filled; a disabled fieldset does not count as filled.
1431
+ const complete = (form: HTMLFormElement) => {
1432
+ const groups = new Map<string, boolean>();
1433
+ for (const radio of form.querySelectorAll<HTMLInputElement>('input[type=radio]')) groups.set(radio.name, (groups.get(radio.name) ?? false) || radio.checked);
1434
+ return groups.size > 0 && [...groups.values()].every(Boolean) &&
1435
+ [...form.querySelectorAll<HTMLTextAreaElement>('textarea')].every(area => !area.required || !!area.value.trim());
1436
+ };
1437
+ const ready = (entry: JobForm) => !answered(entry) && !entry.submitting && complete(entry.form);
1438
+ const refresh = () => {
1439
+ const members = [...rows.values()], count = members.filter(row => answered(row.entry) || ready(row.entry)).length;
1440
+ for (const row of members) {
1441
+ row.action.textContent = t('interview.submitAnswered', [count, sets.length]);
1442
+ row.action.disabled = !members.some(item => ready(item.entry)) || members.some(item => item.entry.submitting);
1443
+ row.redraw();
1444
+ }
1445
+ };
1446
+ const action = document.createElement('button');
1447
+ action.type = 'button'; action.className = 'primary'; action.dataset.jobQuestionsSubmit = '';
1448
+ action.onclick = () => {for (const row of [...rows.values()]) if (ready(row.entry)) row.entry.form.requestSubmit();};
1449
+ return {
1450
+ list: {listAction: action, selected: index,
1451
+ questions: () => sets.map((row, i) => {const member = rows.get(i)?.entry;
1452
+ return {label: row.questionId + ' · ' + row.setId, answered: !!member && (answered(member) || ready(member))};}),
1453
+ onSelect: (i: number) => rows.get(i)?.entry.form.dispatchEvent(new Event('job-question-select', {bubbles: true}))},
1454
+ join(entry: JobForm, redraw: () => void) {
1455
+ rows.set(index, {entry, action, redraw});
1456
+ for (const type of ['input', 'change', 'job-answer-saved', 'job-answer-failed', 'job-form-language']) entry.form.addEventListener(type, refresh);
1457
+ entry.form.addEventListener('job-form-dispose', () => {if (rows.get(index)?.entry === entry) rows.delete(index); refresh();});
1458
+ refresh();
1459
+ },
1460
+ };
1461
+ }
1462
+
1360
1463
  /** The answer builder owns no page shell, transport or draft collection. */
1361
1464
  export interface JobFormDependencies {
1362
- interviewMainView?:boolean;
1363
1465
  node: JobFormNode;
1364
1466
  translate: typeof import('./i18n.ts').t;
1365
1467
  helpers: ReturnType<typeof createJobFormHelpers> & {
@@ -1400,7 +1502,7 @@ export interface JobFormDependencies {
1400
1502
  fields.append(source);
1401
1503
  const subject = ask.subject;
1402
1504
  if(subject.kind==='review-verdict')throw new Error('JOB_ACT_KIND_DISABLED');
1403
- const commentOnly = subject.kind === 'checkpoint' || subject.kind === 'signoff' || subject.kind === 'reopen';
1505
+ const commentOnly = subject.kind === 'checkpoint' || subject.kind === 'signoff';
1404
1506
  if(commentOnly)fields.append(node('p','job.commentsFromWorkspace'));
1405
1507
  let retainedCommentWords='';
1406
1508
  const commentWords=()=>form.commentWords?.()??retainedCommentWords;
@@ -1408,10 +1510,11 @@ export interface JobFormDependencies {
1408
1510
  let submitKey = 'Submit review';
1409
1511
  let disposeInterview:(()=>void)|undefined;
1410
1512
  let interviewForm:ReturnType<typeof createInterviewForm>|undefined;
1513
+ let questionSet:ReturnType<typeof jobQuestionSet>;
1411
1514
  if (subject.kind === 'interview-picks') {
1412
1515
  let question:InterviewDisplayQuestion|undefined = prepared.interview?.questions.find(item => item.set.id === subject.setId && item.set.question === subject.questionId);
1413
1516
  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');
1517
+ if (question.ref.sha256 !== askOptionSet(ask)?.sha256) throw new Error('JOB_ACT_SOURCE_STALE');
1415
1518
  if(ask.status==='answered'&&ask.act?.kind==='interview-picks'){
1416
1519
  const value=ask.act.value;
1417
1520
  const picks=value.selections.map(selection=>({ask:selection.itemId,option_id:selection.optionId,...(selection.otherText!==null?{other_text:selection.otherText}:{})}));
@@ -1437,11 +1540,20 @@ export interface JobFormDependencies {
1437
1540
  legacyNotice.dataset.record = legacyDiagnostic.record;
1438
1541
  fields.prepend(legacyNotice);
1439
1542
  }
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;
1543
+ questionSet=jobQuestionSet(ask,prepared,t);
1544
+ interviewForm=createInterviewForm({question,id:'interview-answer-'+ask.askId,node,form,fieldset:fields,source,mainView:true,
1545
+ images:question.images.map(image=>({name:image.name,src:jobPublicationRoutes(prepared.display,location.origin).instance(image.url)})),answered:ask.status==='answered',
1546
+ ...questionSet?.list});
1547
+ if (prepared.metadata.recordSource && (question.missingPicture || !question.images.length) && !prepared.metadata.manifest?.model) {
1548
+ fields.prepend(node('p', question.missingPicture === 'rig'
1549
+ ? 'This question refers to a rig version that this publication does not include.'
1550
+ : question.missingPicture === 'scene'
1551
+ ? 'This question refers to a scene that this publication does not include.'
1552
+ : 'This request has no picture.'));
1553
+ }
1554
+ const {localize,dispose,read:readInterview}=interviewForm;
1555
+ const offLanguage=onLanguageChange(localize);
1556
+ disposeInterview=()=>{offLanguage();dispose();};read=readInterview;
1445
1557
  submitKey = 'interview.save';
1446
1558
  }
1447
1559
  else if (subject.kind === 'checkpoint') {
@@ -1478,20 +1590,6 @@ export interface JobFormDependencies {
1478
1590
  read = () => ({ stage: subject.stage, decision: 'approved', words: commentWords() });
1479
1591
  submitKey = 'job.signoff';
1480
1592
  }
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
1593
  else {
1496
1594
  throw new Error('JOB_ACT_KIND_DISABLED');
1497
1595
  }
@@ -1512,15 +1610,38 @@ export interface JobFormDependencies {
1512
1610
  const entry: JobForm = { form, fieldset: fields, read, submissionId: crypto.randomUUID(), dirty: false,
1513
1611
  submitting: false, ...(disposeInterview?{dispose:disposeInterview}:{}) };
1514
1612
  if(disposeInterview)form.addEventListener('job-form-dispose',disposeInterview);
1613
+ if(questionSet&&interviewForm)questionSet.join(entry,interviewForm.refresh);
1515
1614
  try {
1516
- const saved = JSON.parse(draftStorage().getItem(localDraftKey(prepared.display)) ?? 'null');
1615
+ const primaryKey = localDraftKey(prepared.display);
1616
+ const legacyPrefix = 'rig-review-job-draft/1:' + (/^\/jobs\/([^/]+)\//.exec(prepared.display.routes.entry)?.[1] ?? '') + ':';
1617
+ const legacyCurrentKey = legacyPrefix + prepared.display.publication.publicationId + ':' + prepared.display.publication.source.sourceHash;
1618
+ const legacyPreviousKey = prepared.display.publication.previousPublicationId
1619
+ ? legacyPrefix + prepared.display.publication.previousPublicationId + ':' + prepared.display.publication.source.sourceHash : '';
1620
+ const primaryRaw = draftStorage().getItem(primaryKey);
1621
+ const raw = primaryRaw ?? draftStorage().getItem(legacyCurrentKey) ?? (legacyPreviousKey ? draftStorage().getItem(legacyPreviousKey) : null);
1622
+ const saved = JSON.parse(raw ?? 'null');
1623
+ const validPublication = primaryRaw !== null
1624
+ ? typeof saved?.publicationId === 'string' && saved.publicationId.length > 0
1625
+ : saved?.publicationId === prepared.display.publication.publicationId ||
1626
+ (Boolean(prepared.display.publication.previousPublicationId) && saved?.publicationId === prepared.display.publication.previousPublicationId);
1517
1627
  // 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 &&
1628
+ if (ask.status !== 'answered' && validPublication &&
1519
1629
  saved?.sourceHash === prepared.display.publication.source.sourceHash) {
1520
1630
  assertJobAskSource({...ask, source: saved.source}, prepared.display);
1521
- const original = saved.forms?.find((item: {
1631
+ const exact = saved.forms?.find((item: {
1522
1632
  askId: string;
1523
1633
  }) => item.askId === ask.askId);
1634
+ const original = exact ?? (saved.publicationId !== prepared.display.publication.publicationId
1635
+ ? [...(saved.forms ?? [])].reverse().find((item: {
1636
+ askId: string;
1637
+ value?: Record<string, unknown>;
1638
+ }) =>
1639
+ subject.kind === 'interview-picks' ? item.value?.questionId === subject.questionId :
1640
+ subject.kind === 'checkpoint' ? item.value?.checkpointId === subject.checkpointId :
1641
+ subject.kind === 'signoff' && item.value?.stage === subject.stage &&
1642
+ !('outcome' in (item.value ?? {})) && 'decision' in (item.value ?? {})
1643
+ )
1644
+ : undefined);
1524
1645
  if(commentOnly&&typeof original?.value?.words==='string'&&original.value.words.length<=10000)retainedCommentWords=original.value.words;
1525
1646
  for (const input of form.querySelectorAll<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>('input[name],textarea[name],select[name]')) {
1526
1647
  const restored = original?.controls?.find((item: {
@@ -1580,6 +1701,8 @@ export interface JobFormDependencies {
1580
1701
  ? error.message : 'JOB_ACT_INVALID';
1581
1702
  status.textContent = jobWindowRefusal(error, 'JOB_ACT_INVALID');
1582
1703
  fields.disabled = false;
1704
+ // A shared question-set submit waits on every member; a failed one must let it re-enable for the retry.
1705
+ form.dispatchEvent(new Event('job-answer-failed'));
1583
1706
  }
1584
1707
  };
1585
1708
  return entry;
@@ -1604,10 +1727,10 @@ export async function joinedInterviewForms(access:InstanceAccess,present:(forms:
1604
1727
  const show=(index:number)=>{
1605
1728
  if(disposed)return;selected=index;
1606
1729
  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;}
1730
+ if(!question){const empty=node('section');empty.dataset.interviewMain='';empty.append(node('p','interview.empty'),interviewRecords(data.diagnostics,data.historical));present([empty]);return;}
1608
1731
  let entry=forms.get(index);
1609
1732
  if(!entry){
1610
- entry=createInterviewForm({question,id:'joined-interview-'+question.ref.sha256,node,
1733
+ entry=createInterviewForm({question,id:'joined-interview-'+question.ref.sha256,node,mainView:true,
1611
1734
  images:question.images.map(image=>({name:image.name,src:access.route(image.url)})),
1612
1735
  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
1736
  selected:index,onSelect:show,diagnostics:data.diagnostics,historical:data.historical});
@@ -1636,9 +1759,21 @@ export async function joinedInterviewForms(access:InstanceAccess,present:(forms:
1636
1759
  return ()=>{disposed=true;off();for(const entry of forms.values())entry.dispose();forms.clear();};
1637
1760
  }
1638
1761
 
1762
+ export function jobSourceDraftId(source: SourceV3): string {
1763
+ if ('record' in source)
1764
+ return source.subject === 'option-set' ? source.selection.questionId + ':' + source.selection.setId : 'plan';
1765
+ if (source.selector?.kind === 'draft')
1766
+ return source.selector.id;
1767
+ if (source.selector?.kind === 'rig')
1768
+ return source.package.id + ':rig:' + source.selector.version;
1769
+ if (source.selector?.kind === 'post')
1770
+ return source.package.id + ':post:' + source.selector.version + ':' + source.selector.rigVersion;
1771
+ return source.package.id;
1772
+ }
1773
+
1639
1774
  export function createJobFormDrafts(options:{jobId:string;current():JobPreparedInspection|null;forms():ReadonlyMap<string,JobForm>;storage():Pick<Storage,'setItem'>}) {
1640
1775
  function localDraftKey(display: DisplayPublicationV3): string {
1641
- return 'rig-review-job-draft/1:' + options.jobId + ':' + display.publication.publicationId + ':' + display.publication.source.sourceHash;
1776
+ return 'rig-review-job-draft/1:' + options.jobId + ':' + jobSourceDraftId(display.publication.source) + ':' + display.publication.source.sourceHash;
1642
1777
  }
1643
1778
  function saveDraft(): void {
1644
1779
  const current=options.current(),forms=options.forms();
@@ -1678,7 +1813,7 @@ export async function mountJobScreen(host:HTMLElement):Promise<()=>void> {
1678
1813
  let stopped=false;
1679
1814
  const dependencies:JobFormDependencies={node,translate:t,helpers:{...helpers,assertJobAskSource,jobCheckpointContext},draftStorage:()=>localStorage,...drafts,access,pageId,
1680
1815
  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,
1816
+ 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
1817
  window:{state:()=>window.state(),submit:input=>window.submit(input)},readPublication:(id,signal)=>transport.readPublication(id,signal),
1683
1818
  routes:display=>jobPublicationRoutes(display,location.origin),load:async()=>(await import('./main.ts')).mountRigScreen()});
1684
1819
  let bootstrapNotice:HTMLElement|null=null,bootstrapStream=false,bootstrapPrior:{text:string;title:string}|null=null;
@@ -1697,7 +1832,7 @@ export async function mountJobScreen(host:HTMLElement):Promise<()=>void> {
1697
1832
  }});
1698
1833
  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
1834
  await rigScreen.waiting();
1700
- startJobWindowEvents({access,signal:abort.signal,event:event=>window.event(event),refused:error=>report(error,'JOB_STREAM_FAILED'),connected:clear});
1835
+ 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
1836
  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
1837
  globalThis.addEventListener('pagehide',stop,{once:true});return stop;
1703
1838
  }
@@ -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;