rig-review 4.6.0 → 4.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,12 +2,14 @@
2
2
  import { createHash } from 'node:crypto';
3
3
  import { readFile } from 'node:fs/promises';
4
4
  import { PNG } from 'pngjs';
5
+ import type { JobPreviousDraft } from './job-contract.ts';
5
6
  import { parsePartsIssue, assertPartsIssueBinding, type PartsIssue } from './parts-comment.ts';
6
7
  import { validatePngCrop, storePngCrop, readPngCrop, type PngCrop } from './comment-crops.ts';
7
8
  import { assertPartsUnchanged, partsDifference, verdictSource, type PartsViewPackage } from './parts-view.ts';
8
9
 
9
10
  export interface PartsCommentBindingOptions {
10
11
  readonly sourceHash?: string;
12
+ readonly previousDraft?: JobPreviousDraft;
11
13
  }
12
14
 
13
15
  export async function preparePartsComment(
@@ -58,9 +60,19 @@ async function resolvePartsComment(
58
60
  throw new Error('PARTS_COMPARISON_UNAVAILABLE: original painting required');
59
61
  }
60
62
  if (c.view.comparison?.mode === 'difference') {
61
- for (const part of c.parts) {
62
- const item = itemMap.get(part.name)!;
63
- await partsDifference(pkg, item.index, c.view.comparison.threshold, c.view.footprints);
63
+ if (c.view.comparison.operand === 'previous-draft') {
64
+ if (c.view.mode !== 'assembled' || c.view.footprints) {
65
+ throw new Error('PARTS_COMPARISON_INVALID: previous draft requires an assembled view without footprints');
66
+ }
67
+ // The job caller checks the snapshot seals around this validation.
68
+ if (!options?.sourceHash || !options.previousDraft) {
69
+ throw new Error('PARTS_DIFFERENCE_UNAVAILABLE: bound previous draft required');
70
+ }
71
+ } else {
72
+ for (const part of c.parts) {
73
+ const item = itemMap.get(part.name)!;
74
+ await partsDifference(pkg, item.index, c.view.comparison.threshold, c.view.footprints);
75
+ }
64
76
  }
65
77
  }
66
78
  const partBuffers = new Map<string, Buffer>();
@@ -1,9 +1,11 @@
1
1
  /** Visual comparison settings are evidence, never a producer verdict. Older comments omit them. */
2
- export type PartsComparison = {mode:'part'|'overlay';opacity:number} | {mode:'difference';opacity:number;threshold:number};
2
+ export type PartsComparison = {mode:'part'|'overlay';opacity:number} |
3
+ {mode:'difference';opacity:number;threshold:number;operand?:'previous-draft'};
3
4
  export const defaultPartsComparison = ():PartsComparison => ({mode:'part',opacity:.5});
4
5
  export function parsePartsComparison(raw:unknown):PartsComparison {
5
6
  const v=raw as PartsComparison;
6
7
  const keys=v?.mode==='difference'?['mode','opacity','threshold']:['mode','opacity'];
8
+ if(v?.mode==='difference'&&Object.hasOwn(v,'operand')&&v.operand==='previous-draft')keys.push('operand');
7
9
  if(!v||typeof v!=='object'||Array.isArray(v)||Object.keys(v).length!==keys.length||!keys.every(k=>Object.hasOwn(v,k))||!['part','overlay','difference'].includes(v.mode)||typeof v.opacity!=='number'||!Number.isFinite(v.opacity)||v.opacity<0||v.opacity>1||v.mode==='difference'&&(!Number.isInteger(v.threshold)||v.threshold<0||v.threshold>255))throw new Error('PARTS_COMPARISON_INVALID: part/overlay with opacity 0..1, or difference with integer threshold 0..255 required');
8
10
  return v;
9
11
  }
@@ -22,22 +24,33 @@ export function paintingRectangle(item:{x:number;y:number;w:number;h:number},rig
22
24
 
23
25
  export interface DifferenceRaster {width:number;height:number;data:Uint8Array}
24
26
  export interface DifferenceBox {x:number;y:number;w:number;h:number}
27
+ type DifferenceFronts = readonly {box:DifferenceBox;raster:DifferenceRaster}[];
28
+ interface PaintingDifferenceRaster extends DifferenceRaster {count:number;covered:number;compared:number}
25
29
  /** Exact native-cell pairing only. No placement rounding, filtering or alpha premultiplication. */
26
- export function differencePixels(part:DifferenceRaster,box:DifferenceBox,painting:DifferenceRaster,fronts:readonly {box:DifferenceBox;raster:DifferenceRaster}[],threshold:number,excludeCovered:boolean) {
30
+ export function differencePixels(part:DifferenceRaster,box:DifferenceBox,painting:DifferenceRaster,fronts:DifferenceFronts,threshold:number,excludeCovered:boolean):PaintingDifferenceRaster;
31
+ export function differencePixels(current:DifferenceRaster,box:DifferenceBox,previous:DifferenceRaster,fronts:readonly [],threshold:number,excludeCovered:false,operand:'previous-draft'):DifferenceRaster;
32
+ export function differencePixels(part:DifferenceRaster,box:DifferenceBox,reference:DifferenceRaster,fronts:DifferenceFronts,threshold:number,excludeCovered:boolean,operand?:'previous-draft'):DifferenceRaster|PaintingDifferenceRaster {
27
33
  if(!Number.isInteger(threshold)||threshold<0||threshold>255)throw new Error('PARTS_COMPARISON_INVALID: integer threshold 0..255 required');
28
34
  const valid=(b:DifferenceBox,r:DifferenceRaster)=>[b.x,b.y,b.w,b.h].every(Number.isSafeInteger)&&b.w===r.width&&b.h===r.height&&r.data.length===r.width*r.height*4;
29
35
  if(!valid(box,part)||(excludeCovered&&fronts.some(f=>!valid(f.box,f.raster))))throw new Error('PARTS_DIFFERENCE_ALIGNMENT: integer native placement and exact PNG dimensions required');
36
+ const previousDraft=operand==='previous-draft';
37
+ if(previousDraft&&(box.x!==0||box.y!==0||!valid(box,reference)||excludeCovered||fronts.length))
38
+ throw new Error('PARTS_DIFFERENCE_ALIGNMENT: integer native placement and exact PNG dimensions required');
30
39
  const rgba=new Uint8Array(part.width*part.height*4);let count=0,covered=0,compared=0;
31
40
  for(let y=0;y<part.height;y++)for(let x=0;x<part.width;x++){
32
- const i=(y*part.width+x)*4;if(!part.data[i+3])continue;
41
+ const i=(y*part.width+x)*4;
42
+ if(!part.data[i+3]&&!(previousDraft&&reference.data[i+3]))continue;
33
43
  const gx=box.x+x,gy=box.y+y;
34
- if(gx<0||gy<0||gx>=painting.width||gy>=painting.height)throw new Error('PARTS_DIFFERENCE_ALIGNMENT: nontransparent part pixel lies outside declared rig grid');
44
+ if(gx<0||gy<0||gx>=reference.width||gy>=reference.height)throw new Error('PARTS_DIFFERENCE_ALIGNMENT: nontransparent part pixel lies outside declared rig grid');
35
45
  if(excludeCovered&&fronts.some(f=>{const fx=gx-f.box.x,fy=gy-f.box.y;return fx>=0&&fy>=0&&fx<f.raster.width&&fy<f.raster.height&&f.raster.data[(fy*f.raster.width+fx)*4+3]!>0;})){
36
46
  rgba.set([128,128,128,255],i);covered++;continue;
37
47
  }
38
- const j=(gy*painting.width+gx)*4,d=Math.max(...[0,1,2].map(c=>Math.abs(part.data[i+c]!-painting.data[j+c]!)));
39
- compared++;if(d>threshold)count++;
40
- rgba.set([d>threshold?d:0,0,0,255],i);
48
+ const j=(gy*reference.width+gx)*4;
49
+ const delta=(channel:number)=>Math.abs(part.data[i+channel]!-reference.data[j+channel]!);
50
+ const d=Math.max(delta(0),delta(1),delta(2),previousDraft?delta(3):0),changed=d>threshold;
51
+ if(!previousDraft){compared++;if(changed)count++;}
52
+ rgba[i]=changed?d:0;rgba[i+3]=255;
41
53
  }
42
- return {width:part.width,height:part.height,data:rgba,count,covered,compared};
54
+ const raster={width:part.width,height:part.height,data:rgba};
55
+ return previousDraft?raster:{...raster,count,covered,compared};
43
56
  }
package/src/parts-view.ts CHANGED
@@ -663,8 +663,11 @@ export function buildVerdict(
663
663
  if (c.view.comparison?.mode === 'overlay' && !pkg.painting) {
664
664
  refuse('PARTS_COMPARISON_UNAVAILABLE', 'original painting required');
665
665
  }
666
- if (c.view.comparison?.mode === 'difference' && !pkg.paintingInRig) {
667
- refuse('PARTS_DIFFERENCE_UNAVAILABLE', 'declared painting_in_rig required');
666
+ if (c.view.comparison?.mode === 'difference') {
667
+ if (c.view.comparison.operand === 'previous-draft') {
668
+ refuse('PARTS_DIFFERENCE_UNAVAILABLE', 'bound previous draft required');
669
+ }
670
+ if (!pkg.paintingInRig) refuse('PARTS_DIFFERENCE_UNAVAILABLE', 'declared painting_in_rig required');
668
671
  }
669
672
  if (pkg.mode !== 'parts') {
670
673
  refuse('PARTS_COMMENT_UNAVAILABLE', 'original part required');
@@ -1017,6 +1020,7 @@ export async function readPartsVerdictJson(pkg: PartsViewPackage): Promise<strin
1017
1020
  export function partsViewJson(
1018
1021
  pkg: PartsViewPackage,
1019
1022
  saved: { verdict: PartsVerdict | null; stale: VerdictStale; legacy?: LegacyPartsVerdictView | null },
1023
+ previousDraft?: {readonly id:string;readonly revision:string},
1020
1024
  ) {
1021
1025
  return {
1022
1026
  schema: 'rig-review-parts-view/1',
@@ -1024,6 +1028,7 @@ export function partsViewJson(
1024
1028
  title: pkg.title,
1025
1029
  rigSize: pkg.rigSize,
1026
1030
  differenceAvailable: !!pkg.paintingInRig,
1031
+ ...(previousDraft ? {previousDraft} : {}),
1027
1032
  painting: pkg.painting ? { sha256: pkg.painting.sha256, width: pkg.painting.width, height: pkg.painting.height } : null,
1028
1033
  sourceHash: verdictSource(pkg).sha256,
1029
1034
  items: pkg.items.map(item => ({
@@ -1119,6 +1124,21 @@ export function exportPartsVerdict(
1119
1124
  }
1120
1125
 
1121
1126
  /** Numeric comparison is decoded from bound original PNG bytes on the server, never browser pixels. */
1127
+ function decodeDifferencePng(bytes: Buffer): PNG {
1128
+ // pngjs normalizes valid PNG colour types and bit depths from the bound bytes.
1129
+ try { return PNG.sync.read(bytes); }
1130
+ catch { return refuse('PARTS_DIFFERENCE_PNG', 'decodable PNG operands required'); }
1131
+ }
1132
+
1133
+ export function previousDraftDifference(pkg: PartsViewPackage, current: Buffer, previous: Buffer, threshold: number) {
1134
+ if (pkg.mode !== 'parts' || !pkg.rigSize) {
1135
+ return refuse('PARTS_DIFFERENCE_UNAVAILABLE', 'declared rig canvas required');
1136
+ }
1137
+ const [w, h] = pkg.rigSize;
1138
+ return differencePixels(decodeDifferencePng(current), {x:0,y:0,w,h}, decodeDifferencePng(previous),
1139
+ [], threshold, false, 'previous-draft');
1140
+ }
1141
+
1122
1142
  export async function partsDifference(pkg: PartsViewPackage, index: number, threshold: number, footprints: boolean) {
1123
1143
  await assertPartsUnchanged(pkg);
1124
1144
  if (!pkg.paintingInRig) {
@@ -1128,12 +1148,7 @@ export async function partsDifference(pkg: PartsViewPackage, index: number, thre
1128
1148
  if (pkg.mode !== 'parts' || !Number.isInteger(index) || !item) {
1129
1149
  refuse('PARTS_DIFFERENCE_UNAVAILABLE', 'known original part required');
1130
1150
  }
1131
- const decode = async (path: string) => {
1132
- const bytes = await readFile(path);
1133
- // pngjs normalizes valid PNG colour types and bit depths from the bound bytes.
1134
- try { return PNG.sync.read(bytes); }
1135
- catch { return refuse('PARTS_DIFFERENCE_PNG', 'decodable PNG operands required'); }
1136
- };
1151
+ const decode = async (path: string) => decodeDifferencePng(await readFile(path));
1137
1152
  const painting = await decode(pkg.paintingInRig!.abs);
1138
1153
  const part = await decode(pkg.imagePaths[index]!);
1139
1154
  const fronts = footprints
package/web/catalog-en.ts CHANGED
@@ -8,6 +8,7 @@ export const enCatalog: Readonly<Record<string, string>> = {
8
8
  "Review\u2026": "Review…",
9
9
  "Nothing is waiting for your answer.": "Nothing is waiting for your answer.",
10
10
  "Add a comment where changes are needed.": "Add a comment where changes are needed.",
11
+ "Request changes needs at least one comment pinned to a part.": "Request changes needs at least one comment pinned to a part.",
11
12
  "Remove the flagged parts comments before approving.": "Remove the flagged parts comments before approving.",
12
13
  "Saved draft could not be restored. Your draft has not been deleted. Download or discard it before submitting.": "Saved draft could not be restored. Your draft has not been deleted. Download or discard it before submitting.",
13
14
  "Saved draft downloaded \u00b7 not submitted": "Saved draft downloaded · not submitted",
@@ -19,6 +20,8 @@ export const enCatalog: Readonly<Record<string, string>> = {
19
20
  "job.refusal.JOB_MODEL_MISSING": "This request has no compiled model. The producer must publish a compiled model before requesting a rig verdict.",
20
21
  "JOB_ASK_UNSUPPORTED": "JOB_ASK_UNSUPPORTED",
21
22
  "job.refusal.JOB_ASK_UNSUPPORTED": "This request lacks a supported source or checkpoint mapping. The producer must publish the matching source and plan mapping before asking again.",
23
+ "In a job, press Request changes to send this edit; the producer rebuilds it.": "In a job, press Request changes to send this edit; the producer rebuilds it.",
24
+ "job.mesh.staleDraft": "Some saved mesh edits could not be restored on this model and will be left out.",
22
25
  "Comment · C": "Comment · C",
23
26
 
24
27
  "project.json": "project.json",
@@ -3228,6 +3231,7 @@ export const enCatalog: Readonly<Record<string, string>> = {
3228
3231
  "Frame ranges require an explicit producer frame. Leave both fields empty for this seconds-only comment.": "Frame ranges require an explicit producer frame. Leave both fields empty for this seconds-only comment.",
3229
3232
  "Exact correction text (UTF-8 file)": "Exact correction text (UTF-8 file)",
3230
3233
  "Add correction": "Add correction",
3234
+ "Check the parts.": "Check the parts.",
3231
3235
  "Check the parts and meshes.": "Check the parts and meshes.",
3232
3236
  "Answer these questions.": "Answer these questions.",
3233
3237
  "Check the rig and motion.": "Check the rig and motion.",
@@ -3405,6 +3409,8 @@ export const enCatalog: Readonly<Record<string, string>> = {
3405
3409
  "--by: expected a nonblank reviewer name": "--by: expected a nonblank reviewer name",
3406
3410
  "--by: launch only; incompatible with export or correction options": "--by: launch only; incompatible with export or correction options",
3407
3411
  "Painting comparison": "Painting comparison",
3412
+ "Compare with": "Compare with",
3413
+ "Previous accepted draft · {0} · {1}": "Previous accepted draft · {0} · {1}",
3408
3414
  "Overlay": "Overlay",
3409
3415
  "Part opacity": "Part opacity",
3410
3416
  "PARTS_COMPARISON_UNAVAILABLE: original painting required": "PARTS_COMPARISON_UNAVAILABLE: original painting required",
@@ -3509,6 +3515,7 @@ export const enCatalog: Readonly<Record<string, string>> = {
3509
3515
  "client: preload": "client: preload",
3510
3516
  "{0} {1} \u00b7 {2} bytes \u00b7 HTTP {3}": "{0} {1} \u00b7 {2} bytes \u00b7 HTTP {3}",
3511
3517
  "job.submit.refused": "The request was refused — refresh the review, check the pending request and try again.",
3518
+ "job.submit.JOB_ACT_KIND_DISABLED": "This version cannot submit mesh edits in jobs.",
3512
3519
  "job.submit.JOB_ACT_NOTHING_TO_SUBMIT": "No decision was selected — choose Approved, Changes requested or a checkpoint outcome.",
3513
3520
  "job.submit.JOB_STILL_CAPTURE_FAILED": "The rig image could not be captured — wait for the rig to finish drawing and try again.",
3514
3521
  "job.submit.JOB_STILL_BINDING_MISMATCH": "The displayed frame or source changed — wait for the current rig to load and submit again.",
@@ -3615,9 +3622,12 @@ export const enCatalog: Readonly<Record<string, string>> = {
3615
3622
  "Original part image · {name}": "Original part image · {name}",
3616
3623
  "Source image SHA-256 · {hash}": "Source image SHA-256 · {hash}",
3617
3624
  "Select a part to inspect its original image source.": "Select a part to inspect its original image source.",
3625
+ "There is no compiled rig yet, so some tools and tabs are unavailable.": "There is no compiled rig yet, so some tools and tabs are unavailable.",
3618
3626
  "Parts raster drawn · Canvas2D": "Parts raster drawn · Canvas2D",
3619
3627
  "Parts images · no compiled rig loaded": "Parts images · no compiled rig loaded",
3620
3628
  "Parts ready. Source files remain unchanged.": "Parts ready. Source files remain unchanged.",
3629
+ "This question refers to a rig version that this publication does not include.": "This question refers to a rig version that this publication does not include.",
3630
+ "This question refers to a scene that this publication does not include.": "This question refers to a scene that this publication does not include.",
3621
3631
  "This request has no picture.": "This request has no picture.",
3622
3632
  "The selected part has no chest regions. The chest editor keeps its current part.": "The selected part has no chest regions. The chest editor keeps its current part.",
3623
3633
  'Resize comment area: {0}': 'Resize comment area: {0}',
package/web/catalog-ko.ts CHANGED
@@ -8,6 +8,7 @@ export const koCatalog: Readonly<Record<string, string>> = {
8
8
  "Review\u2026": "검토하기",
9
9
  "Nothing is waiting for your answer.": "답변을 기다리는 요청이 없어요.",
10
10
  "Add a comment where changes are needed.": "고칠 곳에 코멘트를 달아 주세요",
11
+ "Request changes needs at least one comment pinned to a part.": "수정 요청에는 파츠에 고정한 코멘트가 하나 이상 필요해요.",
11
12
  "Remove the flagged parts comments before approving.": "승인하려면 수정 요청한 파츠 코멘트를 먼저 지워 주세요.",
12
13
  "Saved draft could not be restored. Your draft has not been deleted. Download or discard it before submitting.": "저장해 둔 초안을 불러오지 못했어요. 초안은 지워지지 않았어요. 내려받거나 버린 뒤에 제출해 주세요.",
13
14
  "Saved draft downloaded \u00b7 not submitted": "저장해 둔 초안을 내려받았어요 · 아직 제출하지 않았어요",
@@ -19,6 +20,8 @@ export const koCatalog: Readonly<Record<string, string>> = {
19
20
  "job.refusal.JOB_MODEL_MISSING": "이 요청에는 컴파일된 모델이 없어요. 제작 도구에서 컴파일된 모델을 게시한 후 리그 판정을 요청해야 해요.",
20
21
  "JOB_ASK_UNSUPPORTED": "JOB_ASK_UNSUPPORTED",
21
22
  "job.refusal.JOB_ASK_UNSUPPORTED": "이 요청에 맞는 소스 또는 체크포인트 연결 정보가 없어요. 제작 도구에서 해당 소스와 계획 연결 정보를 게시한 후 다시 요청해야 해요.",
23
+ "In a job, press Request changes to send this edit; the producer rebuilds it.": "잡에서는 수정 요청으로 이 편집을 보내 주세요. 리빌드는 프로듀서가 해요.",
24
+ "job.mesh.staleDraft": "이 모델에서 복원하지 못한 메시 편집은 수정 요청에 포함하지 않아요.",
22
25
  "Comment · C": "코멘트 · C",
23
26
 
24
27
  "project.json": "project.json",
@@ -3228,6 +3231,7 @@ export const koCatalog: Readonly<Record<string, string>> = {
3228
3231
  "Frame ranges require an explicit producer frame. Leave both fields empty for this seconds-only comment.": "프레임 범위에는 명시적 프로듀서 프레임이 필요해요. 초 기준 코멘트는 두 필드를 비워 두세요.",
3229
3232
  "Exact correction text (UTF-8 file)": "정확한 수정 문구 (UTF-8 파일)",
3230
3233
  "Add correction": "수정 기록 추가",
3234
+ "Check the parts.": "파츠를 확인해 주세요.",
3231
3235
  "Check the parts and meshes.": "파츠와 메시를 확인해 주세요.",
3232
3236
  "Answer these questions.": "이 질문에 답해 주세요.",
3233
3237
  "Check the rig and motion.": "리그와 모션을 확인해 주세요.",
@@ -3405,6 +3409,8 @@ export const koCatalog: Readonly<Record<string, string>> = {
3405
3409
  "--by: expected a nonblank reviewer name": "--by: 공백이 아닌 검토자 이름이 필요해요",
3406
3410
  "--by: launch only; incompatible with export or correction options": "--by: 실행 전용 옵션이라 내보내기 또는 수정 인계 옵션과 함께 쓸 수 없어요",
3407
3411
  "Painting comparison": "원화 비교",
3412
+ "Compare with": "비교 대상",
3413
+ "Previous accepted draft · {0} · {1}": "이전 승인 초안 · {0} · {1}",
3408
3414
  "Overlay": "오버레이",
3409
3415
  "Part opacity": "파츠 불투명도",
3410
3416
  "PARTS_COMPARISON_UNAVAILABLE: original painting required": "PARTS_COMPARISON_UNAVAILABLE: 원본 원화가 필요해요",
@@ -3509,6 +3515,7 @@ export const koCatalog: Readonly<Record<string, string>> = {
3509
3515
  "client: preload": "client: preload",
3510
3516
  "{0} {1} \u00b7 {2} bytes \u00b7 HTTP {3}": "{0} {1} \u00b7 {2} bytes \u00b7 HTTP {3}",
3511
3517
  "job.submit.refused": "요청이 거절됐어요 — 리뷰를 새로고침하고 대기 중인 요청을 확인한 뒤 다시 제출해 주세요.",
3518
+ "job.submit.JOB_ACT_KIND_DISABLED": "아직 잡에서는 메시 편집을 제출할 수 없어요.",
3512
3519
  "job.submit.JOB_ACT_NOTHING_TO_SUBMIT": "판정이 선택되지 않았어요 — 승인, 수정 요청 또는 체크포인트 결과를 선택해 주세요.",
3513
3520
  "job.submit.JOB_STILL_CAPTURE_FAILED": "리그 이미지를 캡처하지 못했어요 — 리그가 다 그려질 때까지 기다린 뒤 다시 제출해 주세요.",
3514
3521
  "job.submit.JOB_STILL_BINDING_MISMATCH": "표시된 프레임이나 원본이 바뀌었어요 — 현재 리그가 로드될 때까지 기다린 뒤 다시 제출해 주세요.",
@@ -3615,9 +3622,12 @@ export const koCatalog: Readonly<Record<string, string>> = {
3615
3622
  "Original part image · {name}": "원본 파츠 이미지 · {name}",
3616
3623
  "Source image SHA-256 · {hash}": "원본 이미지 SHA-256 · {hash}",
3617
3624
  "Select a part to inspect its original image source.": "파츠를 선택하여 원본 이미지 출처를 확인하세요.",
3625
+ "There is no compiled rig yet, so some tools and tabs are unavailable.": "아직 컴파일된 리그가 없어서 일부 도구와 탭은 쓸 수 없어요.",
3618
3626
  "Parts raster drawn · Canvas2D": "파츠 래스터 그려짐 · Canvas2D",
3619
3627
  "Parts images · no compiled rig loaded": "파츠 이미지 · 컴파일된 리그 로드 안 됨",
3620
3628
  "Parts ready. Source files remain unchanged.": "파츠 준비 완료. 원본 파일은 변경되지 않아요.",
3629
+ "This question refers to a rig version that this publication does not include.": "이 질문이 가리키는 리그 버전이 이번 게시에 들어 있지 않아요.",
3630
+ "This question refers to a scene that this publication does not include.": "이 질문이 가리키는 장면이 이번 게시에 들어 있지 않아요.",
3621
3631
  "This request has no picture.": "이 요청에는 그림이 없어요.",
3622
3632
  "The selected part has no chest regions. The chest editor keeps its current part.": "선택한 파츠에는 가슴 영역이 없어요. 가슴 편집기는 지금 파츠를 그대로 둬요.",
3623
3633
  'Resize comment area: {0}': '코멘트 영역 크기를 조절해요: {0}',
@@ -4,11 +4,14 @@ import type {PartsSubjectData} from './parts-viewport-provider.ts';
4
4
  /** Card I (#709): a rig publication of a live job opens the one review screen (`main.ts`) instead of the job
5
5
  * window. The job stays the transport: same asks, act kinds, still, displayed-ack and submission idempotency.
6
6
  * Rig verdicts use the act bar; supported approval and interview asks use the shared ask dialog. */
7
- import type {ActV3, DisplayPublicationV3, JobResult, JobUISubmission, PendingAskV3, SourceV3, UISubmissionV3} from '../src/job-contract.ts';
7
+ import {JOB_MESH_EDITS_ACT_SCHEMA,type ActV3,type DisplayPublicationV3,type JobMeshEdit,type JobResult,type JobUISubmission,type PendingAskV3,type SourceV3,type UISubmissionV3} from '../src/job-contract.ts';
8
+ import {canonicalJson} from '../src/canonical-json.ts';
9
+ import {draftKey} from '../src/mesh-edit.ts';
8
10
  import type {Feedback, ReviewSession} from '../src/session.ts';
9
11
  import type {ReviewManifest, ReviewedSource} from '../src/manifest.ts';
10
12
  import {checkpointNoteComments, feedbackItemComments, projectComments} from '../src/stage-comment.ts';
11
13
  import {createJobRigSubmission, freezeJobRigStage} from './job-rig-capture.ts';
14
+ import {sha256Hex,type JobMeshDraftSubmission} from './mesh-editor.ts';
12
15
  import {setRigHost, rigHost, type RigHost, type RigHostScreen, type RigHostCommit, type RigHostNavigation} from './rig-host.ts';
13
16
  import {setSourceAttribute, setSourceText, sourceAttribute, sourceTextContent} from './i18n.ts';
14
17
  import type {InstanceAccess} from './instance-access.ts';
@@ -59,11 +62,11 @@ export function jobRigScreenRefusal(display:DisplayPublicationV3,pending:readonl
59
62
 
60
63
  export type JobRigScreenDecision =
61
64
  | {readonly ask: PendingAskV3; readonly kind: 'checkpoint'; readonly value: Extract<JobUISubmission, {kind: 'checkpoint'}>['value']}
62
- | {readonly ask: PendingAskV3; readonly kind: 'review-verdict'; readonly value: {stage: 'rig-review' | 'direction-review'; verdict: 'approved' | 'changes-requested'; words: string; feedback?: readonly Feedback[]}};
65
+ | {readonly ask: PendingAskV3; readonly kind: 'review-verdict'; readonly value: {stage: 'rig-review' | 'direction-review'; verdict: 'approved' | 'changes-requested'; words: string; feedback?: readonly Feedback[]; general?: readonly string[]; meshEdits?: readonly JobMeshEdit[]}};
63
66
  /** The act bar's decisions as the pending asks' values. `words` is the comments' projection (act@6's), or empty;
64
67
  * a decision still pending is not sent, so a pending ask is never answered with "pending". Checkpoints go first. */
65
68
  export function jobRigScreenDecisions(session: Pick<ReviewSession, 'status' | 'checkpoints' | 'feedback'>,
66
- pending: readonly PendingAskV3[], publicationId: string): JobRigScreenDecision[] {
69
+ pending: readonly PendingAskV3[], publicationId: string, general?: readonly string[]): JobRigScreenDecision[] {
67
70
  const open = pending.filter(ask => ask.publicationId === publicationId && ask.status === 'pending');
68
71
  const decisions: JobRigScreenDecision[] = [];
69
72
  for (const ask of open) {
@@ -78,12 +81,20 @@ export function jobRigScreenDecisions(session: Pick<ReviewSession, 'status' | 'c
78
81
  if (verdict?.subject.kind === 'review-verdict' && verdict.subject.stage !== 'image-review' && session.status !== 'pending') {
79
82
  decisions.push({ask: verdict, kind: 'review-verdict', value: {stage: verdict.subject.stage, verdict: session.status,
80
83
  words: session.feedback.length ? projectComments(feedbackItemComments(session.feedback)) : '',
81
- ...(verdict.subject.kind === 'review-verdict' && verdict.subject.stage === 'rig-review' && session.feedback.length ? {feedback: structuredClone(session.feedback)} : {})}});
84
+ ...(verdict.subject.stage === 'rig-review' && session.feedback.length ? {feedback: structuredClone(session.feedback)} : {}),
85
+ ...(verdict.subject.stage === 'rig-review' && general?.length ? {general: [...general]} : {})}});
82
86
  }
83
87
  return decisions;
84
88
  }
85
89
 
86
90
  interface ReviewJson {manifest: ReviewManifest; reviewedSource: ReviewedSource; sourceHash: string}
91
+ export interface JobRigMeshScreen extends RigHostScreen {
92
+ hasMeshEdits?(): boolean;
93
+ meshEdits?(): Promise<JobMeshDraftSubmission|null>;
94
+ }
95
+ export interface JobRigMeshHost extends RigHost {
96
+ canSubmitMeshEdits?(): boolean;
97
+ }
87
98
  export interface JobRigScreenPrepared {readonly jobRigScreen: true; readonly display: DisplayPublicationV3; readonly entry: string;
88
99
  readonly refusal?:string; readonly modals?: {inspection:JobPreparedInspection;forms:Map<string,JobForm>}; readonly review?: ReviewJson; readonly record?: {inspection:JobPreparedInspection;forms:Map<string,JobForm>;picture:JobRigScreenPrepared|null}; readonly parts?:PartsSubjectData; readonly checkpoints: ReadonlySet<string>}
89
100
  export function isJobRigScreen(value: unknown): value is JobRigScreenPrepared {
@@ -104,7 +115,7 @@ export function createJobRigScreen(options: {
104
115
  /** Imports the rig composition once the host is set. */
105
116
  load(): Promise<unknown>;
106
117
  }) {
107
- let mounted: JobRigScreenPrepared | null = null, screen: RigHostScreen | null = null, drawGeneration = 0;
118
+ let mounted: JobRigScreenPrepared | null = null, screen: JobRigMeshScreen | null = null, drawGeneration = 0;
108
119
  let lastMessage: [text: string, error?: boolean, diagnostic?: string] = ['', false];
109
120
  let streamReport: {message: [text: string, error?: boolean, diagnostic?: string]; footer: {source: string; title: string; sourceTitle: string | null; error: boolean} | null; header: {source: string; error: boolean} | null; applied: string} | null = null;
110
121
  let transition:{rollback():Promise<void>;finalize():void}|null=null;
@@ -121,11 +132,17 @@ export function createJobRigScreen(options: {
121
132
  if (!options.formDependencies) throw new Error('JOB_ACT_KIND_DISABLED');
122
133
  const inspection = await prepareJobInspection(display, signal);
123
134
  try {
124
- let previous = display.publication.previousPublicationId, picture:JobRigScreenPrepared|null = null;
135
+ const {entry} = options.routes(display);
136
+ const {manifest, reviewedSource} = inspection.metadata;
137
+ let picture: JobRigScreenPrepared | null = manifest?.model && reviewedSource?.rig
138
+ ? {jobRigScreen:true, display, entry, checkpoints:new Set(), review:{...inspection.metadata, manifest, reviewedSource}}
139
+ : null;
140
+ const missingBoundRig = inspection.interview?.questions.some(question => question.missingPicture === 'rig');
141
+ let previous = missingBoundRig ? null : display.publication.previousPublicationId;
125
142
  const jobId=jobPublicationRoutes(display,location.origin).jobId;
126
143
  const seen = new Set([display.publication.publicationId]);
127
144
  let generation = display.publication.generation;
128
- while (previous) {
145
+ while (!picture && previous) {
129
146
  if(signal.aborted)throw new Error('JOB_PRELOAD_CANCELLED');
130
147
  if (seen.has(previous) || !options.readPublication) throw new Error('JOB_DISPLAY_MISMATCH');
131
148
  seen.add(previous);
@@ -139,16 +156,17 @@ export function createJobRigScreen(options: {
139
156
  if (jobRigScreenSubject(candidate.publication.source)) {picture = await prepare(candidate, signal, true);break;}
140
157
  previous = candidate.publication.previousPublicationId;
141
158
  }
142
- if (!picture && inspection.interview?.questions.some(question => question.hasParts)) {
159
+ if (!picture && !missingBoundRig && inspection.interview?.questions.some(question => question.hasParts)) {
143
160
  const response = await fetch(options.routes(display).api('stage-parts'), {signal});
144
161
  if (!response.ok) throw new Error('JOB_VISUAL_UNAVAILABLE');
145
162
  const parts = await response.json() as PartsSubjectData;
146
163
  if (parts.sourceHash !== source.sourceHash || parts.mode !== 'parts') throw new Error('JOB_DISPLAY_MISMATCH');
147
- picture = {jobRigScreen:true,display,entry:options.routes(display).entry,checkpoints:new Set(),parts};
164
+ picture = {jobRigScreen:true,display,entry,checkpoints:new Set(),parts};
148
165
  }
149
166
  if(signal.aborted)throw new Error('JOB_PRELOAD_CANCELLED');
150
- const forms = prepareJobForms(display, options.window.state().pending, ask => formFor(ask, inspection, {...options.formDependencies!,interviewMainView:!!picture}),!!picture);
151
- return {jobRigScreen:true,display,entry:options.routes(display).entry,checkpoints:new Set(),record:{inspection,forms,picture}};
167
+ const questionMainView = !!picture || !!inspection.interview?.questions.some(question => question.scenePicture);
168
+ const forms = prepareJobForms(display, options.window.state().pending, ask => formFor(ask, inspection, {...options.formDependencies!,interviewMainView:questionMainView}),questionMainView);
169
+ return {jobRigScreen:true,display,entry,checkpoints:new Set(),record:{inspection,forms,picture}};
152
170
  } catch(error) {inspection.dispose();throw error;}
153
171
  }
154
172
  if (!jobRigScreenSubject(source)) {
@@ -195,15 +213,26 @@ export function createJobRigScreen(options: {
195
213
  return freezeJobRigStage({...stage,source},ask.askId,++drawGeneration);
196
214
  }
197
215
 
198
- async function submit(session: ReviewSession, committed: (commit: RigHostCommit) => void | Promise<void>, directionWords?:string): Promise<string> {
216
+ async function submit(session: ReviewSession, committed: (commit: RigHostCommit) => void | Promise<void>, directionWords?:string, general?:readonly string[]): Promise<string> {
199
217
  const prepared = mounted, state = options.window.state();
200
218
  if (!prepared || !state.receipt || state.preparing) throw new Error('JOB_ACT_SOURCE_STALE');
201
219
  if (state.closed) throw new Error('JOB_CLOSED');
202
220
  const refusal=jobRigScreenRefusal(prepared.display,state.pending,prepared.checkpoints);if(refusal)throw new Error(options.translate('job.refusal.'+refusal));
203
221
  if (!options.access.capability) throw new Error('JOB_CAPABILITY_REQUIRED');
204
- const decisions=jobRigScreenDecisions(session, state.pending.filter(ask=>!prepared.modals?.forms.has(ask.askId)), prepared.display.publication.publicationId);
222
+ const decisions=jobRigScreenDecisions(session, state.pending.filter(ask=>!prepared.modals?.forms.has(ask.askId)), prepared.display.publication.publicationId, general);
205
223
  if(directionWords!==undefined)for(const decision of decisions)if(decision.kind==='review-verdict'&&decision.value.stage==='direction-review')decision.value.words=directionWords;
206
224
  if (!decisions.length) throw new Error('JOB_ACT_NOTHING_TO_SUBMIT');
225
+ const rigChanges=decisions.find(decision=>decision.kind==='review-verdict'&&decision.value.stage==='rig-review'&&decision.value.verdict==='changes-requested');
226
+ const meshDraft=rigChanges?.kind==='review-verdict'?await screen?.meshEdits?.():null;
227
+ if(rigChanges?.kind==='review-verdict'){
228
+ if(meshDraft?.edits.length){
229
+ const edits=meshDraft.edits.map(edit=>({key:draftKey(edit),edit}));
230
+ edits.sort((a,b)=>a.key<b.key?-1:a.key>b.key?1:0);
231
+ rigChanges.value.meshEdits=await Promise.all(edits.map(async ({edit})=>({edit,sha256:await sha256Hex(canonicalJson(edit))})));
232
+ }
233
+ const latest=options.window.state();
234
+ if(mounted!==prepared||latest.preparing||latest.receipt?.displayedNonce!==state.receipt.displayedNonce)throw new Error('JOB_ACT_SOURCE_STALE');
235
+ }
207
236
  for (const decision of decisions) {
208
237
  const key = JSON.stringify(decision.value);
209
238
  let attempt = attempts.get(decision.ask.askId);
@@ -220,26 +249,32 @@ export function createJobRigScreen(options: {
220
249
  const result = await options.window.submit(frozen);
221
250
  if (!result.ok) throw new Error(result.error.code, {cause: (result.error as {cause?: unknown}).cause});
222
251
  attempts.delete(ask.askId);
252
+ const act=result.value;
253
+ if(decision===rigChanges&&rigChanges.kind==='review-verdict'&&meshDraft&&act.schema===JOB_MESH_EDITS_ACT_SCHEMA&&act.kind==='review-verdict'&&act.value.meshEdits){
254
+ const accepted=new Set(act.value.meshEdits.map(row=>row.sha256));
255
+ meshDraft.clear(rigChanges.value.meshEdits?.filter(row=>accepted.has(row.sha256)).map(row=>row.edit)??[]);
256
+ }
223
257
  await committed({...current.commit, at: result.value.at});
224
258
  }
225
259
  return options.translate('job.saved');
226
260
  }
227
261
  const partsAttempts=new Map<string,{key:string;submissionId:string}>();
228
262
  /** One parts verdict act. A pending signoff remains independent and is never synthesized here. */
229
- async function submitParts(issues:readonly PartsIssue[]):Promise<string>{
263
+ async function submitParts(issues:readonly PartsIssue[], general?:readonly string[]):Promise<string>{
230
264
  const prepared=mounted,state=options.window.state();
231
265
  if(!prepared?.parts||!state.receipt||state.preparing)throw new Error('JOB_ACT_SOURCE_STALE');
232
266
  if(state.closed)throw new Error('JOB_CLOSED');
233
267
  const ask=state.pending.find(ask=>ask.publicationId===prepared.display.publication.publicationId&&ask.status==='pending'&&ask.subject.kind==='parts-verdict');
234
268
  if(!ask)throw new Error('JOB_ACT_NOTHING_TO_SUBMIT');
235
- const value={verdict:issues.length?'changes-requested' as const:'approved' as const,issues:structuredClone(issues),words:''},key=JSON.stringify(value);
269
+ const value={verdict:issues.length?'changes-requested' as const:'approved' as const,issues:structuredClone(issues),words:'',
270
+ ...(general?.length?{general:[...general]}:{})},key=JSON.stringify(value);
236
271
  let attempt=partsAttempts.get(ask.askId);if(!attempt||attempt.key!==key){attempt={key,submissionId:crypto.randomUUID()};partsAttempts.set(ask.askId,attempt);}
237
272
  const result=await options.window.submit({kind:'parts-verdict',publicationId:ask.publicationId,askId:ask.askId,pageId:options.pageId,displayedNonce:state.receipt.displayedNonce,expectedGeneration:state.generation,submissionId:attempt.submissionId,value});
238
273
  if(!result.ok)throw new Error(result.error.code);
239
274
  partsAttempts.delete(ask.askId);return options.translate('job.saved');
240
275
  }
241
276
  const pendingSubjects=()=>options.window.state().pending.filter(ask=>ask.publicationId===mounted?.display.publication.publicationId&&ask.status==='pending').map(ask=>ask.subject);
242
- function host(prepared: JobRigScreenPrepared, ready: {resolve(): void; reject(error: unknown): void}, navigation?:RigHostNavigation): RigHost {
277
+ function host(prepared: JobRigScreenPrepared, ready: {resolve(): void; reject(error: unknown): void}, navigation?:RigHostNavigation): JobRigMeshHost {
243
278
  const base = new URL(prepared.entry).pathname;
244
279
  const access: InstanceAccess = {base, key: prepared.display.publication.instanceKey, capability: options.access.capability,
245
280
  route: path => {if (!path.startsWith('/') || path.startsWith('//')) throw new Error('Instance route must be app-absolute'); return base + path.slice(1);},
@@ -247,10 +282,11 @@ export function createJobRigScreen(options: {
247
282
  const review = prepared.review;
248
283
  if(prepared.record){
249
284
  const record=prepared.record,backdrop=record.picture?host(record.picture,ready):null;
285
+ const question=record.inspection.interview?.questions[0];
250
286
  return {...(backdrop?.subject?{subject:backdrop.subject}:{}),access:{...(backdrop?.access??access),capability:null,
251
287
  headers:init=>{const headers=options.access.headers(init);headers.delete('X-Review-Capability');return headers;}},
252
288
  ownerActAccess:{capability:options.access.capability},
253
- record:{publicationId:prepared.display.publication.publicationId,label:prepared.display.publication.label,sourceHash:prepared.display.publication.source.sourceHash,hasPicture:!!record.picture},...prepared.refusal?{unavailable:prepared.refusal}:{},pendingSubjects,
289
+ record:{publicationId:prepared.display.publication.publicationId,label:prepared.display.publication.label,sourceHash:prepared.display.publication.source.sourceHash,hasPicture:!!record.picture,missingPicture:question?.missingPicture,scenePicture:question?.scenePicture},...prepared.refusal?{unavailable:prepared.refusal}:{},pendingSubjects,
254
290
  read:(path,method)=>method==='GET'&&backdrop?backdrop.read(path,method):Promise.reject(new Error('JOB_REVIEW_READ_ONLY')),
255
291
  submit:async()=>{throw new Error('JOB_REVIEW_READ_ONLY');},
256
292
  submitParts:async()=>{throw new Error('JOB_REVIEW_READ_ONLY');},
@@ -258,7 +294,11 @@ export function createJobRigScreen(options: {
258
294
  displayed:()=>ready.resolve(),failed:error=>ready.reject(error)};
259
295
  }
260
296
  if(!review&&!prepared.parts)throw new Error('JOB_DISPLAY_MISMATCH');
261
- return {access,pendingSubjects,navigation,...prepared.refusal?{unavailable:prepared.refusal}:{},...prepared.display.publication.source.direction?{direction:{publicationId:prepared.display.publication.publicationId,sourceHash:prepared.display.publication.source.sourceHash}}:{},
297
+ const {publicationId,source}=prepared.display.publication;
298
+ const binding={publicationId,sourceHash:source.sourceHash};
299
+ return {access,pendingSubjects,navigation,...prepared.refusal?{unavailable:prepared.refusal}:{},
300
+ ...(source.direction?{direction:binding}:jobRigScreenSubject(source)?{verdictComments:{...binding,rows:[],available:()=>pendingSubjects().some(subject=>
301
+ prepared.parts?subject.kind==='parts-verdict':subject.kind==='review-verdict'&&subject.stage==='rig-review')}}:{}),
262
302
  reviewState(issues,sending) {
263
303
  if(sending)return options.translate('job.parts.sending');
264
304
  const kind=prepared.parts?'parts-verdict':'review-verdict';
@@ -285,6 +325,7 @@ export function createJobRigScreen(options: {
285
325
  return Promise.reject(new Error('JOB_REVIEW_READ_ONLY'));
286
326
  },
287
327
  submit,
328
+ canSubmitMeshEdits:()=>!!screen?.hasMeshEdits?.(),
288
329
  attach: value => {screen = value;lastMessage=['',false];streamReport=null;screen.pendingSubjects?.(pendingSubjects());refreshRecordForms();},
289
330
  displayed: () => ready.resolve(),
290
331
  failed: error => ready.reject(error)};
@@ -293,7 +334,8 @@ export function createJobRigScreen(options: {
293
334
  function refreshRecordForms():void {
294
335
  const record=mounted?.record??mounted?.modals,deps=options.formDependencies;if(!record||!deps)return;
295
336
  const state=options.window.state(),display=record.inspection.display;
296
- const next=prepareJobForms(display,state.pending.filter(ask=>ask.subject.kind!=='parts-verdict'&&ask.subject.kind!=='review-verdict'&&jobRigScreenAsk(display,ask,mounted!.checkpoints)),ask=>{const previous=record.forms.get(ask.askId),saved=state.pending.find(item=>item.askId===ask.askId);if(previous&&saved?.act?.kind==='interview-picks'&&ask.status==='answered'&&!previous.submitting&&previous.form.dataset.interviewAnswered!=='true'){previous.dispose?.();return formFor(saved,record.inspection,{...deps,interviewMainView:!!mounted?.record?.picture});}return previous??formFor(saved??ask,record.inspection,{...deps,interviewMainView:!!mounted?.record?.picture});},!!mounted?.record?.picture);
337
+ const questionMainView = !!mounted?.record?.picture || !!record.inspection.interview?.questions.some(question => question.scenePicture);
338
+ const next=prepareJobForms(display,state.pending.filter(ask=>ask.subject.kind!=='parts-verdict'&&ask.subject.kind!=='review-verdict'&&jobRigScreenAsk(display,ask,mounted!.checkpoints)),ask=>{const previous=record.forms.get(ask.askId),saved=state.pending.find(item=>item.askId===ask.askId);if(previous&&saved?.act?.kind==='interview-picks'&&ask.status==='answered'&&!previous.submitting&&previous.form.dataset.interviewAnswered!=='true'){previous.dispose?.();return formFor(saved,record.inspection,{...deps,interviewMainView:questionMainView});}return previous??formFor(saved??ask,record.inspection,{...deps,interviewMainView:questionMainView});},questionMainView);
297
339
  for(const [id,entry]of next)record.forms.set(id,entry);
298
340
  for(const [id,entry]of record.forms){const ask=state.pending.find(ask=>ask.askId===id);entry.fieldset.disabled=entry.submitting||ask?.status!=='pending'||state.preparing||state.closed||!state.receipt||!options.access.capability;}
299
341
  screen?.recordForms?.([...record.forms.values()].map(entry=>entry.form));
@@ -370,14 +412,14 @@ export function createJobRigScreen(options: {
370
412
  }catch(error){await rollback();throw error;}
371
413
  },
372
414
  /** Unsupported asks stay on the shared screen with a named explanation. */
373
- changed(state: {readonly pending: readonly PendingAskV3[]; readonly closed: boolean; readonly preparing?:boolean; readonly error?:string|null; readonly errorOrigin?:string; readonly previousLabel?:string|null; readonly displayed?:DisplayPublicationV3|null}): void {
415
+ changed(state: {readonly pending: readonly PendingAskV3[]; readonly closed: boolean; readonly preparing?:boolean; readonly error?:string|null; readonly errorOrigin?:string; readonly failure?:unknown; readonly previousLabel?:string|null; readonly displayed?:DisplayPublicationV3|null}): void {
374
416
  if (!mounted) return;
375
417
  if(mounted.record){screen?.pendingSubjects?.(pendingSubjects());refreshRecordForms();if(mounted.refusal)say(options.translate('job.refusal.'+mounted.refusal),true,undefined,mounted.refusal);if(state.closed)say(options.translate('job.closed'),true);return;}
376
418
  const refusal=jobRigScreenRefusal(mounted.display,state.pending,mounted.checkpoints);
377
419
  if(refusal){say(options.translate('job.refusal.'+refusal),true,undefined,refusal);return;}
378
420
  screen?.pendingSubjects?.(pendingSubjects());
379
421
  refreshRecordForms();
380
- if(state.error)say(options.translate('job.failed')+' · '+options.refusal(state.error),true,jobSubmissionRefusal(new Error(state.error,{cause:state.errorOrigin})).title);
422
+ if(state.error)say(options.translate('job.failed')+' · '+options.refusal(state.failure??state.error),true,jobSubmissionRefusal(new Error(state.error,{cause:state.errorOrigin})).title);
381
423
  else if (state.closed) say(options.translate('job.closed'), true);
382
424
  else if(!state.preparing&&state.displayed?.publication.publicationId===mounted.display.publication.publicationId){
383
425
  const label=state.previousLabel?options.translate('job.updated',[state.previousLabel,mounted.display.publication.label]):mounted.display.publication.label;