rig-review 2.1.0 → 2.3.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.
package/web/job-hub.ts ADDED
@@ -0,0 +1,179 @@
1
+ /** Owner-only job selection. Each retained frame owns its existing job window and draft. */
2
+ import type {JobHubList, JobHubRow} from '../src/job-hub.ts';
3
+
4
+ export const JOB_HUB_READY = 'rig-review-job-hub-ready/1';
5
+ export const JOB_HUB_VISIBILITY = 'rig-review-job-hub-visibility/1';
6
+ export interface JobHubBinding {
7
+ incarnation: string;
8
+ jobId: string;
9
+ publicationId: string | null;
10
+ sourceHash: string | null;
11
+ }
12
+ export function jobHubMessageMatches(event: Pick<MessageEvent, 'origin' | 'source' | 'data'>,
13
+ origin: string, source: MessageEventSource | null, binding: JobHubBinding, kind: 'ready' | 'visibility'): boolean {
14
+ if (!source || event.origin !== origin || event.source !== source || !event.data || typeof event.data !== 'object') return false;
15
+ const value = event.data;
16
+ const keys = ['schema', 'incarnation', 'jobId', 'publicationId', 'sourceHash', ...(kind === 'visibility' ? ['visible', 'language'] : [])];
17
+ return !Object.keys(value).some(key => !keys.includes(key)) &&
18
+ value.schema === (kind === 'ready' ? JOB_HUB_READY : JOB_HUB_VISIBILITY) &&
19
+ value.incarnation === binding.incarnation && value.jobId === binding.jobId &&
20
+ value.publicationId === binding.publicationId && value.sourceHash === binding.sourceHash &&
21
+ (binding.publicationId === null && binding.sourceHash === null ||
22
+ typeof binding.publicationId === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(binding.publicationId) &&
23
+ typeof binding.sourceHash === 'string' && /^[a-f0-9]{64}$/.test(binding.sourceHash)) &&
24
+ (kind === 'ready' || typeof value.visible === 'boolean' && ['en', 'ko'].includes(value.language));
25
+ }
26
+ export function jobHubAccess(href: string, storage: Pick<Storage, 'getItem' | 'setItem'> | null, replace: (href: string) => void) {
27
+ const url = new URL(href), incarnation = url.searchParams.get('workspace');
28
+ if (url.pathname !== '/hub/' || !incarnation || !/^[a-f0-9-]{36}$/.test(incarnation) ||
29
+ [...url.searchParams.keys()].some(key => !['workspace', 'lang'].includes(key) || url.searchParams.getAll(key).length !== 1) ||
30
+ url.searchParams.has('lang') && !['en', 'ko'].includes(url.searchParams.get('lang')!)) throw new Error('JOB_REQUEST_INVALID');
31
+ const slot = 'rig-review-job-hub/1:' + url.origin + ':' + incarnation;
32
+ let capability = url.hash.startsWith('#cap=') ? url.hash.slice(5) : '';
33
+ if (!/^[a-f0-9]{64}$/.test(capability)) capability = '';
34
+ try {
35
+ if (capability) storage?.setItem(slot, capability);
36
+ else capability = storage?.getItem(slot) ?? '';
37
+ } catch { /* Memory-only owner access. */ }
38
+ if (!/^[a-f0-9]{64}$/.test(capability)) capability = '';
39
+ url.hash = ''; replace(url.href);
40
+ return {incarnation, capability};
41
+ }
42
+ export function checkedJobHubList(value: JobHubList, incarnation: string): JobHubList {
43
+ if (value?.schema !== 'rig-review-job-hub/1' || value.incarnation !== incarnation ||
44
+ !Number.isSafeInteger(value.limit) || value.limit < 1 || value.limit > 32 ||
45
+ !Array.isArray(value.jobs) || value.jobs.length > value.limit) throw new Error('JOB_HUB_STATE_INVALID');
46
+ const ids = new Set<string>();
47
+ for (const job of value.jobs) {
48
+ if (!job || typeof job.jobId !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(job.jobId) || ids.has(job.jobId) ||
49
+ !['active', 'closed'].includes(job.status) || !Number.isSafeInteger(job.generation) || job.generation < 0 ||
50
+ !Number.isSafeInteger(job.pendingCount) || job.pendingCount < 0 || job.publication !== null &&
51
+ (!job.publication || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(job.publication.publicationId) ||
52
+ !/^[a-f0-9]{64}$/.test(job.publication.instanceKey) || !/^[a-f0-9]{64}$/.test(job.publication.sourceHash) ||
53
+ typeof job.publication.label !== 'string' || job.publication.label.length > 512)) throw new Error('JOB_HUB_STATE_INVALID');
54
+ ids.add(job.jobId);
55
+ }
56
+ return value;
57
+ }
58
+
59
+ export async function mountJobHub(root: HTMLElement): Promise<() => void> {
60
+ const i18n = await import('./i18n.ts');
61
+ const {t, getLanguage} = i18n;
62
+ let storage: Storage | null = null;
63
+ try {storage = sessionStorage;} catch { /* Memory-only access. */ }
64
+ const access = jobHubAccess(location.href, storage, href => history.replaceState(history.state, '', href));
65
+ const requestedLanguage = new URL(location.href).searchParams.get('lang');
66
+ if (requestedLanguage === 'en' || requestedLanguage === 'ko') i18n.setLanguagePreference(requestedLanguage);
67
+ const header = document.createElement('header'); header.className = 'hub-header';
68
+ const title = document.createElement('h1');
69
+ const notice = document.createElement('p'); notice.className = 'hub-status'; notice.setAttribute('role', 'status');
70
+ const language = document.createElement('select');
71
+ for (const name of ['en', 'ko']) {const option = document.createElement('option'); option.value = name; language.append(option);}
72
+ header.append(title, notice, language);
73
+ const list = document.createElement('nav'); list.className = 'hub-list';
74
+ const stage = document.createElement('main'); stage.className = 'hub-stage';
75
+ root.replaceChildren(header, list, stage);
76
+ type Frame = {frame: HTMLIFrameElement; row: JobHubRow; binding: JobHubBinding; announced?: JobHubBinding};
77
+ const frames = new Map<string, Frame>(), cancellation = new AbortController();
78
+ let current: JobHubList | null = null, selected: string | null = null, intent = 0, disposed = false;
79
+ let status = 'job.hubHint', timer: ReturnType<typeof setTimeout> | undefined;
80
+ const binding = (row: JobHubRow): JobHubBinding => ({incarnation: access.incarnation, jobId: row.jobId,
81
+ publicationId: row.publication?.publicationId ?? null, sourceHash: row.publication?.sourceHash ?? null});
82
+ function visibility(entry: Frame) {
83
+ entry.frame.contentWindow?.postMessage({...entry.binding, schema: JOB_HUB_VISIBILITY,
84
+ visible: entry.row.jobId === selected, language: getLanguage()}, location.origin);
85
+ }
86
+ function showSelection() {
87
+ for (const entry of frames.values()) {
88
+ entry.frame.hidden = entry.row.jobId !== selected;
89
+ entry.frame.inert = entry.frame.hidden;
90
+ entry.frame.setAttribute('aria-hidden', String(entry.frame.hidden)); visibility(entry);
91
+ }
92
+ }
93
+ function render() {
94
+ document.documentElement.lang = getLanguage();
95
+ title.textContent = t('job.hubTitle'); document.title = t('job.hubTitle'); notice.textContent = t(status);
96
+ list.setAttribute('aria-label', t('job.hubJobs')); language.setAttribute('aria-label', t('interview.language'));
97
+ language.options[0]!.textContent = t('English'); language.options[1]!.textContent = t('Korean'); language.value = getLanguage();
98
+ list.replaceChildren();
99
+ for (const row of current?.jobs ?? []) {
100
+ const button = document.createElement('button'); button.type = 'button';
101
+ button.dataset.jobId = row.jobId; button.setAttribute('aria-pressed', String(row.jobId === selected));
102
+ const name = document.createElement('span'); name.textContent = row.publication?.label || row.jobId;
103
+ const state = document.createElement('span'); state.className = 'hub-job-state';
104
+ state.textContent = row.status === 'closed' ? t('job.hubClosed') : t('job.hubPending', [row.pendingCount]);
105
+ const source = document.createElement('span'); source.className = 'hub-job-source'; source.textContent = row.publication?.sourceHash ?? '';
106
+ button.append(name, state, source);
107
+ button.onclick = () => {void select(row).catch(() => {status = 'JOB_HUB_REQUEST_REFUSED'; render();});}; list.append(button);
108
+ }
109
+ }
110
+ async function select(row: JobHubRow) {
111
+ const selection = ++intent;
112
+ let entry = frames.get(row.jobId);
113
+ if (!entry && row.status === 'closed') {
114
+ selected = row.jobId; status = 'job.hubClosed'; showSelection(); render(); return;
115
+ }
116
+ if (!entry) {
117
+ if (!current || frames.size >= current.limit) throw new Error('JOB_HUB_LIMIT');
118
+ const response = await fetch('/hub/api/jobs/' + row.jobId + '/open', {method: 'POST',
119
+ headers: {'Content-Type': 'application/json', 'X-Review-Capability': access.capability},
120
+ body: JSON.stringify({schema: 'rig-review-job-hub/1', incarnation: access.incarnation}),
121
+ signal: AbortSignal.any([cancellation.signal, AbortSignal.timeout(5000)])});
122
+ const grant = await response.json();
123
+ if (!response.ok) throw new Error('JOB_HUB_REQUEST_REFUSED');
124
+ if (disposed || selection !== intent) return;
125
+ if (grant.schema !== 'rig-review-job-hub/1' || grant.incarnation !== access.incarnation || grant.jobId !== row.jobId ||
126
+ grant.entry !== '/jobs/' + row.jobId + '/?hub=' + access.incarnation || !/^[a-f0-9]{64}$/.test(grant.capability)) throw new Error('JOB_HUB_STATE_INVALID');
127
+ const url = new URL(grant.entry, location.origin); url.searchParams.set('lang', getLanguage()); url.hash = 'cap=' + grant.capability;
128
+ const frame = document.createElement('iframe'); frame.title = row.publication?.label || row.jobId; frame.hidden = true; frame.src = url.href;
129
+ entry = {frame, row, binding: {...binding(row), publicationId: null, sourceHash: null}};
130
+ frames.set(row.jobId, entry); stage.append(frame);
131
+ }
132
+ selected = row.jobId; status = 'job.hubHint'; showSelection(); render();
133
+ }
134
+ function ready(event: MessageEvent) {
135
+ const entry = frames.get(event.data?.jobId);
136
+ if (!entry || !current) return;
137
+ const candidate: JobHubBinding = {incarnation: access.incarnation, jobId: entry.row.jobId,
138
+ publicationId: event.data?.publicationId, sourceHash: event.data?.sourceHash};
139
+ if (!jobHubMessageMatches(event, location.origin, entry.frame.contentWindow, candidate, 'ready')) return;
140
+ entry.announced = candidate;
141
+ if (jobHubMessageMatches(event, location.origin, entry.frame.contentWindow, binding(entry.row), 'ready')) {
142
+ entry.binding = candidate; visibility(entry);
143
+ }
144
+ }
145
+ async function refresh() {
146
+ try {
147
+ const response = await fetch('/hub/api/jobs', {headers: {'X-Review-Capability': access.capability},
148
+ signal: AbortSignal.any([cancellation.signal, AbortSignal.timeout(5000)])});
149
+ if (!response.ok) throw new Error('JOB_HUB_REQUEST_REFUSED');
150
+ current = checkedJobHubList(await response.json(), access.incarnation);
151
+ for (const row of current.jobs) {
152
+ const entry = frames.get(row.jobId);
153
+ if (!entry) continue;
154
+ entry.row = row;
155
+ if (entry.announced && JSON.stringify(entry.announced) === JSON.stringify(binding(row))) entry.binding = entry.announced;
156
+ visibility(entry);
157
+ }
158
+ render();
159
+ if (!selected && current.jobs[0]) await select(current.jobs[0]);
160
+ } catch {if (!disposed) {status = 'JOB_HUB_REQUEST_REFUSED'; render();}}
161
+ finally {if (!disposed) timer = setTimeout(() => {void refresh();}, 1000);}
162
+ }
163
+ language.onchange = () => {i18n.setLinkLanguage(null); i18n.setLanguagePreference(language.value === 'ko' ? 'ko' : 'en');};
164
+ const unlocalize = i18n.onLanguageChange(() => {render(); showSelection();});
165
+ globalThis.addEventListener('message', ready);
166
+ const stop = () => {
167
+ if (disposed) return;
168
+ disposed = true; clearTimeout(timer); cancellation.abort(); unlocalize();
169
+ globalThis.removeEventListener('message', ready); globalThis.removeEventListener('pagehide', stop);
170
+ };
171
+ globalThis.addEventListener('pagehide', stop, {once: true});
172
+ render(); void refresh(); return stop;
173
+ }
174
+ if (typeof document !== 'undefined' && document.body?.hasAttribute('data-job-hub')) {
175
+ void mountJobHub(document.getElementById('job-hub')!).catch(async () => {
176
+ const {t} = await import('./i18n.ts');
177
+ document.getElementById('job-hub')!.textContent = t('JOB_HUB_REQUEST_REFUSED');
178
+ });
179
+ }
@@ -3,6 +3,7 @@ import type { JobAct, JobDisplayPublication, JobDisplayReceipt, JobEvent, JobPen
3
3
  import {enCatalog} from './catalog-en.ts';
4
4
  import {koCatalog} from './catalog-ko.ts';
5
5
  import {t} from './i18n.ts';
6
+ import {JOB_HUB_READY, jobHubMessageMatches, type JobHubBinding} from './job-hub.ts';
6
7
 
7
8
  /** Imported runtimes may throw arbitrary prose. Only registered refusal copy reaches the window. */
8
9
  export function jobWindowRefusal(error: unknown, fallback = 'JOB_WINDOW_FAILED'): string {
@@ -440,6 +441,61 @@ export async function* jobWindowEvents(access: JobWindowAccess, after: string |
440
441
  reader.releaseLock();
441
442
  }
442
443
  }
444
+ /** One reader per window. Hub members bootstrap before visibility can suspend transport. */
445
+ export function startJobWindowEvents(options: {
446
+ access: JobWindowAccess;
447
+ signal: AbortSignal;
448
+ member: boolean;
449
+ event(value: JobEvent): void;
450
+ refused(error: unknown): void;
451
+ fetcher?: typeof fetch;
452
+ }) {
453
+ let bootstrap = options.member;
454
+ let visible = !options.member;
455
+ let cursor: string | null = null;
456
+ let reader: AbortController | null = null;
457
+ let wake: (() => void) | null = null;
458
+ const enabled = () => bootstrap || visible;
459
+ function changed() {
460
+ if (!enabled()) reader?.abort();
461
+ wake?.();
462
+ }
463
+ const stopped = () => { reader?.abort(); wake?.(); };
464
+ options.signal.addEventListener('abort', stopped, {once: true});
465
+ function wait(milliseconds?: number): Promise<void> {
466
+ return new Promise(resolve => {
467
+ const timer = milliseconds === undefined ? undefined : setTimeout(finish, milliseconds);
468
+ function finish() { clearTimeout(timer); wake = null; resolve(); }
469
+ wake = finish;
470
+ if (options.signal.aborted) finish();
471
+ });
472
+ }
473
+ const done = (async () => {
474
+ try {
475
+ while (!options.signal.aborted) {
476
+ if (!enabled()) { await wait(); continue; }
477
+ const current = new AbortController();
478
+ reader = current;
479
+ try {
480
+ for await (const event of jobWindowEvents(options.access, cursor, current.signal, options.fetcher)) {
481
+ // Only complete, delivered events advance replay, including a final event racing hide.
482
+ options.event(event);
483
+ cursor = event.cursor;
484
+ if (event.type === 'closed') return;
485
+ }
486
+ } catch (error) {
487
+ if (!current.signal.aborted && !options.signal.aborted) options.refused(error);
488
+ } finally { reader = null; }
489
+ if (!options.signal.aborted && enabled() && !current.signal.aborted) await wait(500);
490
+ }
491
+ } finally { options.signal.removeEventListener('abort', stopped); }
492
+ })();
493
+ return {
494
+ done,
495
+ visibility(value: boolean) { if (options.member) { bootstrap = false; visible = value; changed(); } },
496
+ displayed() { if (options.member) { bootstrap = false; changed(); } },
497
+ };
498
+ }
443
499
  import type { ModelAssets, RigPlayer } from '@rig-c/play';
444
500
  import type { PartInspection } from './part-selection.ts';
445
501
  import type { Checkpoint, ReviewManifest, ReviewedSource } from '../src/manifest.ts';
@@ -849,6 +905,9 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
849
905
  }
850
906
  catch { /* Capability stays in memory. */ }
851
907
  const access = jobWindowAccess(location.href, storage, href => history.replaceState(history.state, '', href));
908
+ const hubIncarnation = new URL(location.href).searchParams.get('hub');
909
+ let hubVisible = !hubIncarnation;
910
+ let events: ReturnType<typeof startJobWindowEvents> | undefined;
852
911
  const pageId = crypto.randomUUID();
853
912
  const transport = createJobWindowTransport(access);
854
913
  const abort = new AbortController();
@@ -1410,6 +1469,19 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1410
1469
  }
1411
1470
  viewport.fitCamera();
1412
1471
  }
1472
+ function hubBinding(): JobHubBinding {
1473
+ return {incarnation: hubIncarnation!, jobId: access.jobId,
1474
+ publicationId: current?.display.publication.publicationId ?? null,
1475
+ sourceHash: current?.display.publication.source.sourceHash ?? null};
1476
+ }
1477
+ function pauseHiddenHubFrame(): void {
1478
+ if (hubVisible) return;
1479
+ current?.player?.pause();
1480
+ for (const video of workspace.querySelectorAll('video')) video.pause();
1481
+ }
1482
+ function announceHubFrame(): void {
1483
+ if (hubIncarnation) globalThis.parent.postMessage({...hubBinding(), schema: JOB_HUB_READY}, location.origin);
1484
+ }
1413
1485
  const window = createJobWindow({ jobId: access.jobId, pageId, transport, adapter: {
1414
1486
  async prepare(display, signal): Promise<PreparedWindow> {
1415
1487
  const inspection = await prepareJobInspection(display, signal);
@@ -1571,6 +1643,8 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1571
1643
  catch { /* In-memory retained evidence remains available. */ }
1572
1644
  history.textContent = [...retained.values()].map(draft => t('job.retained', [draft.label]) + '\n' + draft.sourceHash + '\n' + JSON.stringify(draft.value, null, 2)).join('\n');
1573
1645
  }
1646
+ pauseHiddenHubFrame(); announceHubFrame();
1647
+ if (state.receipt && !state.preparing) events?.displayed();
1574
1648
  },
1575
1649
  } });
1576
1650
  const localize = i18n.onLanguageChange(() => {
@@ -1581,26 +1655,24 @@ export async function mountJobSession(host: HTMLElement): Promise<() => void> {
1581
1655
  viewport.renderCameraControls();
1582
1656
  window.refresh();
1583
1657
  });
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));
1658
+ const hubVisibility = (event: MessageEvent) => {
1659
+ if (!hubIncarnation || !jobHubMessageMatches(event, location.origin, globalThis.parent, hubBinding(), 'visibility')) return;
1660
+ hubVisible = event.data.visible;
1661
+ host.dataset.hubVisible = String(hubVisible);
1662
+ events?.visibility(hubVisible);
1663
+ if (event.data.language !== i18n.getLanguage()) {
1664
+ i18n.setLinkLanguage(null); i18n.setLanguagePreference(event.data.language);
1601
1665
  }
1602
- })();
1666
+ pauseHiddenHubFrame();
1667
+ if (hubVisible) current?.player?.draw();
1668
+ };
1669
+ if (hubIncarnation) {globalThis.addEventListener('message', hubVisibility); announceHubFrame();}
1670
+ events = startJobWindowEvents({access, signal: abort.signal, member: !!hubIncarnation,
1671
+ event: event => window.event(event),
1672
+ refused: error => {notice.textContent = jobWindowRefusal(error, 'JOB_STREAM_FAILED');},
1673
+ });
1603
1674
  const stop = () => {
1675
+ globalThis.removeEventListener('message', hubVisibility);
1604
1676
  saveDraft();
1605
1677
  referenceSelection.cancel();
1606
1678
  abort.abort();