@rig-c/review 1.16.7 → 1.18.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.
@@ -0,0 +1,1623 @@
1
+ /** Live job window transactions. Every form remains bound to its displayed publication. */
2
+ import type { JobAct, JobDisplayPublication, JobDisplayReceipt, JobEvent, JobPendingAsk, JobPublication, JobResult, JobUISubmission, JobSourceBinding, } from '../src/job-contract.ts';
3
+ import {enCatalog} from './catalog-en.ts';
4
+ import {koCatalog} from './catalog-ko.ts';
5
+ import {t} from './i18n.ts';
6
+
7
+ /** Imported runtimes may throw arbitrary prose. Only registered refusal copy reaches the window. */
8
+ export function jobWindowRefusal(error: unknown, fallback = 'JOB_WINDOW_FAILED'): string {
9
+ const message = error instanceof Error ? error.message : error;
10
+ if (typeof message === 'string' &&
11
+ Object.hasOwn(enCatalog, message) && Object.hasOwn(koCatalog, message)) {
12
+ return t(message);
13
+ }
14
+ return t(fallback);
15
+ }
16
+ export interface JobWindowTransport {
17
+ readPublication(publicationId: string, signal?: AbortSignal): Promise<JobResult<JobDisplayPublication>>;
18
+ acknowledge(input: {
19
+ publicationId: string;
20
+ pageId: string;
21
+ sourceHash: string;
22
+ }, signal: AbortSignal): Promise<JobResult<JobDisplayReceipt>>;
23
+ submit(input: JobUISubmission): Promise<JobResult<JobAct>>;
24
+ }
25
+ export interface JobPreparedCommit {
26
+ /** Restore the previous view, including its original forms and route bindings. */
27
+ rollback(): void;
28
+ /** Dispose the old view only after the new displayed nonce is acknowledged. */
29
+ finalize(): void;
30
+ }
31
+ export interface JobWindowAdapter<Prepared> {
32
+ /** Resolve assets, metadata, forms and publication-pinned routes before returning. */
33
+ prepare(display: JobDisplayPublication, signal: AbortSignal): Promise<Prepared>;
34
+ /** Called immediately before commit, so edits made during preloading are retained. */
35
+ captureDraft(): unknown | null;
36
+ commit(prepared: Prepared, display: JobDisplayPublication): JobPreparedCommit;
37
+ painted(prepared: Prepared, signal: AbortSignal): Promise<void>;
38
+ discard(prepared: Prepared): void;
39
+ changed(state: JobWindowState): void;
40
+ }
41
+ export interface JobRetainedDraft {
42
+ readonly publicationId: string;
43
+ readonly sourceHash: string;
44
+ readonly source?: JobSourceBinding;
45
+ readonly label: string;
46
+ readonly value: unknown;
47
+ }
48
+ export interface JobWindowState {
49
+ readonly generation: number;
50
+ readonly displayed: JobDisplayPublication | null;
51
+ readonly receipt: JobDisplayReceipt | null;
52
+ readonly preparing: boolean;
53
+ readonly closed: boolean;
54
+ readonly error: string | null;
55
+ readonly previousLabel: string | null;
56
+ readonly pending: readonly JobPendingAsk[];
57
+ readonly retainedDrafts: readonly JobRetainedDraft[];
58
+ }
59
+ function unwrap<Value>(result: JobResult<Value>): Value {
60
+ if (!result.ok)
61
+ throw new Error(result.error.code);
62
+ return result.value;
63
+ }
64
+ function sourceSnapshot(source: JobSourceBinding): string {
65
+ return JSON.stringify(source, (_key, value: unknown) => {
66
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
67
+ return value;
68
+ const record = value as Record<string, unknown>;
69
+ return Object.fromEntries(Object.keys(record).sort().map(key => [key, record[key]]));
70
+ });
71
+ }
72
+ function assertJobAskSource(ask: JobPendingAsk, display: JobDisplayPublication): void {
73
+ const source = ask.subject.kind === 'interview-picks'
74
+ ? { ...ask.source, optionSet: display.publication.source.optionSet }
75
+ : ask.source;
76
+ if (sourceSnapshot(source) !== sourceSnapshot(display.publication.source)) {
77
+ throw new Error('JOB_ACT_SOURCE_STALE');
78
+ }
79
+ if (ask.subject.kind === 'interview-picks' &&
80
+ (ask.source.optionSet?.id !== ask.subject.setId || !/^[a-f0-9]{64}$/.test(ask.source.optionSet.sha256))) {
81
+ throw new Error('JOB_ACT_SOURCE_STALE');
82
+ }
83
+ }
84
+
85
+ /** Build pending form dependencies off-stage. A failure rejects the candidate before it is displayed. */
86
+ export function prepareJobForms<Form>(
87
+ display: JobDisplayPublication,
88
+ asks: readonly JobPendingAsk[],
89
+ prepare: (ask: JobPendingAsk) => Form,
90
+ ): Map<string, Form> {
91
+ const prepared = new Map<string, Form>();
92
+ for (const ask of asks) {
93
+ if (ask.publicationId !== display.publication.publicationId || ask.status !== 'pending') continue;
94
+ assertJobAskSource(ask, display);
95
+ prepared.set(ask.askId, prepare(ask));
96
+ }
97
+ return prepared;
98
+ }
99
+
100
+ /** C2 publishes the plan mapping in the ask. Legacy checkpoint metadata is optional guidance. */
101
+ export function jobCheckpointContext(
102
+ ask: JobPendingAsk,
103
+ checkpoints: readonly Pick<Checkpoint, 'id' | 'title' | 'note'>[],
104
+ ) {
105
+ if (ask.subject.kind !== 'checkpoint') throw new Error('JOB_ASK_INVALID');
106
+ const checkpointId = ask.subject.checkpointId;
107
+ const planStepId = ask.subject.planStepId ?? checkpointId;
108
+ const step = ask.source.plan?.steps.find(item => item.id === planStepId);
109
+ if (!step) throw new Error('JOB_ASK_INVALID');
110
+ const checkpoint = checkpoints.find(item => item.id === checkpointId);
111
+ return {
112
+ step,
113
+ title: checkpoint?.title ?? checkpointId,
114
+ note: checkpoint?.note ?? '',
115
+ };
116
+ }
117
+
118
+ /** No network, DOM or storage is accessed until the supplied adapter does so. */
119
+ export function createJobWindow<Prepared>(options: {
120
+ jobId: string;
121
+ pageId: string;
122
+ transport: JobWindowTransport;
123
+ adapter: JobWindowAdapter<Prepared>;
124
+ }) {
125
+ const { transport, adapter, pageId } = options;
126
+ const pending = new Map<string, JobPendingAsk>();
127
+ const retainedDrafts: JobRetainedDraft[] = [];
128
+ let generation = 0;
129
+ let displayed: JobDisplayPublication | null = null;
130
+ let receipt: JobDisplayReceipt | null = null;
131
+ let preparing = false;
132
+ let closed = false;
133
+ let error: string | null = null;
134
+ let previousLabel: string | null = null;
135
+ let intent = 0;
136
+ let stopped = false;
137
+ let controller: AbortController | null = null;
138
+ let queue = Promise.resolve();
139
+ function state(): JobWindowState {
140
+ return {
141
+ generation, displayed, receipt, preparing, closed, error, previousLabel,
142
+ pending: [...pending.values()], retainedDrafts: [...retainedDrafts],
143
+ };
144
+ }
145
+ function changed(): void { adapter.changed(state()); }
146
+ function replace(publication: JobPublication): Promise<void> {
147
+ if (stopped)
148
+ return Promise.resolve();
149
+ const revision = ++intent;
150
+ controller?.abort();
151
+ const abort = new AbortController();
152
+ controller = abort;
153
+ preparing = true;
154
+ error = null;
155
+ changed();
156
+ queue = queue.then(async () => {
157
+ if (revision !== intent || stopped)
158
+ return;
159
+ let prepared: Prepared | undefined;
160
+ let committed: JobPreparedCommit | undefined;
161
+ try {
162
+ if (publication.visual.status !== 'available')
163
+ throw new Error(publication.visual.code);
164
+ const candidate = unwrap(await transport.readPublication(publication.publicationId, abort.signal));
165
+ if (candidate.publication.publicationId !== publication.publicationId ||
166
+ candidate.publication.source.sourceHash !== publication.source.sourceHash ||
167
+ candidate.publication.instanceKey !== publication.instanceKey ||
168
+ candidate.publication.generation !== publication.generation ||
169
+ sourceSnapshot(candidate.publication.source) !== sourceSnapshot(publication.source)) {
170
+ throw new Error('JOB_DISPLAY_MISMATCH');
171
+ }
172
+ prepared = await adapter.prepare(candidate, abort.signal);
173
+ if (revision !== intent || stopped)
174
+ return;
175
+ const draft = adapter.captureDraft();
176
+ committed = adapter.commit(prepared, candidate);
177
+ await adapter.painted(prepared, abort.signal);
178
+ if (revision !== intent || stopped)
179
+ return;
180
+ const acknowledged = unwrap(await transport.acknowledge({
181
+ publicationId: publication.publicationId, pageId,
182
+ sourceHash: publication.source.sourceHash,
183
+ }, abort.signal));
184
+ if (revision !== intent || stopped)
185
+ return;
186
+ if (acknowledged.publicationId !== publication.publicationId ||
187
+ acknowledged.pageId !== pageId || !acknowledged.displayedNonce) {
188
+ throw new Error('JOB_DISPLAY_MISMATCH');
189
+ }
190
+ if (displayed && draft !== null) {
191
+ retainedDrafts.push({
192
+ publicationId: displayed.publication.publicationId,
193
+ sourceHash: displayed.publication.source.sourceHash,
194
+ source: structuredClone(displayed.publication.source),
195
+ label: displayed.publication.label,
196
+ value: structuredClone(draft),
197
+ });
198
+ }
199
+ previousLabel = displayed?.publication.label ?? null;
200
+ displayed = candidate;
201
+ receipt = acknowledged;
202
+ const cleanup = committed;
203
+ committed = undefined;
204
+ prepared = undefined;
205
+ try {
206
+ cleanup.finalize();
207
+ }
208
+ catch {
209
+ error = 'JOB_WINDOW_CLEANUP_FAILED';
210
+ }
211
+ }
212
+ catch (failure) {
213
+ if (revision === intent && !stopped)
214
+ error = failure instanceof Error ? failure.message : 'JOB_DISPLAY_MISMATCH';
215
+ }
216
+ finally {
217
+ committed?.rollback();
218
+ if (prepared !== undefined)
219
+ adapter.discard(prepared);
220
+ if (revision === intent) {
221
+ preparing = false;
222
+ changed();
223
+ }
224
+ }
225
+ });
226
+ return queue;
227
+ }
228
+ function event(value: JobEvent): void {
229
+ if (stopped || value.jobId !== options.jobId)
230
+ return;
231
+ generation = Math.max(generation, value.generation);
232
+ if (value.type === 'published') {
233
+ for (const [id, ask] of pending) {
234
+ if (ask.status === 'pending' && ask.publicationId !== value.publication.publicationId) {
235
+ pending.set(id, { ...ask, status: 'superseded' });
236
+ }
237
+ }
238
+ if (value.publication.publicationId !== displayed?.publication.publicationId)
239
+ void replace(value.publication);
240
+ }
241
+ else if (value.type === 'pending') {
242
+ pending.set(value.ask.askId, value.ask);
243
+ }
244
+ else if (value.type === 'act') {
245
+ const ask = pending.get(value.act.askId);
246
+ if (ask)
247
+ pending.set(ask.askId, { ...ask, status: 'answered' });
248
+ }
249
+ else if (value.type === 'closed') {
250
+ closed = true;
251
+ }
252
+ changed();
253
+ }
254
+ async function submit(input: JobUISubmission): Promise<JobResult<JobAct>> {
255
+ if (closed)
256
+ return { ok: false, error: { code: 'JOB_CLOSED', message: 'JOB_CLOSED' } };
257
+ const ask = pending.get(input.askId);
258
+ if (preparing || !displayed || !receipt ||
259
+ input.publicationId !== displayed.publication.publicationId ||
260
+ input.pageId !== pageId || input.displayedNonce !== receipt.displayedNonce ||
261
+ input.expectedGeneration > generation ||
262
+ ask && (ask.status !== 'pending' || ask.publicationId !== input.publicationId || ask.subject.kind !== input.kind)) {
263
+ return { ok: false, error: { code: 'JOB_ACT_SOURCE_STALE', message: 'JOB_ACT_SOURCE_STALE' } };
264
+ }
265
+ // The backend authenticates the actual Request and validates the semantic value.
266
+ return transport.submit(input);
267
+ }
268
+ return {
269
+ event, replace, submit, state, refresh: changed,
270
+ settled: () => queue,
271
+ stop() { stopped = true; ++intent; controller?.abort(); },
272
+ };
273
+ }
274
+ export interface JobWindowAccess {
275
+ readonly jobId: string;
276
+ readonly base: string;
277
+ readonly capability: string | null;
278
+ route(path: string): string;
279
+ headers(init?: HeadersInit): Headers;
280
+ }
281
+ /** The owner capability stays in this page's memory and its own job-scoped tab slot. */
282
+ export function jobWindowAccess(href: string, storage: Pick<Storage, 'getItem' | 'setItem'> | null, replace: (href: string) => void): JobWindowAccess {
283
+ const url = new URL(href);
284
+ const match = /^\/jobs\/([A-Za-z0-9][A-Za-z0-9._-]{0,127})\/$/.exec(url.pathname);
285
+ if (!match)
286
+ throw new Error('JOB_REQUEST_INVALID');
287
+ const jobId = match[1]!;
288
+ const base = url.pathname;
289
+ const slot = 'rig-review-job-capability/1:' + jobId;
290
+ let capability: string | null = null;
291
+ if (url.hash.startsWith('#cap=')) {
292
+ const value = url.hash.slice(5);
293
+ if (/^[a-f0-9]{64}$/.test(value))
294
+ capability = value;
295
+ url.hash = '';
296
+ replace(url.href);
297
+ try {
298
+ if (capability)
299
+ storage?.setItem(slot, capability);
300
+ }
301
+ catch { /* Memory-only capability when storage is denied. */ }
302
+ }
303
+ if (!capability) {
304
+ try {
305
+ const saved = storage?.getItem(slot);
306
+ if (saved && /^[a-f0-9]{64}$/.test(saved))
307
+ capability = saved;
308
+ }
309
+ catch { /* A copied link remains read-only. */ }
310
+ }
311
+ return {
312
+ jobId, base, capability,
313
+ route(path) {
314
+ if (path.startsWith('/') || /[\\\x00-\x20]/.test(path) || path.split('?')[0]!.split('/').some(part => part === '..' || part === '.')) {
315
+ throw new Error('JOB_REQUEST_INVALID');
316
+ }
317
+ return base + path;
318
+ },
319
+ headers(init) {
320
+ const headers = new Headers(init);
321
+ if (capability)
322
+ headers.set('X-Review-Capability', capability);
323
+ return headers;
324
+ },
325
+ };
326
+ }
327
+ /** Resolve only the publication's explicit immutable instance routes. */
328
+ export function jobPublicationRoutes(display: JobDisplayPublication, origin: string) {
329
+ const key = display.publication.instanceKey;
330
+ if (!/^[a-f0-9]{64}$/.test(key))
331
+ throw new Error('JOB_DISPLAY_MISMATCH');
332
+ const match = /^\/jobs\/([A-Za-z0-9][A-Za-z0-9._-]{0,127})\/publications\/([A-Za-z0-9][A-Za-z0-9._-]{0,127})\/instances\/([a-f0-9]{64})\/$/.exec(display.routes.entry);
333
+ if (!match || match[2] !== display.publication.publicationId || match[3] !== key) {
334
+ throw new Error('JOB_DISPLAY_MISMATCH');
335
+ }
336
+ const prefix = display.routes.entry;
337
+ function checked(path: string): URL {
338
+ if (!path.startsWith(prefix) || /[\\?#]/.test(path) || /%(?:2e|2f|5c)/i.test(path)) {
339
+ throw new Error('JOB_DISPLAY_MISMATCH');
340
+ }
341
+ const url = new URL(path, origin);
342
+ if (url.origin !== origin || !url.pathname.startsWith(prefix))
343
+ throw new Error('JOB_DISPLAY_MISMATCH');
344
+ return url;
345
+ }
346
+ const entry = checked(display.routes.entry);
347
+ const apiBase = checked(display.routes.apiBase);
348
+ const assetsBase = checked(display.routes.assetsBase);
349
+ if (!entry.pathname.endsWith('/') || !apiBase.pathname.endsWith('/') || !assetsBase.pathname.endsWith('/')) {
350
+ throw new Error('JOB_DISPLAY_MISMATCH');
351
+ }
352
+ return {
353
+ entry: entry.href,
354
+ api(path: string) {
355
+ if (!/^[A-Za-z0-9][A-Za-z0-9/._-]*$/.test(path) || path.includes('..'))
356
+ throw new Error('JOB_DISPLAY_MISMATCH');
357
+ return checked(apiBase.pathname + path).href;
358
+ },
359
+ asset(path: string) {
360
+ if (!path || path.split('/').some(part => !part || part === '.' || part === '..') || /[\\\x00-\x1f]/.test(path)) {
361
+ throw new Error('JOB_DISPLAY_MISMATCH');
362
+ }
363
+ return checked(assetsBase.pathname + path.split('/').map(encodeURIComponent).join('/')).href;
364
+ },
365
+ instance(path: string) {
366
+ if (!path.startsWith('/') || path.startsWith('//'))
367
+ throw new Error('JOB_DISPLAY_MISMATCH');
368
+ return checked(prefix + path.slice(1)).href;
369
+ },
370
+ assertAsset(url: string): string {
371
+ const requested = new URL(url);
372
+ const value = checked(requested.pathname);
373
+ if (requested.origin !== origin || requested.search || requested.hash || requested.username || requested.password ||
374
+ !value.pathname.startsWith(assetsBase.pathname)) {
375
+ throw new Error('JOB_DISPLAY_MISMATCH');
376
+ }
377
+ return value.href;
378
+ },
379
+ };
380
+ }
381
+ /** Raw UI-only mutations stay separate from the agent API. No capability is put in a URL. */
382
+ export function createJobWindowTransport(access: JobWindowAccess, fetcher: typeof fetch = fetch): JobWindowTransport {
383
+ async function read<Value>(path: string, init?: RequestInit): Promise<JobResult<Value>> {
384
+ const response = await fetcher(access.route(path), { ...init, headers: access.headers(init?.headers) });
385
+ const value = await response.json() as JobResult<Value>;
386
+ if (typeof value?.ok !== 'boolean')
387
+ throw new Error('JOB_REQUEST_INVALID');
388
+ if (!response.ok && value.ok)
389
+ throw new Error('JOB_REQUEST_INVALID');
390
+ return value;
391
+ }
392
+ function post<Value>(path: string, body: unknown, signal?: AbortSignal) {
393
+ return read<Value>(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), signal });
394
+ }
395
+ return {
396
+ readPublication: (id, signal) => read('publications/' + encodeURIComponent(id), { signal }),
397
+ acknowledge: (body, signal) => post('ui/displayed', body, signal),
398
+ submit: body => post('ui/acts', body),
399
+ };
400
+ }
401
+ /** Bounded newline events. Reconnects resume after the last fully parsed event. */
402
+ export async function* jobWindowEvents(access: JobWindowAccess, after: string | null, signal: AbortSignal, fetcher: typeof fetch = fetch): AsyncGenerator<JobEvent> {
403
+ const path = 'events' + (after === null ? '' : '?after=' + encodeURIComponent(after));
404
+ const response = await fetcher(access.route(path), { signal, headers: access.headers() });
405
+ if (!response.ok || !response.body)
406
+ throw new Error('JOB_STREAM_FAILED');
407
+ const reader = response.body.getReader();
408
+ const decoder = new TextDecoder('utf-8', { fatal: true });
409
+ let buffered = '';
410
+ const limit = 1024 * 1024;
411
+ try {
412
+ for (;;) {
413
+ const next = await reader.read();
414
+ if (next.done) {
415
+ buffered += decoder.decode();
416
+ if (buffered.length)
417
+ throw new Error('JOB_STREAM_INCOMPLETE');
418
+ return;
419
+ }
420
+ buffered += decoder.decode(next.value, { stream: true });
421
+ let newline = buffered.indexOf('\n');
422
+ while (newline >= 0) {
423
+ if (newline > limit)
424
+ throw new Error('JOB_BODY_LIMIT');
425
+ const event = JSON.parse(buffered.slice(0, newline)) as JobEvent;
426
+ if (!event || event.jobId !== access.jobId || typeof event.cursor !== 'string' ||
427
+ !Number.isSafeInteger(event.generation) || event.generation < 0 ||
428
+ !['published', 'pending', 'act', 'closed'].includes(event.type))
429
+ throw new Error('JOB_STREAM_FAILED');
430
+ buffered = buffered.slice(newline + 1);
431
+ yield event;
432
+ newline = buffered.indexOf('\n');
433
+ }
434
+ if (buffered.length > limit)
435
+ throw new Error('JOB_BODY_LIMIT');
436
+ }
437
+ }
438
+ finally {
439
+ void reader.cancel().catch(() => { });
440
+ reader.releaseLock();
441
+ }
442
+ }
443
+ import type { ModelAssets, RigPlayer } from '@rig-c/play';
444
+ import type { PartInspection } from './part-selection.ts';
445
+ import type { Checkpoint, ReviewManifest, ReviewedSource } from '../src/manifest.ts';
446
+ import type { DirectionInspection } from '../src/direction-inspection.ts';
447
+ import type { InterviewQuestion } from '../src/interview-project.ts';
448
+ export interface JobInspectionMetadata {
449
+ manifest: ReviewManifest;
450
+ sourceHash: string;
451
+ reviewedSource: ReviewedSource;
452
+ setsHash?: string;
453
+ initialAnimation?: string | null;
454
+ direction?: DirectionInspection;
455
+ referenceHashes?: Record<string, string>;
456
+ sourcePainting?: {
457
+ id: string;
458
+ path: string;
459
+ sha256: string;
460
+ url: string;
461
+ };
462
+ capabilities: {
463
+ interview?: boolean;
464
+ preRig?: boolean;
465
+ playback: boolean;
466
+ };
467
+ feedbackCatalog: {
468
+ slots: string[];
469
+ };
470
+ }
471
+ type JobInterview = {
472
+ questions: (Omit<InterviewQuestion, 'images'> & {
473
+ images: {
474
+ name: string;
475
+ url: string;
476
+ }[];
477
+ })[];
478
+ };
479
+ interface JobPartsInventory {
480
+ sourceHash: string;
481
+ rigSize: [
482
+ number,
483
+ number
484
+ ] | null;
485
+ items: {
486
+ name: string;
487
+ index: number;
488
+ x: number;
489
+ y: number;
490
+ w: number;
491
+ h: number;
492
+ imageHash?: string;
493
+ }[];
494
+ }
495
+ interface JobReferenceView {
496
+ id: string;
497
+ label: string;
498
+ element: HTMLImageElement | HTMLVideoElement | HTMLCanvasElement;
499
+ width: number;
500
+ height: number;
501
+ seek(time: number, signal: AbortSignal): Promise<void>;
502
+ }
503
+
504
+ /** A reference stays off-stage until its seek matches the latest inspection time. */
505
+ export function createJobReferenceSelection<Reference extends Pick<JobReferenceView, 'seek'>>(options: {
506
+ current(): {owner: object | null; time: number};
507
+ present(reference: Reference): void;
508
+ refused(error: unknown): void;
509
+ }) {
510
+ let intent = 0;
511
+ let controller: AbortController | null = null;
512
+ function cancel(): void {
513
+ intent++;
514
+ controller?.abort();
515
+ controller = null;
516
+ }
517
+ async function select(reference: Reference): Promise<void> {
518
+ cancel();
519
+ const revision = intent;
520
+ const owner = options.current().owner;
521
+ if (!owner) return;
522
+ const abort = new AbortController();
523
+ controller = abort;
524
+ let time = options.current().time;
525
+ try {
526
+ for (;;) {
527
+ await reference.seek(time, abort.signal);
528
+ const latest = options.current();
529
+ if (abort.signal.aborted || revision !== intent || latest.owner !== owner) return;
530
+ if (latest.time !== time) {
531
+ time = latest.time;
532
+ continue;
533
+ }
534
+ options.present(reference);
535
+ return;
536
+ }
537
+ } catch (error) {
538
+ if (!abort.signal.aborted && revision === intent && options.current().owner === owner)
539
+ options.refused(error);
540
+ }
541
+ }
542
+ return {select, cancel};
543
+ }
544
+
545
+ export interface JobPreparedInspection {
546
+ display: JobDisplayPublication;
547
+ metadata: JobInspectionMetadata;
548
+ interview: JobInterview | null;
549
+ parts: JobPartsInventory | null;
550
+ partImages: Map<string, HTMLImageElement>;
551
+ interviewImages: Map<string, HTMLImageElement>;
552
+ references: JobReferenceView[];
553
+ assets: ModelAssets | null;
554
+ player: RigPlayer | null;
555
+ rigRoot: HTMLElement;
556
+ inspection: PartInspection | null;
557
+ setupPose(): void;
558
+ dispose(): void;
559
+ }
560
+ async function jobBytes(url: string, signal: AbortSignal, maximum: number): Promise<Uint8Array<ArrayBuffer>> {
561
+ const response = await fetch(url, { signal });
562
+ if (!response.ok || !response.body)
563
+ throw new Error('JOB_PRELOAD_FAILED');
564
+ const reader = response.body.getReader();
565
+ const chunks: Uint8Array[] = [];
566
+ let size = 0;
567
+ try {
568
+ for (;;) {
569
+ const next = await reader.read();
570
+ if (next.done)
571
+ break;
572
+ size += next.value.length;
573
+ if (size > maximum)
574
+ throw new Error('JOB_BODY_LIMIT');
575
+ chunks.push(next.value);
576
+ }
577
+ }
578
+ finally {
579
+ void reader.cancel().catch(() => { });
580
+ reader.releaseLock();
581
+ }
582
+ const bytes = new Uint8Array(size);
583
+ let offset = 0;
584
+ for (const chunk of chunks) {
585
+ bytes.set(chunk, offset);
586
+ offset += chunk.length;
587
+ }
588
+ return bytes;
589
+ }
590
+ async function jobDigest(bytes: Uint8Array<ArrayBuffer>): Promise<string> {
591
+ return [...new Uint8Array(await crypto.subtle.digest('SHA-256', bytes))]
592
+ .map(value => value.toString(16).padStart(2, '0')).join('');
593
+ }
594
+ async function jobJson<Value>(url: string, signal: AbortSignal): Promise<Value> {
595
+ const bytes = await jobBytes(url, signal, 2 * 1024 * 1024);
596
+ return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)) as Value;
597
+ }
598
+ function mediaReady(media: HTMLVideoElement, name: 'loadeddata' | 'seeked', signal: AbortSignal): Promise<void> {
599
+ return new Promise((resolve, reject) => {
600
+ const finish = (error?: Error) => {
601
+ clearTimeout(timer);
602
+ media.removeEventListener(name, loaded);
603
+ media.removeEventListener('error', failed);
604
+ signal.removeEventListener('abort', failed);
605
+ if (error)
606
+ reject(error);
607
+ else
608
+ resolve();
609
+ };
610
+ const loaded = () => finish();
611
+ const failed = () => finish(new Error('JOB_VISUAL_UNAVAILABLE'));
612
+ const timer = setTimeout(failed, 10000);
613
+ media.addEventListener(name, loaded, { once: true });
614
+ media.addEventListener('error', failed, { once: true });
615
+ signal.addEventListener('abort', failed, { once: true });
616
+ if (signal.aborted)
617
+ failed();
618
+ });
619
+ }
620
+ /** Prepare the real published Play model, references and every form dependency off-stage. */
621
+ export async function prepareJobInspection(display: JobDisplayPublication, signal: AbortSignal): Promise<JobPreparedInspection> {
622
+ const routes = jobPublicationRoutes(display, location.origin);
623
+ const metadata = await jobJson<JobInspectionMetadata>(routes.api('review'), signal);
624
+ if (metadata.manifest.id !== display.publication.source.package.id ||
625
+ metadata.manifest.revision !== display.publication.source.package.revision ||
626
+ (metadata.reviewedSource.rig?.sha256 ?? null) !== (display.publication.source.model?.sha256 ?? null)) {
627
+ throw new Error('JOB_DISPLAY_MISMATCH');
628
+ }
629
+ const objectUrls: string[] = [];
630
+ const media: HTMLVideoElement[] = [];
631
+ const rigRoot = document.createElement('div');
632
+ rigRoot.id = 'rig-root';
633
+ let assets: ModelAssets | null = null;
634
+ let player: RigPlayer | null = null;
635
+ let inspection: PartInspection | null = null;
636
+ let resetToSetup = () => {};
637
+ let disposed = false;
638
+ const dispose = () => {
639
+ if (disposed)
640
+ return;
641
+ disposed = true;
642
+ for (const video of media) {
643
+ video.pause();
644
+ video.removeAttribute('src');
645
+ video.load();
646
+ }
647
+ player?.dispose();
648
+ assets?.dispose();
649
+ for (const url of objectUrls)
650
+ URL.revokeObjectURL(url);
651
+ };
652
+ async function visualBytes(url: string, hash?: string) {
653
+ const bytes = await jobBytes(url, signal, 128 * 1024 * 1024);
654
+ if (hash && await jobDigest(bytes) !== hash)
655
+ throw new Error('JOB_SOURCE_MISMATCH');
656
+ return bytes;
657
+ }
658
+ async function image(url: string, hash?: string): Promise<HTMLImageElement> {
659
+ const bytes = await visualBytes(url, hash);
660
+ const blob = URL.createObjectURL(new Blob([bytes.slice().buffer]));
661
+ objectUrls.push(blob);
662
+ const image = new Image();
663
+ image.src = blob;
664
+ await image.decode();
665
+ if (!image.naturalWidth || !image.naturalHeight || signal.aborted)
666
+ throw new Error('JOB_VISUAL_UNAVAILABLE');
667
+ return image;
668
+ }
669
+ try {
670
+ const interview = metadata.capabilities.interview ? await jobJson<JobInterview>(routes.api('interview'), signal) : null;
671
+ const parts = metadata.capabilities.preRig ? await jobJson<JobPartsInventory>(routes.api('stage-parts'), signal) : null;
672
+ const references: JobReferenceView[] = [];
673
+ const partImages = new Map<string, HTMLImageElement>();
674
+ const interviewImages = new Map<string, HTMLImageElement>();
675
+ const preload: Promise<void>[] = [];
676
+ for (const reference of metadata.manifest.references) {
677
+ preload.push((async () => {
678
+ if (reference.type === 'image') {
679
+ const element = await image(routes.asset(reference.path), metadata.referenceHashes?.[reference.id]);
680
+ element.alt = reference.label;
681
+ references.push({ id: reference.id, label: reference.label, element,
682
+ width: element.naturalWidth, height: element.naturalHeight, seek: async () => { } });
683
+ }
684
+ else if (reference.type === 'video') {
685
+ const bytes = await visualBytes(routes.asset(reference.path), metadata.referenceHashes?.[reference.id]);
686
+ const element = document.createElement('video');
687
+ media.push(element);
688
+ const blob = URL.createObjectURL(new Blob([bytes.slice().buffer]));
689
+ objectUrls.push(blob);
690
+ element.preload = 'auto';
691
+ element.muted = true;
692
+ element.playsInline = true;
693
+ const ready = mediaReady(element, 'loadeddata', signal);
694
+ element.src = blob;
695
+ await ready;
696
+ references.push({ id: reference.id, label: reference.label, element,
697
+ width: element.videoWidth, height: element.videoHeight,
698
+ async seek(time, abort) {
699
+ if (!Number.isFinite(time) || time < 0 || time > element.duration)
700
+ throw new Error('REFERENCE_OUT_OF_DOMAIN');
701
+ if (element.currentTime === time && element.readyState >= 2 && !element.seeking)
702
+ return;
703
+ const ready = mediaReady(element, 'seeked', abort);
704
+ element.currentTime = time;
705
+ await ready;
706
+ while (element.seeking) await mediaReady(element, 'seeked', abort);
707
+ } });
708
+ }
709
+ else {
710
+ // Pose references retain their own declared points. No inferred rig mapping.
711
+ const bytes = await visualBytes(routes.asset(reference.path), metadata.referenceHashes?.[reference.id]);
712
+ const pose = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
713
+ const element = document.createElement('canvas');
714
+ if (!Number.isSafeInteger(pose.width) || !Number.isSafeInteger(pose.height) || pose.width <= 0 || pose.height <= 0) {
715
+ throw new Error('JOB_VISUAL_UNAVAILABLE');
716
+ }
717
+ element.width = pose.width;
718
+ element.height = pose.height;
719
+ const context = element.getContext('2d');
720
+ if (!context)
721
+ throw new Error('JOB_VISUAL_UNAVAILABLE');
722
+ const draw = async (time: number) => {
723
+ context.clearRect(0, 0, element.width, element.height);
724
+ context.fillStyle = getComputedStyle(document.documentElement).getPropertyValue('--fg-strong');
725
+ if (pose.spec === 'rig-pose-sequence/1') {
726
+ const frames = pose.frames as {
727
+ t: number;
728
+ people: {
729
+ joints: Record<string, {
730
+ at?: [
731
+ number,
732
+ number
733
+ ];
734
+ }>;
735
+ }[];
736
+ }[];
737
+ const first = frames[0]?.t;
738
+ const frame = frames.filter(frame => frame.t - first <= time).at(-1);
739
+ if (!frame || time > frames.at(-1)!.t - first)
740
+ throw new Error('REFERENCE_OUT_OF_DOMAIN');
741
+ for (const person of frame.people)
742
+ for (const [name, joint] of Object.entries(person.joints)) {
743
+ if (!joint.at)
744
+ continue;
745
+ context.beginPath();
746
+ context.arc(joint.at[0], joint.at[1], 3, 0, Math.PI * 2);
747
+ context.fill();
748
+ context.fillText(name, joint.at[0] + 4, joint.at[1]);
749
+ }
750
+ }
751
+ else if (pose.schema === 'rig-review-pose/1') {
752
+ for (const joint of pose.joints as {
753
+ id: string;
754
+ x: number;
755
+ y: number;
756
+ }[]) {
757
+ context.beginPath();
758
+ context.arc(joint.x, joint.y, 3, 0, Math.PI * 2);
759
+ context.fill();
760
+ context.fillText(joint.id, joint.x + 4, joint.y);
761
+ }
762
+ }
763
+ else
764
+ throw new Error('JOB_VISUAL_UNAVAILABLE');
765
+ };
766
+ await draw(0);
767
+ references.push({ id: reference.id, label: reference.label, element,
768
+ width: element.width, height: element.height, seek: draw });
769
+ }
770
+ })());
771
+ }
772
+ if (metadata.sourcePainting) {
773
+ const source = metadata.sourcePainting;
774
+ preload.push(image(routes.instance(source.url), source.sha256).then(element => {
775
+ element.alt = source.path;
776
+ references.push({ id: source.id, label: source.path, element,
777
+ width: element.naturalWidth, height: element.naturalHeight, seek: async () => { } });
778
+ }));
779
+ }
780
+ for (const part of parts?.items ?? []) {
781
+ preload.push(image(routes.api('stage-parts/image/' + part.index), part.imageHash)
782
+ .then(element => { element.alt = part.name; partImages.set(part.name, element); }));
783
+ }
784
+ for (const question of interview?.questions ?? [])
785
+ for (const asset of question.images) {
786
+ preload.push(image(routes.instance(asset.url)).then(element => { element.alt = asset.name; interviewImages.set(asset.url, element); }));
787
+ }
788
+ const preloaded = await Promise.allSettled(preload);
789
+ const failed = preloaded.find(result => result.status === 'rejected');
790
+ if (failed?.status === 'rejected')
791
+ throw failed.reason;
792
+ if (metadata.manifest.model) {
793
+ const runtime = await import('@rig-c/play');
794
+ const modelUrl = routes.asset(metadata.manifest.model);
795
+ const modelHash = metadata.reviewedSource.rig!.sha256;
796
+ const setsUrl = metadata.manifest.sets ? routes.asset(metadata.manifest.sets) : null;
797
+ const checkedFetch = new Proxy(fetch, { apply: async (_target, _receiver, args: Parameters<typeof fetch>) => {
798
+ const url = String(args[0]);
799
+ const expected = url === modelUrl ? modelHash : url === setsUrl ? metadata.setsHash : null;
800
+ if (!expected)
801
+ throw new Error('JOB_SOURCE_MISMATCH');
802
+ const bytes = await visualBytes(url, expected);
803
+ return new Response(bytes);
804
+ } });
805
+ assets = await runtime.loadModel({ modelUrl, setsUrl, fetch: checkedFetch,
806
+ resolvePage: (name, url) => routes.assertAsset(new URL(name, url).href) });
807
+ const loadedAssets = assets;
808
+ const parts = await import('./part-selection.ts');
809
+ const catalog = await parts.loadPartModel(modelUrl, modelHash, metadata.feedbackCatalog.slots, checkedFetch);
810
+ resetToSetup = () => {
811
+ player?.dispose();
812
+ player = new runtime.RigPlayer(rigRoot, loadedAssets);
813
+ player.draw();
814
+ inspection = new parts.PartInspection();
815
+ inspection.register('single', catalog.entries, player);
816
+ inspection.present('single');
817
+ };
818
+ resetToSetup();
819
+ }
820
+ if (!player && !references.length && !partImages.size)
821
+ throw new Error('JOB_VISUAL_UNAVAILABLE');
822
+ if (signal.aborted)
823
+ throw new Error('JOB_PRELOAD_CANCELLED');
824
+ // Preloads can finish out of order. Restore the producer's declared display order.
825
+ const order = [metadata.sourcePainting?.id, ...metadata.manifest.references.map(reference => reference.id)];
826
+ references.sort((a, b) => order.indexOf(a.id) - order.indexOf(b.id));
827
+ return {
828
+ display, metadata, interview, parts, partImages, interviewImages, references, assets, rigRoot,
829
+ get player() { return player; },
830
+ get inspection() { return inspection; },
831
+ setupPose: () => resetToSetup(),
832
+ dispose,
833
+ };
834
+ }
835
+ catch (error) {
836
+ dispose();
837
+ throw error;
838
+ }
839
+ }
840
+ /** Browser mount is explicit so importing transaction helpers never starts an app. */
841
+ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
842
+ const [{ createViewportController, createViewportState }, { createRigViewportProvider }, { mountViewportPair }, i18n] = await Promise.all([
843
+ import('./viewport-controller.ts'), import('./rig-viewport-provider.ts'),
844
+ import('./viewport-pair.ts'), import('./i18n.ts'),
845
+ ]);
846
+ let storage: Storage | null = null;
847
+ try {
848
+ storage = sessionStorage;
849
+ }
850
+ catch { /* Capability stays in memory. */ }
851
+ const access = jobWindowAccess(location.href, storage, href => history.replaceState(history.state, '', href));
852
+ const pageId = crypto.randomUUID();
853
+ const transport = createJobWindowTransport(access);
854
+ const abort = new AbortController();
855
+ const language = new URL(location.href).searchParams.get('lang');
856
+ if (language === 'en' || language === 'ko')
857
+ i18n.setLanguagePreference(language);
858
+ const t = i18n.t;
859
+ const node = <Tag extends keyof HTMLElementTagNameMap>(tag: Tag, key?: string) => {
860
+ const value = document.createElement(tag);
861
+ if (key) {
862
+ value.dataset.jobText = key;
863
+ value.textContent = t(key);
864
+ }
865
+ return value;
866
+ };
867
+ const title = node('h1', 'job.title');
868
+ const languages = node('select');
869
+ for (const value of ['en', 'ko']) {
870
+ const option = node('option');
871
+ option.value = value;
872
+ option.textContent = value;
873
+ languages.append(option);
874
+ }
875
+ languages.value = i18n.getLanguage();
876
+ languages.setAttribute('aria-label', t('interview.language'));
877
+ languages.onchange = () => { i18n.setLinkLanguage(null); i18n.setLanguagePreference(languages.value === 'ko' ? 'ko' : 'en'); };
878
+ const header = node('header');
879
+ header.className = 'job-header';
880
+ header.append(title, languages);
881
+ const notice = node('p', 'job.waiting');
882
+ notice.className = 'job-notice';
883
+ notice.setAttribute('role', 'status');
884
+ const workspace = node('main');
885
+ host.classList.add('job-window');
886
+ host.replaceChildren(header, notice, workspace);
887
+ let current: JobPreparedInspection | null = null;
888
+ let currentElement: HTMLElement | null = null;
889
+ let animation = '';
890
+ let time = 0;
891
+ let selectedPart = '';
892
+ let partMode: 'context' | 'solo' = 'context';
893
+ let selectedReference = '';
894
+ let panel = '3';
895
+ let compatibilityNotice = false;
896
+ type JobForm = {
897
+ form: HTMLFormElement;
898
+ fieldset: HTMLFieldSetElement;
899
+ read: () => JobUISubmission['value'];
900
+ submissionId: string;
901
+ dirty: boolean;
902
+ };
903
+ type PreparedWindow = JobPreparedInspection & {
904
+ element: HTMLElement;
905
+ forms: Map<string, JobForm>;
906
+ };
907
+ const forms = new Map<string, JobForm>();
908
+ const viewportState = createViewportState();
909
+ const el = <Element extends HTMLElement = HTMLElement>(id: string): Element => {
910
+ const element = workspace.querySelector<HTMLElement>('#' + id);
911
+ if (!element)
912
+ throw new Error('JOB_WINDOW_ELEMENT_MISSING');
913
+ return element as Element;
914
+ };
915
+ const reference = () => current?.references.find(item => item.id === selectedReference) ?? null;
916
+ const setText = (id: string, value: string) => { const element = workspace.querySelector('#' + id); if (element)
917
+ element.textContent = i18n.tr(value); };
918
+ const provider = createRigViewportProvider({
919
+ el, player: () => current?.player ?? null, assets: () => current?.assets ?? null,
920
+ referenceSize: () => reference(), view: () => 'compare', referenceGeneration: () => current?.display.publication.generation ?? 0,
921
+ parts: () => current?.inspection ?? null, text: setText,
922
+ message: value => { notice.textContent = jobWindowRefusal(value); }, redrawOverlay: () => { },
923
+ }, viewportState);
924
+ const canonicalControls = provider.renderControls;
925
+ provider.renderControls = controller => {
926
+ canonicalControls(controller);
927
+ const fit = el('fit');
928
+ fit.textContent = t(fit.textContent ?? 'Fit');
929
+ };
930
+ const viewport = createViewportController(provider, viewportState);
931
+ const referenceSelection = createJobReferenceSelection<JobReferenceView>({
932
+ current: () => ({owner: current, time}),
933
+ present(value) {
934
+ const previous = selectedReference;
935
+ const camera = structuredClone(viewportState);
936
+ selectedReference = value.id;
937
+ try {
938
+ showReference();
939
+ el<HTMLSelectElement>('job-reference').value = value.id;
940
+ viewport.fitCamera();
941
+ } catch (error) {
942
+ selectedReference = previous;
943
+ Object.assign(viewportState, camera);
944
+ showReference();
945
+ el<HTMLSelectElement>('job-reference').value = previous;
946
+ viewport.fitCamera();
947
+ throw error;
948
+ }
949
+ },
950
+ refused(error) {
951
+ el<HTMLSelectElement>('job-reference').value = selectedReference;
952
+ notice.textContent = jobWindowRefusal(error, 'JOB_VISUAL_UNAVAILABLE');
953
+ },
954
+ });
955
+ let unbindNavigation: (() => void) | null = null;
956
+ let resize: ResizeObserver | null = null;
957
+ function localDraftKey(display: JobDisplayPublication): string {
958
+ return 'rig-review-job-draft/1:' + access.jobId + ':' + display.publication.publicationId + ':' + display.publication.source.sourceHash;
959
+ }
960
+ function saveDraft(): void {
961
+ if (!current)
962
+ return;
963
+ try {
964
+ localStorage.setItem(localDraftKey(current.display), JSON.stringify({
965
+ publicationId: current.display.publication.publicationId,
966
+ sourceHash: current.display.publication.source.sourceHash,
967
+ source: current.display.publication.source,
968
+ label: current.display.publication.label,
969
+ forms: [...forms].filter(([, item]) => item.dirty).map(([askId, item]) => ({
970
+ askId, value: item.read(),
971
+ controls: [...item.form.querySelectorAll<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>('input[name],textarea[name],select[name]')]
972
+ .map(input => ({ name: input.name, value: input.value })),
973
+ })),
974
+ }));
975
+ }
976
+ catch { /* The in-memory retained draft remains source-bound. */ }
977
+ }
978
+ function inputLabel(key: string, input: HTMLElement): HTMLElement {
979
+ const label = node('label');
980
+ label.append(node('span', key), input);
981
+ return label;
982
+ }
983
+ function selectValues(values: readonly string[], labels: readonly string[]): HTMLSelectElement {
984
+ const select = node('select');
985
+ values.forEach((value, index) => {
986
+ const option = node('option', labels[index]);
987
+ option.value = value;
988
+ select.append(option);
989
+ });
990
+ return select;
991
+ }
992
+ function textArea(parent: HTMLElement, key: string, name = 'note'): HTMLTextAreaElement {
993
+ const input = node('textarea');
994
+ input.name = name;
995
+ parent.append(inputLabel(key, input));
996
+ return input;
997
+ }
998
+ function formFor(ask: JobPendingAsk, prepared: JobPreparedInspection): JobForm {
999
+ if (ask.publicationId !== prepared.display.publication.publicationId)
1000
+ throw new Error('JOB_DISPLAY_MISMATCH');
1001
+ assertJobAskSource(ask, prepared.display);
1002
+ const form = node('form');
1003
+ form.dataset.jobAsk = ask.askId;
1004
+ const fields = node('fieldset');
1005
+ form.append(fields);
1006
+ const source = node('p');
1007
+ source.className = 'job-source';
1008
+ source.textContent = prepared.display.publication.label + ' · ' + ask.source.sourceHash;
1009
+ fields.append(source);
1010
+ const note = textArea(fields, 'interview.note');
1011
+ let read: () => JobUISubmission['value'];
1012
+ let submitKey = 'Submit review';
1013
+ const subject = ask.subject;
1014
+ if (subject.kind === 'interview-picks') {
1015
+ const question = prepared.interview?.questions.find(item => item.set.id === subject.setId && item.set.question === subject.questionId);
1016
+ if (!question || !question.editable) throw new Error('JOB_ASK_INVALID');
1017
+ if (question.ref.sha256 !== ask.source.optionSet?.sha256) throw new Error('JOB_ACT_SOURCE_STALE');
1018
+ const heading = node('h3');
1019
+ heading.textContent = question.set.question;
1020
+ fields.prepend(heading);
1021
+ const answers = question.set.asks.map(item => {
1022
+ const group = node('fieldset');
1023
+ const legend = node('legend');
1024
+ legend.textContent = item.prompt;
1025
+ group.append(legend);
1026
+ const pick = node('select');
1027
+ pick.required = true;
1028
+ pick.name = 'choice.' + item.id;
1029
+ const empty = node('option', 'job.choose');
1030
+ empty.value = '';
1031
+ pick.append(empty);
1032
+ for (const choice of item.options) {
1033
+ const option = node('option');
1034
+ option.value = choice.id;
1035
+ option.textContent = choice.label + ' · ' + choice.effect;
1036
+ pick.append(option);
1037
+ }
1038
+ const other = node('textarea');
1039
+ other.hidden = true;
1040
+ other.name = 'other.' + item.id;
1041
+ const warning = node('p');
1042
+ warning.hidden = true;
1043
+ pick.onchange = () => {
1044
+ const choice = item.options.find(option => option.id === pick.value);
1045
+ other.hidden = choice?.kind !== 'other';
1046
+ other.required = choice?.kind === 'other';
1047
+ warning.hidden = choice?.kind === 'value';
1048
+ warning.textContent = t(choice?.kind === 'other' ? 'interview.otherPending' : 'interview.autoPending');
1049
+ };
1050
+ group.append(pick, other, warning);
1051
+ fields.append(group);
1052
+ return { item, pick, other };
1053
+ });
1054
+ for (const image of question.images) {
1055
+ const visual = prepared.interviewImages.get(image.url);
1056
+ if (!visual)
1057
+ throw new Error('JOB_VISUAL_UNAVAILABLE');
1058
+ fields.append(visual.cloneNode(true));
1059
+ }
1060
+ read = () => ({ questionId: subject.questionId,
1061
+ selections: answers.map(({ item, pick, other }) => ({ itemId: item.id, optionId: pick.value,
1062
+ otherText: item.options.find(option => option.id === pick.value)?.kind === 'other' ? other.value : null })), note: note.value });
1063
+ submitKey = 'interview.save';
1064
+ }
1065
+ else if (subject.kind === 'checkpoint') {
1066
+ const checkpoint = jobCheckpointContext(ask, prepared.metadata.manifest.checkpoints);
1067
+ const heading = node('h3');
1068
+ heading.textContent = checkpoint.title;
1069
+ fields.prepend(heading);
1070
+ const guidance = node('p');
1071
+ guidance.textContent = checkpoint.note;
1072
+ const planStep = node('p');
1073
+ planStep.className = 'job-source';
1074
+ planStep.textContent = checkpoint.step.id + ' · ' + checkpoint.step.hash;
1075
+ fields.append(planStep, guidance);
1076
+ const outcome = selectValues(['', 'pass', 'fail'], ['Pending', 'Pass', 'job.fail']);
1077
+ outcome.required = true;
1078
+ outcome.name = 'outcome';
1079
+ fields.append(outcome);
1080
+ read = () => ({ checkpointId: subject.checkpointId, outcome: outcome.value as 'pass' | 'fail', words: note.value });
1081
+ submitKey = 'job.saveCheckpoint';
1082
+ }
1083
+ else if (subject.kind === 'parts-verdict') {
1084
+ if (!prepared.parts)
1085
+ throw new Error('JOB_ASK_INVALID');
1086
+ const verdict = selectValues(['pending', 'approved', 'changes-requested'], ['Pending', 'Approved', 'Changes requested']);
1087
+ verdict.name = 'verdict';
1088
+ fields.append(verdict);
1089
+ const parts = prepared.parts.items.map(part => {
1090
+ const group = node('fieldset');
1091
+ const legend = node('legend');
1092
+ legend.textContent = part.name;
1093
+ group.append(legend);
1094
+ const partOutcome = selectValues(['pending', 'clean', 'flagged'], ['Pending', 'Clean', 'Flagged']);
1095
+ const meshOutcome = selectValues(['pending', 'clean', 'flagged'], ['Pending', 'Clean', 'Flagged']);
1096
+ partOutcome.name = 'parts.' + part.name + '.outcome';
1097
+ meshOutcome.name = 'mesh.' + part.name + '.outcome';
1098
+ group.append(inputLabel('Parts', partOutcome));
1099
+ const partNote = textArea(group, 'Note', 'parts.' + part.name + '.note');
1100
+ group.append(inputLabel('Mesh', meshOutcome));
1101
+ const meshNote = textArea(group, 'Note', 'mesh.' + part.name + '.note');
1102
+ fields.append(group);
1103
+ return { partId: part.name, partOutcome, meshOutcome, partNote, meshNote };
1104
+ });
1105
+ read = () => ({ verdict: verdict.value as 'pending' | 'approved' | 'changes-requested', words: note.value,
1106
+ parts: parts.map(part => ({ partId: part.partId,
1107
+ part: { outcome: part.partOutcome.value as 'pending' | 'clean' | 'flagged', note: part.partNote.value },
1108
+ mesh: { outcome: part.meshOutcome.value as 'pending' | 'clean' | 'flagged', note: part.meshNote.value } })) });
1109
+ submitKey = 'job.savePartsVerdict';
1110
+ }
1111
+ else if (subject.kind === 'review-verdict') {
1112
+ const verdict = selectValues(['pending', 'approved', 'changes-requested'], ['Pending', 'Approved', 'Changes requested']);
1113
+ verdict.name = 'verdict';
1114
+ fields.append(verdict);
1115
+ read = () => ({ stage: subject.stage, verdict: verdict.value as 'pending' | 'approved' | 'changes-requested', words: note.value });
1116
+ }
1117
+ else if (subject.kind === 'signoff') {
1118
+ const stage = node('p');
1119
+ stage.textContent = subject.stage;
1120
+ fields.append(stage);
1121
+ read = () => ({ stage: subject.stage, decision: 'approved', words: note.value });
1122
+ submitKey = 'job.signoff';
1123
+ }
1124
+ else {
1125
+ throw new Error('JOB_ACT_KIND_DISABLED');
1126
+ }
1127
+ const submit = node('button', submitKey);
1128
+ submit.type = 'submit';
1129
+ fields.append(submit);
1130
+ const status = node('p');
1131
+ status.setAttribute('role', 'status');
1132
+ form.append(status);
1133
+ const entry = { form, fieldset: fields, read, submissionId: crypto.randomUUID(), dirty: false };
1134
+ try {
1135
+ const saved = JSON.parse(localStorage.getItem(localDraftKey(prepared.display)) ?? 'null');
1136
+ if (saved?.publicationId === prepared.display.publication.publicationId &&
1137
+ saved?.sourceHash === prepared.display.publication.source.sourceHash) {
1138
+ const original = saved.forms?.find((item: {
1139
+ askId: string;
1140
+ }) => item.askId === ask.askId);
1141
+ for (const input of form.querySelectorAll<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>('input[name],textarea[name],select[name]')) {
1142
+ const restored = original?.controls?.find((item: {
1143
+ name: string;
1144
+ value: string;
1145
+ }) => item.name === input.name);
1146
+ if (restored && typeof restored.value === 'string') {
1147
+ input.value = restored.value;
1148
+ if (input instanceof HTMLSelectElement)
1149
+ input.dispatchEvent(new Event('change'));
1150
+ }
1151
+ }
1152
+ entry.dirty = !!original;
1153
+ }
1154
+ }
1155
+ catch { /* Invalid or unavailable local drafts grant no submission authority. */ }
1156
+ form.oninput = () => { entry.dirty = true; entry.submissionId = crypto.randomUUID(); saveDraft(); };
1157
+ form.onsubmit = async (event) => {
1158
+ event.preventDefault();
1159
+ const state = window.state();
1160
+ const receipt = state.receipt;
1161
+ if (!receipt || state.preparing || state.closed || !access.capability || !form.reportValidity())
1162
+ return;
1163
+ fields.disabled = true;
1164
+ try {
1165
+ const result = await window.submit({ kind: subject.kind, publicationId: ask.publicationId,
1166
+ askId: ask.askId, pageId, displayedNonce: receipt.displayedNonce,
1167
+ expectedGeneration: state.generation, submissionId: entry.submissionId, value: read() } as JobUISubmission);
1168
+ if (!result.ok)
1169
+ throw new Error(result.error.code);
1170
+ entry.dirty = false;
1171
+ status.textContent = t('job.saved');
1172
+ saveDraft();
1173
+ }
1174
+ catch (error) {
1175
+ status.textContent = jobWindowRefusal(error, 'JOB_ACT_INVALID');
1176
+ fields.disabled = false;
1177
+ }
1178
+ };
1179
+ return entry;
1180
+ }
1181
+ function updateForms(state: JobWindowState): void {
1182
+ if (!current)
1183
+ return;
1184
+ const host = workspace.querySelector<HTMLElement>('[data-job-forms]');
1185
+ if (!host)
1186
+ return;
1187
+ for (const ask of state.pending) {
1188
+ if (ask.publicationId !== current.display.publication.publicationId)
1189
+ continue;
1190
+ let entry = forms.get(ask.askId);
1191
+ if (!entry && ask.status === 'pending') {
1192
+ try {
1193
+ entry = formFor(ask, current);
1194
+ forms.set(ask.askId, entry);
1195
+ host.append(entry.form);
1196
+ }
1197
+ catch (error) {
1198
+ const refusal = node('p');
1199
+ refusal.textContent = jobWindowRefusal(error, 'JOB_ASK_INVALID');
1200
+ host.append(refusal);
1201
+ }
1202
+ }
1203
+ if (entry)
1204
+ entry.fieldset.disabled = ask.status !== 'pending' || state.preparing || state.closed || !state.receipt || !access.capability;
1205
+ }
1206
+ }
1207
+ function build(prepared: JobPreparedInspection): HTMLElement {
1208
+ const root = node('div');
1209
+ root.className = 'job-inspection';
1210
+ const sidebar = node('section');
1211
+ sidebar.className = 'job-sidebar';
1212
+ const identity = node('p');
1213
+ identity.className = 'job-source';
1214
+ identity.textContent = prepared.display.publication.label + '\n' + prepared.display.publication.source.sourceHash;
1215
+ sidebar.append(identity);
1216
+ const binding = node('details');
1217
+ const bindingTitle = node('summary', 'job.binding');
1218
+ const sourceBinding = node('pre');
1219
+ sourceBinding.className = 'job-source';
1220
+ sourceBinding.textContent = JSON.stringify(prepared.display.publication.source, null, 2);
1221
+ binding.append(bindingTitle, sourceBinding);
1222
+ sidebar.append(binding);
1223
+ const parts = node('select');
1224
+ parts.id = 'job-part';
1225
+ const whole = node('option', 'job.wholeRig');
1226
+ whole.value = '';
1227
+ parts.append(whole);
1228
+ for (const slot of prepared.metadata.feedbackCatalog.slots) {
1229
+ const option = node('option');
1230
+ option.value = slot;
1231
+ option.textContent = slot;
1232
+ parts.append(option);
1233
+ }
1234
+ parts.onchange = () => { selectedPart = parts.value; selectPart(); };
1235
+ sidebar.append(inputLabel('Parts', parts));
1236
+ const solo = node('input');
1237
+ solo.type = 'checkbox';
1238
+ solo.id = 'job-solo';
1239
+ solo.onchange = () => { partMode = solo.checked ? 'solo' : 'context'; selectPart(); };
1240
+ sidebar.append(inputLabel('Solo', solo));
1241
+ const observation = node('pre');
1242
+ observation.id = 'job-part-observation';
1243
+ observation.className = 'job-source';
1244
+ sidebar.append(observation);
1245
+ const referenceSelect = node('select');
1246
+ referenceSelect.id = 'job-reference';
1247
+ for (const reference of prepared.references) {
1248
+ const option = node('option');
1249
+ option.value = reference.id;
1250
+ option.textContent = reference.label;
1251
+ referenceSelect.append(option);
1252
+ }
1253
+ referenceSelect.onchange = () => {
1254
+ const next = prepared.references.find(item => item.id === referenceSelect.value);
1255
+ if (current === prepared && next) void referenceSelection.select(next);
1256
+ };
1257
+ sidebar.append(inputLabel('Reference', referenceSelect));
1258
+ const images = node('div');
1259
+ images.className = 'job-part-images';
1260
+ for (const [name, image] of prepared.partImages) {
1261
+ const label = node('label');
1262
+ const title = node('span');
1263
+ title.textContent = name;
1264
+ label.append(title, image);
1265
+ images.append(label);
1266
+ }
1267
+ sidebar.append(images);
1268
+ const stage = node('section');
1269
+ stage.className = 'job-stage';
1270
+ const controls = node('div');
1271
+ controls.className = 'viewbar';
1272
+ for (const [id, key] of [['zoom-in', 'job.zoomIn'], ['zoom-out', 'job.zoomOut'], ['fit', 'Fit']]) {
1273
+ const button = node('button', key);
1274
+ button.id = id!;
1275
+ button.type = 'button';
1276
+ controls.append(button);
1277
+ }
1278
+ const sync = node('input');
1279
+ sync.id = 'camera-sync';
1280
+ sync.type = 'checkbox';
1281
+ controls.append(inputLabel('job.cameraSync', sync));
1282
+ const zoom = node('span');
1283
+ zoom.id = 'zoom-value';
1284
+ controls.append(zoom);
1285
+ const pair = node('div');
1286
+ pair.id = 'stage-layout';
1287
+ mountViewportPair(pair);
1288
+ for (const id of ['rig-overlay', 'idle-handles', 'rig-fields-stage'])
1289
+ pair.querySelector('#' + id)?.remove();
1290
+ for (const [id, key] of [['reference-label', 'Reference'], ['rig-label', 'Generated rig · read only'],
1291
+ ['reference-empty', 'No reference supplied.'], ['rig-empty', 'No compiled model supplied.']]) {
1292
+ const label = pair.querySelector<HTMLElement>('#' + id);
1293
+ if (label) {
1294
+ label.dataset.jobText = key;
1295
+ label.textContent = t(key!);
1296
+ }
1297
+ }
1298
+ pair.querySelector('#reference-pane')?.setAttribute('aria-label', t('Reference'));
1299
+ pair.querySelector('#rig-pane')?.setAttribute('aria-label', t('Rig'));
1300
+ pair.querySelector('#rig-root')!.replaceWith(prepared.rigRoot);
1301
+ const transport = node('div');
1302
+ transport.className = 'job-transport';
1303
+ const clips = node('select');
1304
+ clips.id = 'job-animation';
1305
+ const setup = node('option', 'Setup');
1306
+ setup.value = '';
1307
+ clips.append(setup);
1308
+ for (const clip of prepared.assets?.animations ?? []) {
1309
+ const option = node('option');
1310
+ option.value = clip.name;
1311
+ option.textContent = clip.name;
1312
+ clips.append(option);
1313
+ }
1314
+ clips.onchange = () => { animation = clips.value; time = 0; pose(); };
1315
+ const clock = node('input');
1316
+ clock.id = 'job-time';
1317
+ clock.type = 'number';
1318
+ clock.min = '0';
1319
+ clock.step = '0.001';
1320
+ clock.onchange = () => {
1321
+ const value = Number(clock.value);
1322
+ const duration = current?.assets?.animations.find(clip => clip.name === animation)?.duration;
1323
+ if (!Number.isFinite(value) || value < 0 || duration !== undefined && value > duration) {
1324
+ clock.value = String(time);
1325
+ notice.textContent = t('KEY_TIME_OUT_OF_DOMAIN');
1326
+ return;
1327
+ }
1328
+ time = value;
1329
+ pose();
1330
+ };
1331
+ const panels = selectValues(['1', '2', '3', '4'], ['1 Parts + mesh', '2 Interview', '3 Rig + animation', '4 Direction']);
1332
+ panels.id = 'job-panel';
1333
+ panels.onchange = () => { panel = panels.value; showPanel(); };
1334
+ transport.append(clips, inputLabel('job.time', clock), panels);
1335
+ const numeric = node('pre');
1336
+ numeric.id = 'view-coordinates';
1337
+ numeric.hidden = true;
1338
+ const coordinates = node('span');
1339
+ coordinates.id = 'coordinates';
1340
+ coordinates.hidden = true;
1341
+ stage.append(controls, pair, transport, numeric, coordinates);
1342
+ const formsHost = node('section');
1343
+ formsHost.className = 'job-forms';
1344
+ formsHost.dataset.jobForms = '';
1345
+ const heading = node('h2', 'job.pending');
1346
+ formsHost.append(heading);
1347
+ const direction = node('pre');
1348
+ direction.className = 'job-direction';
1349
+ direction.dataset.jobDirection = '';
1350
+ if (prepared.metadata.direction)
1351
+ direction.textContent = t('job.metadata') + '\n' + JSON.stringify(prepared.metadata.direction, null, 2);
1352
+ const history = node('div');
1353
+ history.className = 'job-history';
1354
+ history.dataset.jobHistory = '';
1355
+ formsHost.append(direction, history);
1356
+ root.append(sidebar, stage, formsHost);
1357
+ return root;
1358
+ }
1359
+ function selectPart(): void {
1360
+ if (!current?.inspection)
1361
+ return;
1362
+ current.inspection.select(selectedPart ? { side: 'single', slot: selectedPart, mode: partMode } : null);
1363
+ setText('job-part-observation', selectedPart ? JSON.stringify(current.inspection.observation(), null, 2) : '');
1364
+ viewport.renderCameraControls();
1365
+ }
1366
+ function showReference(): void {
1367
+ const value = reference();
1368
+ el('reference-content').replaceChildren(...(value ? [value.element] : []));
1369
+ el('reference-empty').hidden = !!value;
1370
+ }
1371
+ function showPanel(): void {
1372
+ const direction = workspace.querySelector<HTMLElement>('[data-job-direction]');
1373
+ if (direction)
1374
+ direction.hidden = panel !== '4';
1375
+ for (const [askId, entry] of forms) {
1376
+ const ask = window.state().pending.find(item => item.askId === askId);
1377
+ entry.form.hidden = panel === '2' && ask?.subject.kind !== 'interview-picks';
1378
+ }
1379
+ }
1380
+ function pose(seekReference = true): void {
1381
+ if (!current)
1382
+ return;
1383
+ const clip = current.assets?.animations.find(item => item.name === animation);
1384
+ const clock = el<HTMLInputElement>('job-time');
1385
+ clock.value = String(time);
1386
+ if (animation && (!clip || time > clip.duration)) {
1387
+ notice.textContent = t('KEY_TIME_OUT_OF_DOMAIN');
1388
+ return;
1389
+ }
1390
+ if (!animation && current.player?.current) current.setupPose();
1391
+ if (current.player) {
1392
+ if (animation && current.player.current !== animation)
1393
+ current.player.play(animation, { loop: true });
1394
+ if (animation)
1395
+ current.player.seek(time);
1396
+ current.player.pause();
1397
+ current.player.draw();
1398
+ current.inspection?.present('single');
1399
+ current.inspection?.select(selectedPart ? { side: 'single', slot: selectedPart, mode: partMode } : null);
1400
+ setText('job-part-observation', selectedPart ? JSON.stringify(current.inspection?.observation(), null, 2) : '');
1401
+ }
1402
+ if (seekReference) {
1403
+ const value = reference();
1404
+ const owner = current;
1405
+ const at = time;
1406
+ void value?.seek(at, abort.signal).catch(error => {
1407
+ if (current === owner && reference() === value && time === at)
1408
+ notice.textContent = jobWindowRefusal(error, 'JOB_VISUAL_UNAVAILABLE');
1409
+ });
1410
+ }
1411
+ viewport.fitCamera();
1412
+ }
1413
+ const window = createJobWindow({ jobId: access.jobId, pageId, transport, adapter: {
1414
+ async prepare(display, signal): Promise<PreparedWindow> {
1415
+ const inspection = await prepareJobInspection(display, signal);
1416
+ try {
1417
+ const element = build(inspection);
1418
+ const preparedForms = prepareJobForms(display, window.state().pending, ask => formFor(ask, inspection));
1419
+ return Object.assign(inspection, { element, forms: preparedForms });
1420
+ }
1421
+ catch (error) {
1422
+ inspection.dispose();
1423
+ throw error;
1424
+ }
1425
+ },
1426
+ captureDraft() { saveDraft(); const dirty = [...forms].filter(([, item]) => item.dirty); return dirty.length ? dirty.map(([askId, item]) => ({ askId, value: item.read() })) : null; },
1427
+ commit(prepared, display) {
1428
+ // Pending asks can arrive while assets load. Finish their forms before the visible replacement.
1429
+ const nextForms = prepareJobForms(display, window.state().pending,
1430
+ ask => prepared.forms.get(ask.askId) ?? formFor(ask, prepared));
1431
+ const root = prepared.element;
1432
+ const formHost = root.querySelector<HTMLElement>('[data-job-forms]');
1433
+ if (!formHost) throw new Error('JOB_WINDOW_ELEMENT_MISSING');
1434
+ for (const entry of nextForms.values()) formHost.append(entry.form);
1435
+ referenceSelection.cancel();
1436
+ const previous = current;
1437
+ const previousElement = currentElement;
1438
+ const previousForms = new Map(forms);
1439
+ const navigation = { animation, time, selectedPart, partMode, selectedReference, panel,
1440
+ partIdentity: current?.inspection?.value(), camera: structuredClone(viewportState) };
1441
+ compatibilityNotice = false;
1442
+ if (animation && !prepared.assets?.animations.some(item => item.name === animation && time <= item.duration)) {
1443
+ animation = '';
1444
+ time = 0;
1445
+ compatibilityNotice = true;
1446
+ }
1447
+ if (selectedPart && !prepared.metadata.feedbackCatalog.slots.includes(selectedPart)) {
1448
+ selectedPart = '';
1449
+ compatibilityNotice = true;
1450
+ }
1451
+ if (!prepared.references.some(item => item.id === selectedReference))
1452
+ selectedReference = prepared.references[0]?.id ?? '';
1453
+ let nextUnbind: (() => void) | null = null;
1454
+ let nextResize: ResizeObserver | null = null;
1455
+ const rollback = () => {
1456
+ nextUnbind?.();
1457
+ nextResize?.disconnect();
1458
+ current = previous;
1459
+ currentElement = previousElement;
1460
+ animation = navigation.animation;
1461
+ time = navigation.time;
1462
+ selectedPart = navigation.selectedPart;
1463
+ partMode = navigation.partMode;
1464
+ selectedReference = navigation.selectedReference;
1465
+ panel = navigation.panel;
1466
+ forms.clear();
1467
+ for (const [id, item] of previousForms)
1468
+ forms.set(id, item);
1469
+ workspace.replaceChildren(...(previousElement ? [previousElement] : []));
1470
+ Object.assign(viewportState, navigation.camera);
1471
+ if (current) {
1472
+ el<HTMLSelectElement>('job-reference').value = selectedReference;
1473
+ viewport.fitCamera();
1474
+ }
1475
+ };
1476
+ try {
1477
+ current = prepared;
1478
+ currentElement = root;
1479
+ forms.clear();
1480
+ for (const [id, entry] of nextForms) forms.set(id, entry);
1481
+ workspace.replaceChildren(root);
1482
+ el<HTMLSelectElement>('job-part').value = selectedPart;
1483
+ el<HTMLInputElement>('job-solo').checked = partMode === 'solo';
1484
+ el<HTMLSelectElement>('job-reference').value = selectedReference;
1485
+ el<HTMLSelectElement>('job-animation').value = animation;
1486
+ el<HTMLSelectElement>('job-panel').value = panel;
1487
+ el('rig-empty').hidden = !!prepared.player;
1488
+ Object.assign(viewportState, navigation.camera, { cameraRestoring: true });
1489
+ showReference();
1490
+ pose(false);
1491
+ if (selectedPart) {
1492
+ try {
1493
+ prepared.inspection?.assertIdentity(navigation.partIdentity);
1494
+ }
1495
+ catch {
1496
+ selectedPart = '';
1497
+ compatibilityNotice = true;
1498
+ el<HTMLSelectElement>('job-part').value = '';
1499
+ }
1500
+ }
1501
+ selectPart();
1502
+ viewportState.cameraRestoring = false;
1503
+ updateForms(window.state());
1504
+ showPanel();
1505
+ viewport.bindControls();
1506
+ nextUnbind = viewport.bindNavigation();
1507
+ nextResize = viewport.observeResize();
1508
+ return {
1509
+ rollback,
1510
+ finalize() {
1511
+ unbindNavigation?.();
1512
+ resize?.disconnect();
1513
+ unbindNavigation = nextUnbind;
1514
+ resize = nextResize;
1515
+ previous?.dispose();
1516
+ title.textContent = display.publication.source.package.id;
1517
+ },
1518
+ };
1519
+ }
1520
+ catch (error) {
1521
+ rollback();
1522
+ throw error;
1523
+ }
1524
+ },
1525
+ async painted(prepared, signal) {
1526
+ await reference()?.seek(time, signal);
1527
+ if (prepared.player) {
1528
+ prepared.player.draw();
1529
+ prepared.inspection?.present('single');
1530
+ }
1531
+ await new Promise<void>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
1532
+ if (signal.aborted)
1533
+ throw new Error('JOB_PRELOAD_CANCELLED');
1534
+ },
1535
+ discard(prepared) { prepared.dispose(); },
1536
+ changed(state) {
1537
+ notice.dataset.failed = String(!!state.error);
1538
+ if (state.error)
1539
+ notice.textContent = state.displayed && state.error !== 'JOB_WINDOW_CLEANUP_FAILED'
1540
+ ? t('job.failed') + ' · ' + jobWindowRefusal(state.error) : jobWindowRefusal(state.error);
1541
+ else if (state.closed)
1542
+ notice.textContent = t('job.closed');
1543
+ else if (state.preparing)
1544
+ notice.textContent = t('job.preparing');
1545
+ else if (state.displayed)
1546
+ notice.textContent = state.previousLabel
1547
+ ? t('job.updated', [state.previousLabel, state.displayed.publication.label]) : state.displayed.publication.label;
1548
+ if (compatibilityNotice)
1549
+ notice.textContent += ' · ' + t('job.incompatible');
1550
+ updateForms(state);
1551
+ if (current)
1552
+ showPanel();
1553
+ const history = workspace.querySelector<HTMLElement>('[data-job-history]');
1554
+ if (history) {
1555
+ const retained = new Map(state.retainedDrafts.map(draft => [draft.publicationId, draft]));
1556
+ try {
1557
+ const prefix = 'rig-review-job-draft/1:' + access.jobId + ':';
1558
+ for (let index = 0; index < localStorage.length; index++) {
1559
+ const key = localStorage.key(index);
1560
+ if (!key?.startsWith(prefix))
1561
+ continue;
1562
+ const saved = JSON.parse(localStorage.getItem(key) ?? 'null');
1563
+ if (!saved?.forms?.length || saved.publicationId === state.displayed?.publication.publicationId)
1564
+ continue;
1565
+ if (typeof saved.publicationId !== 'string' || typeof saved.sourceHash !== 'string' || typeof saved.label !== 'string')
1566
+ continue;
1567
+ retained.set(saved.publicationId, { publicationId: saved.publicationId, sourceHash: saved.sourceHash,
1568
+ source: saved.source, label: saved.label, value: saved.forms });
1569
+ }
1570
+ }
1571
+ catch { /* In-memory retained evidence remains available. */ }
1572
+ history.textContent = [...retained.values()].map(draft => t('job.retained', [draft.label]) + '\n' + draft.sourceHash + '\n' + JSON.stringify(draft.value, null, 2)).join('\n');
1573
+ }
1574
+ },
1575
+ } });
1576
+ const localize = i18n.onLanguageChange(() => {
1577
+ for (const element of host.querySelectorAll<HTMLElement>('[data-job-text]'))
1578
+ element.textContent = t(element.dataset.jobText!);
1579
+ languages.setAttribute('aria-label', t('interview.language'));
1580
+ if (current)
1581
+ viewport.renderCameraControls();
1582
+ window.refresh();
1583
+ });
1584
+ let cursor: string | null = null;
1585
+ void (async () => {
1586
+ while (!abort.signal.aborted) {
1587
+ try {
1588
+ for await (const event of jobWindowEvents(access, cursor, abort.signal)) {
1589
+ cursor = event.cursor;
1590
+ window.event(event);
1591
+ if (event.type === 'closed')
1592
+ return;
1593
+ }
1594
+ }
1595
+ catch (error) {
1596
+ if (abort.signal.aborted)
1597
+ return;
1598
+ notice.textContent = jobWindowRefusal(error, 'JOB_STREAM_FAILED');
1599
+ }
1600
+ await new Promise<void>(resolve => setTimeout(resolve, 500));
1601
+ }
1602
+ })();
1603
+ const stop = () => {
1604
+ saveDraft();
1605
+ referenceSelection.cancel();
1606
+ abort.abort();
1607
+ window.stop();
1608
+ localize();
1609
+ unbindNavigation?.();
1610
+ resize?.disconnect();
1611
+ current?.dispose();
1612
+ };
1613
+ globalThis.addEventListener('pagehide', stop, { once: true });
1614
+ return () => { globalThis.removeEventListener('pagehide', stop); stop(); };
1615
+ }
1616
+ if (typeof document !== 'undefined' && document.body?.hasAttribute('data-job-window')) {
1617
+ void mountJobSession(document.body).catch(error => {
1618
+ const status = document.createElement('p');
1619
+ status.setAttribute('role', 'alert');
1620
+ status.textContent = jobWindowRefusal(error);
1621
+ document.body.append(status);
1622
+ });
1623
+ }