@khanglvm/relay 0.19.0 → 0.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/README.md +11 -4
  2. package/bin/rly.js +1 -1
  3. package/package.json +4 -4
  4. package/src/cli/args.js +46 -0
  5. package/src/cli/ask.js +12 -0
  6. package/src/cli/boards.js +326 -0
  7. package/src/cli/config.js +56 -0
  8. package/src/cli/context.js +13 -0
  9. package/src/cli/git.js +183 -0
  10. package/src/cli/help.js +91 -0
  11. package/src/cli/index.js +103 -0
  12. package/src/cli/install.js +197 -0
  13. package/src/cli/io.js +186 -0
  14. package/src/cli/mcp.js +94 -0
  15. package/src/cli/share.js +45 -0
  16. package/src/cli/skill.js +192 -0
  17. package/src/cli/upgrade.js +130 -0
  18. package/src/cli/wait.js +172 -0
  19. package/src/file-preview.js +1 -1
  20. package/src/index.js +1 -1
  21. package/src/link.js +57 -9
  22. package/src/mcp-ui/board/block-ctx.js +43 -0
  23. package/src/mcp-ui/board/bridge.js +165 -0
  24. package/src/mcp-ui/board/controls.js +310 -0
  25. package/src/mcp-ui/board/core.js +20 -0
  26. package/src/mcp-ui/board/lifecycle.js +118 -0
  27. package/src/mcp-ui/board/normalize.js +95 -0
  28. package/src/mcp-ui/board/render.js +200 -0
  29. package/src/mcp-ui/board/state.js +106 -0
  30. package/src/mcp-ui/board/vendors.js +86 -0
  31. package/src/mcp.js +12 -18
  32. package/src/{server.js → server/board.js} +16 -779
  33. package/src/server/files.js +141 -0
  34. package/src/server/http.js +114 -0
  35. package/src/server/index.js +2 -0
  36. package/src/server/page.js +183 -0
  37. package/src/server/paths.js +7 -0
  38. package/src/server/result.js +58 -0
  39. package/src/server/reviews.js +41 -0
  40. package/src/server/sanitize.js +231 -0
  41. package/src/spec/blocks/a2ui.js +25 -0
  42. package/src/spec/blocks/chart.js +49 -0
  43. package/src/spec/blocks/code.js +38 -0
  44. package/src/spec/blocks/diagram.js +39 -0
  45. package/src/spec/blocks/git-conflict.js +106 -0
  46. package/src/spec/blocks/image.js +32 -0
  47. package/src/spec/blocks/index.js +33 -0
  48. package/src/spec/blocks/markdown.js +13 -0
  49. package/src/spec/blocks/pdf.js +38 -0
  50. package/src/spec/blocks/table.js +122 -0
  51. package/src/spec/blocks/video.js +68 -0
  52. package/src/spec/blocks/widgets.js +98 -0
  53. package/src/spec/constants.js +65 -0
  54. package/src/spec/index.js +5 -0
  55. package/src/spec/normalize.js +285 -0
  56. package/src/spec/ready.js +106 -0
  57. package/src/spec/schema.js +182 -0
  58. package/src/spec/sources.js +83 -0
  59. package/src/store.js +1 -1
  60. package/src/ui/annotate/api.js +149 -0
  61. package/src/ui/annotate/badges.js +77 -0
  62. package/src/ui/annotate/chrome.js +158 -0
  63. package/src/ui/annotate/core.js +134 -0
  64. package/src/ui/annotate/highlights.js +129 -0
  65. package/src/ui/annotate/mutations.js +127 -0
  66. package/src/ui/annotate/popover.js +206 -0
  67. package/src/ui/annotate/summary.js +67 -0
  68. package/src/ui/app/annotations.js +88 -0
  69. package/src/ui/app/autosave.js +44 -0
  70. package/src/ui/app/core.js +74 -0
  71. package/src/ui/app/drafts.js +201 -0
  72. package/src/ui/app/heartbeat.js +150 -0
  73. package/src/ui/app/iframe-bridge.js +64 -0
  74. package/src/ui/app/persistence.js +117 -0
  75. package/src/ui/app/prefilled.js +21 -0
  76. package/src/ui/app/presence.js +38 -0
  77. package/src/ui/app/question-color.js +67 -0
  78. package/src/ui/app/questions.js +360 -0
  79. package/src/ui/app/render.js +135 -0
  80. package/src/ui/app/share.js +108 -0
  81. package/src/ui/app/submit.js +109 -0
  82. package/src/ui/app/theme.js +63 -0
  83. package/src/ui/blocks/api.js +1 -0
  84. package/src/ui/blocks/chart.js +222 -0
  85. package/src/ui/blocks/code.js +138 -0
  86. package/src/ui/blocks/compare.js +82 -0
  87. package/src/ui/blocks/core.js +74 -0
  88. package/src/ui/blocks/diff.js +361 -0
  89. package/src/ui/blocks/dispatch.js +111 -0
  90. package/src/ui/blocks/file-links.js +180 -0
  91. package/src/ui/blocks/git-conflict.js +151 -0
  92. package/src/ui/blocks/graphviz.js +57 -0
  93. package/src/ui/blocks/html.js +45 -0
  94. package/src/ui/blocks/image.js +371 -0
  95. package/src/ui/blocks/kpi.js +26 -0
  96. package/src/ui/blocks/markdown.js +223 -0
  97. package/src/ui/blocks/mermaid.js +242 -0
  98. package/src/ui/blocks/palette.js +59 -0
  99. package/src/ui/blocks/pdf.js +21 -0
  100. package/src/ui/blocks/plantuml.js +152 -0
  101. package/src/ui/blocks/table.js +155 -0
  102. package/src/ui/blocks/typography.js +25 -0
  103. package/src/ui/blocks/vendor.js +43 -0
  104. package/src/ui/blocks/video.js +43 -0
  105. package/src/ui/blocks/viewer-fullscreen.js +146 -0
  106. package/src/ui/blocks/viewer.js +324 -0
  107. package/src/ui/kit.js +1 -0
  108. package/src/ui/manifest.js +140 -0
  109. package/types/index.d.ts +1 -1
  110. package/types/spec/blocks/a2ui.d.ts +4 -0
  111. package/types/spec/blocks/chart.d.ts +4 -0
  112. package/types/spec/blocks/code.d.ts +10 -0
  113. package/types/spec/blocks/diagram.d.ts +15 -0
  114. package/types/spec/blocks/git-conflict.d.ts +7 -0
  115. package/types/spec/blocks/image.d.ts +5 -0
  116. package/types/spec/blocks/index.d.ts +30 -0
  117. package/types/spec/blocks/markdown.d.ts +5 -0
  118. package/types/spec/blocks/pdf.d.ts +4 -0
  119. package/types/spec/blocks/table.d.ts +9 -0
  120. package/types/spec/blocks/video.d.ts +4 -0
  121. package/types/spec/blocks/widgets.d.ts +21 -0
  122. package/types/spec/constants.d.ts +67 -0
  123. package/types/spec/index.d.ts +4 -0
  124. package/types/spec/normalize.d.ts +17 -0
  125. package/types/spec/ready.d.ts +1 -0
  126. package/types/{spec.d.ts → spec/schema.d.ts} +0 -20
  127. package/types/spec/sources.d.ts +14 -0
  128. package/types/ui/manifest.d.ts +62 -0
  129. package/src/cli.js +0 -1767
  130. package/src/mcp-ui/board.js +0 -1162
  131. package/src/spec.js +0 -1224
  132. package/src/ui/annotate.js +0 -1055
  133. package/src/ui/app.js +0 -1643
  134. package/src/ui/blocks.js +0 -3260
@@ -1,1162 +0,0 @@
1
- // board.js — the relay board as an MCP App (SEP-1865 "io.modelcontextprotocol/ui").
2
- //
3
- // This is the same board relay opens in a browser, but rendered INSIDE the
4
- // host app (Claude desktop/mobile, Codex, …) as a sandboxed inline iframe.
5
- // There is no local HTTP server here: every exchange with the host travels over
6
- // JSON-RPC on window.postMessage — the spec arrives as the tool result, the
7
- // user's final submission goes back as a `ui/message` user turn, and vendored
8
- // libraries (Chart.js / Mermaid / Viz.js) are pulled through the host's
9
- // `resources/read`.
10
- //
11
- // Rich blocks are rendered by the SAME window.RelayBlocks as the browser board
12
- // (markdown, code, diff, table, chart, mermaid, graphviz, image, html), so the
13
- // two surfaces stay in lockstep. Annotations / autosave / heartbeat are
14
- // browser-server concepts and intentionally absent; per-question notes and the
15
- // overall comment carry structured feedback back to the agent.
16
- (() => {
17
- 'use strict';
18
-
19
- const BOOT = (() => {
20
- try { return JSON.parse(document.getElementById('boot').textContent); } catch { return {}; }
21
- })();
22
- const PROTOCOL = '2025-06-18';
23
-
24
- // ---------- tiny DOM helper (mirrors app.js / blocks.js) ----------
25
- function el(tag, attrs = {}, ...children) {
26
- const n = document.createElement(tag);
27
- for (const [k, v] of Object.entries(attrs)) {
28
- if (v === undefined || v === null) continue;
29
- if (k === 'class') n.className = v;
30
- else if (k.startsWith('on')) n.addEventListener(k.slice(2), v);
31
- else n.setAttribute(k, v);
32
- }
33
- for (const c of children.flat()) {
34
- if (c !== null && c !== undefined) n.append(c.nodeType ? c : document.createTextNode(c));
35
- }
36
- return n;
37
- }
38
-
39
- // ======================================================================
40
- // MCP Apps postMessage / JSON-RPC bridge
41
- // ======================================================================
42
- const pending = new Map();
43
- let rpcSeq = 0;
44
- const notifyHandlers = Object.create(null);
45
- function onNotify(method, fn) {
46
- (notifyHandlers[method] || (notifyHandlers[method] = [])).push(fn);
47
- }
48
- function post(msg) {
49
- try {
50
- (window.parent && window.parent !== window ? window.parent : window).postMessage(msg, '*');
51
- } catch {
52
- // host frame gone — nothing we can do
53
- }
54
- }
55
- function request(method, params) {
56
- const id = 'rly-' + (++rpcSeq);
57
- return new Promise((resolve, reject) => {
58
- pending.set(id, { resolve, reject });
59
- post({ jsonrpc: '2.0', id, method, params: params || {} });
60
- // Don't hang forever if a host ignores a method — resolve-less reject.
61
- setTimeout(() => {
62
- if (pending.has(id)) {
63
- pending.delete(id);
64
- reject(new Error('timeout: ' + method));
65
- }
66
- }, 15000);
67
- });
68
- }
69
- function notify(method, params) {
70
- post({ jsonrpc: '2.0', method, params: params || {} });
71
- }
72
-
73
- window.addEventListener('message', (e) => {
74
- const msg = e.data;
75
- if (!msg || typeof msg !== 'object' || msg.jsonrpc !== '2.0') return;
76
- // A response to one of our requests.
77
- if (msg.id !== undefined && msg.id !== null && (('result' in msg) || ('error' in msg))) {
78
- const p = pending.get(msg.id);
79
- if (!p) return;
80
- pending.delete(msg.id);
81
- if (msg.error) p.reject(Object.assign(new Error(msg.error.message || 'rpc error'), { rpc: msg.error }));
82
- else p.resolve(msg.result);
83
- return;
84
- }
85
- // A notification or request FROM the host.
86
- if (typeof msg.method === 'string') {
87
- const hs = notifyHandlers[msg.method] || [];
88
- for (const h of hs) {
89
- try { h(msg.params || {}, msg); } catch { /* handler errors never break the bridge */ }
90
- }
91
- // Host requests we must acknowledge.
92
- if (msg.id !== undefined && msg.id !== null) {
93
- if (msg.method === 'ui/resource-teardown') post({ jsonrpc: '2.0', id: msg.id, result: {} });
94
- else post({ jsonrpc: '2.0', id: msg.id, result: {} });
95
- }
96
- }
97
- });
98
-
99
- // ======================================================================
100
- // theme + size
101
- // ======================================================================
102
- let host = {};
103
- function effectiveTheme() {
104
- if (host.theme === 'dark' || host.theme === 'light') return host.theme;
105
- return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
106
- }
107
- function applyTheme() {
108
- const t = host.theme;
109
- if (t === 'dark' || t === 'light') {
110
- document.documentElement.dataset.theme = t;
111
- // Pin color-scheme so the host's light-dark() style variables resolve to
112
- // the side the host actually picked (not whatever the OS prefers).
113
- document.documentElement.style.colorScheme = t;
114
- } else {
115
- delete document.documentElement.dataset.theme;
116
- document.documentElement.style.colorScheme = 'light dark';
117
- }
118
- if (window.RelayBlocks && typeof RelayBlocks.onThemeChange === 'function') {
119
- try { RelayBlocks.onThemeChange(effectiveTheme()); } catch { /* not rendered yet */ }
120
- }
121
- }
122
-
123
- // Full color-blend: map the host's standardized style variables (SEP-1865
124
- // theming) onto relay's own custom properties so the board adopts the app's
125
- // surfaces, text, borders, primary-action color and fonts — reading as part of
126
- // Claude/Codex rather than a foreign page. Every mapping is conditional: a
127
- // token the host omits keeps relay's own default, so it degrades gracefully on
128
- // leaner hosts (where the warm terracotta identity simply stays).
129
- const HOST_VAR_MAP = {
130
- '--bg': '--color-background-primary',
131
- '--card': '--color-background-secondary',
132
- '--bg-sunken': '--color-background-tertiary',
133
- '--fg': '--color-text-primary',
134
- '--fg-2': '--color-text-secondary',
135
- '--muted': '--color-text-tertiary',
136
- '--border': '--color-border-primary',
137
- '--border-strong': '--color-border-secondary',
138
- '--accent': '--color-background-inverse',
139
- '--accent-hover': '--color-background-inverse',
140
- '--accent-fg': '--color-text-inverse',
141
- '--accent-soft': '--color-background-tertiary',
142
- '--danger': '--color-text-danger',
143
- '--ok': '--color-text-success',
144
- '--sans': '--font-sans',
145
- '--mono': '--font-mono',
146
- };
147
- let hostFontStyleEl = null;
148
- function adoptHostStyles() {
149
- const styles = host && host.styles;
150
- if (!styles || typeof styles !== 'object') return;
151
- const v = styles.variables && typeof styles.variables === 'object' ? styles.variables : {};
152
- const root = document.documentElement.style;
153
- for (const [ours, theirs] of Object.entries(HOST_VAR_MAP)) {
154
- if (typeof v[theirs] === 'string' && v[theirs]) root.setProperty(ours, v[theirs]);
155
- }
156
- const fonts = styles.css && typeof styles.css.fonts === 'string' ? styles.css.fonts : '';
157
- if (fonts) {
158
- if (!hostFontStyleEl) { hostFontStyleEl = document.createElement('style'); document.head.appendChild(hostFontStyleEl); }
159
- hostFontStyleEl.textContent = fonts;
160
- }
161
- }
162
-
163
- // Platform awareness: reflect the host's surface so the board (and CSS) can
164
- // adapt — a data-platform hint, a touch flag, and the host's safe-area insets
165
- // applied as padding so content clears notches / home indicators on mobile.
166
- function applyHostEnv() {
167
- const root = document.documentElement;
168
- if (host.platform === 'web' || host.platform === 'desktop' || host.platform === 'mobile') {
169
- root.dataset.platform = host.platform;
170
- }
171
- root.classList.toggle('mcp-touch', Boolean(host.deviceCapabilities && host.deviceCapabilities.touch));
172
- const sai = host.safeAreaInsets;
173
- if (sai && typeof sai === 'object') {
174
- const px = (n) => (Number.isFinite(n) ? n : 0) + 'px';
175
- root.style.setProperty('--mcp-safe-top', px(sai.top));
176
- root.style.setProperty('--mcp-safe-right', px(sai.right));
177
- root.style.setProperty('--mcp-safe-bottom', px(sai.bottom));
178
- root.style.setProperty('--mcp-safe-left', px(sai.left));
179
- }
180
- }
181
-
182
- let sizeTimer = null;
183
- function measureHeight() {
184
- return Math.max(document.documentElement.scrollHeight, document.body ? document.body.scrollHeight : 0);
185
- }
186
- function sendSize() {
187
- notify('ui/notifications/size-changed', { width: document.documentElement.scrollWidth, height: measureHeight() });
188
- }
189
- function reportSize() {
190
- if (sizeTimer) return;
191
- sizeTimer = setTimeout(() => { sizeTimer = null; sendSize(); }, 60);
192
- }
193
- // Immediate, un-debounced report — used when the board shrinks (e.g. after
194
- // submit) so the host collapses the iframe right away instead of waiting.
195
- function reportSizeNow() {
196
- if (sizeTimer) { clearTimeout(sizeTimer); sizeTimer = null; }
197
- sendSize();
198
- }
199
- window.addEventListener('resize', reportSize);
200
- if (typeof ResizeObserver !== 'undefined') {
201
- try { new ResizeObserver(reportSize).observe(document.documentElement); } catch { /* older host */ }
202
- }
203
-
204
- // ======================================================================
205
- // client-side spec normalization (resilience)
206
- // ----------------------------------------------------------------------
207
- // The host normally hands us the SERVER-normalized spec via the tool result
208
- // (structuredContent.spec) — options as {value,label}, blocks with ids, etc.
209
- // If a host only forwards the raw tool input, this brings it close enough to
210
- // render: it assigns ids and coerces option/column shapes. File-backed blocks
211
- // (codeFile/htmlFile/local images) can't be resolved client-side and are left
212
- // to the server path.
213
- function clientNormalize(raw) {
214
- if (!raw || typeof raw !== 'object') return null;
215
- const spec = {
216
- title: String(raw.title || 'Relay'),
217
- intro: typeof raw.intro === 'string' ? raw.intro : '',
218
- blocks: normBlocks(raw.blocks, ''),
219
- allowPartial: raw.allowPartial !== false,
220
- note: raw.note !== false,
221
- autoClose: raw.autoClose !== false,
222
- responseRequired: raw.responseRequired !== false,
223
- questions: [],
224
- submitLabel: typeof raw.submitLabel === 'string' ? raw.submitLabel : '',
225
- };
226
- const qs = Array.isArray(raw.questions) ? raw.questions : [];
227
- qs.forEach((rq, i) => {
228
- if (!rq || typeof rq !== 'object') return;
229
- const id = String(rq.id || 'q' + (i + 1));
230
- const type = String(rq.type || 'text');
231
- const q = {
232
- id, type,
233
- label: String(rq.label || rq.question || rq.text || ''),
234
- description: typeof rq.description === 'string' ? rq.description : '',
235
- required: rq.required === true,
236
- note: rq.note === undefined ? (type === 'single' || type === 'rank' || type === 'checklist' || type === 'allocate') : rq.note === true,
237
- placeholder: typeof rq.placeholder === 'string' ? rq.placeholder : '',
238
- blocks: normBlocks(rq.blocks, id + '-'),
239
- };
240
- if (type === 'single' || type === 'multi' || type === 'rank' || type === 'checklist' || type === 'allocate') {
241
- const opts = Array.isArray(rq.options) ? rq.options : [];
242
- q.options = opts.map((o, j) => {
243
- if (typeof o === 'string' || typeof o === 'number') return { value: String(o), label: String(o) };
244
- if (o && typeof o === 'object') {
245
- const value = String(o.value != null ? o.value : o.label != null ? o.label : '');
246
- const out = { value, label: String(o.label != null ? o.label : value) };
247
- if (o.description) out.description = String(o.description);
248
- const ob = normBlocks(o.blocks, id + '-o' + (j + 1) + '-');
249
- if (ob.length) out.blocks = ob;
250
- return out;
251
- }
252
- return { value: String(o), label: String(o) };
253
- });
254
- if (type === 'single' || type === 'multi') q.other = type === 'single' ? rq.other !== false : rq.other === true;
255
- }
256
- if (type === 'checklist') {
257
- const rawSt = Array.isArray(rq.statuses) && rq.statuses.length ? rq.statuses
258
- : [{ value: 'pass', label: 'Pass', tone: 'ok' }, { value: 'fail', label: 'Fail', tone: 'bad' }, { value: 'na', label: 'N/A', tone: 'muted' }];
259
- q.statuses = rawSt.map((s) => typeof s === 'object' && s
260
- ? { value: String(s.value != null ? s.value : s.label || ''), label: String(s.label != null ? s.label : s.value || ''), tone: s.tone ? String(s.tone) : undefined }
261
- : { value: String(s), label: String(s) === 'na' ? 'N/A' : String(s) });
262
- }
263
- if (type === 'allocate') {
264
- q.total = Number.isFinite(rq.total) && rq.total > 0 ? Math.floor(rq.total) : 100;
265
- if (rq.unit !== undefined) q.unit = String(rq.unit);
266
- }
267
- if (type === 'scale') {
268
- q.min = Number.isFinite(rq.min) ? rq.min : 1;
269
- q.max = Number.isFinite(rq.max) ? rq.max : Math.max(5, q.min + 1);
270
- q.minLabel = typeof rq.minLabel === 'string' ? rq.minLabel : '';
271
- q.maxLabel = typeof rq.maxLabel === 'string' ? rq.maxLabel : '';
272
- }
273
- if (type === 'color' && Array.isArray(rq.presets)) {
274
- q.presets = rq.presets.map((c) => String(c)).filter(Boolean);
275
- }
276
- if (type === 'color' && Array.isArray(rq.palette)) {
277
- q.palette = rq.palette.map((p) => typeof p === 'object' && p
278
- ? { value: String(p.value != null ? p.value : p.color || ''), label: String(p.label != null ? p.label : (p.name != null ? p.name : (p.value != null ? p.value : p.color || ''))) }
279
- : { value: String(p), label: String(p) }).filter((p) => p.value);
280
- }
281
- if (rq.default !== undefined) q.default = rq.default;
282
- spec.questions.push(q);
283
- });
284
- if (!spec.submitLabel) spec.submitLabel = spec.questions.length ? 'Submit' : 'Acknowledge';
285
- return spec;
286
- }
287
- function normBlocks(blocks, prefix) {
288
- if (!Array.isArray(blocks)) return [];
289
- let n = 0;
290
- const out = [];
291
- for (const b of blocks) {
292
- if (!b || typeof b !== 'object' || !b.type) continue;
293
- out.push(b.id ? b : { ...b, id: prefix + 'b' + (++n) });
294
- if (b.id) n++;
295
- }
296
- return out;
297
- }
298
-
299
- // ======================================================================
300
- // vendored libraries pulled through the host bridge (resources/read)
301
- // ----------------------------------------------------------------------
302
- // blocks.js lazy-loads Chart.js / Mermaid / Viz.js via <script src="/vendor/…">
303
- // and short-circuits when the global already exists. There's no server here,
304
- // so we fetch the vendor source over the bridge and define the global up
305
- // front; blocks.js then never reaches for the (absent) /vendor route.
306
- const NEED = { chart: ['chart.umd.js', 'Chart'], mermaid: ['mermaid.min.js', 'mermaid'], graphviz: ['viz-standalone.js', 'Viz'] };
307
- function blockTypesIn(spec) {
308
- const types = new Set();
309
- const scan = (blocks) => {
310
- for (const b of Array.isArray(blocks) ? blocks : []) {
311
- if (b && b.type) types.add(b.type);
312
- if (b && Array.isArray(b.blocks)) scan(b.blocks);
313
- }
314
- };
315
- scan(spec.blocks);
316
- for (const q of spec.questions || []) {
317
- scan(q.blocks);
318
- for (const o of Array.isArray(q.options) ? q.options : []) if (o) scan(o.blocks);
319
- }
320
- return types;
321
- }
322
- async function ensureVendor(file, globalName) {
323
- if (window[globalName]) return true;
324
- try {
325
- const res = await request('resources/read', { uri: 'ui://relay/vendor/' + file });
326
- const c = res && Array.isArray(res.contents) ? res.contents[0] : null;
327
- const code = c && (c.text || (c.blob ? atob(c.blob) : ''));
328
- if (!code) return false;
329
- const s = document.createElement('script');
330
- s.textContent = code;
331
- document.head.appendChild(s);
332
- return Boolean(window[globalName]);
333
- } catch {
334
- return false;
335
- }
336
- }
337
- async function preloadVendors(spec) {
338
- const types = blockTypesIn(spec);
339
- const jobs = [];
340
- if (types.has('chart')) jobs.push(ensureVendor(...NEED.chart));
341
- if (types.has('mermaid')) jobs.push(ensureVendor(...NEED.mermaid));
342
- if (types.has('graphviz')) jobs.push(ensureVendor(...NEED.graphviz));
343
- if (jobs.length) await Promise.allSettled(jobs);
344
- }
345
-
346
- // html blocks: the browser board serves each in its own iframe from
347
- // /html/b/<id>. Here we wrap the body into a self-contained document and hand
348
- // blocks.js a blob: URL for the iframe src (same sandbox, no server needed).
349
- const htmlBodies = new Map();
350
- function indexHtmlBlocks(spec) {
351
- const add = (blocks) => {
352
- for (const b of Array.isArray(blocks) ? blocks : []) {
353
- if (b && b.type === 'html' && typeof b.html === 'string') htmlBodies.set(b.id, b.html);
354
- }
355
- };
356
- add(spec.blocks);
357
- for (const q of spec.questions || []) {
358
- add(q.blocks);
359
- for (const o of Array.isArray(q.options) ? q.options : []) if (o) add(o.blocks);
360
- }
361
- }
362
- function htmlBlobSrc(blockId) {
363
- const body = htmlBodies.get(blockId) || '';
364
- const dark = effectiveTheme() === 'dark';
365
- let doc;
366
- if (/<html[\s>]/i.test(body)) {
367
- doc = body;
368
- } else {
369
- const bg = dark ? '#282624' : '#ffffff';
370
- const fg = dark ? '#edeae4' : '#1c1b19';
371
- doc =
372
- '<!doctype html><html><head><meta charset="utf-8">' +
373
- '<meta name="viewport" content="width=device-width, initial-scale=1">' +
374
- '<style>:root{color-scheme:' + (dark ? 'dark' : 'light') + '}' +
375
- 'body{margin:12px;font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Arial,sans-serif;' +
376
- 'background:' + bg + ';color:' + fg + '}</style></head><body>' + body + '</body></html>';
377
- }
378
- try {
379
- return URL.createObjectURL(new Blob([doc], { type: 'text/html' }));
380
- } catch {
381
- return 'data:text/html;charset=utf-8,' + encodeURIComponent(doc);
382
- }
383
- }
384
-
385
- function blockCtx(questionId) {
386
- return {
387
- theme: effectiveTheme,
388
- htmlSrc: (blockId) => htmlBlobSrc(blockId),
389
- questionId: questionId == null ? null : questionId,
390
- // No annotation during the streaming preview (it re-renders); on the final
391
- // interactive render, wire the engine so blocks register their targets.
392
- annotate: composing || (spec && spec.responseRequired === false) ? null : Annotate,
393
- canComment: Boolean(spec && spec.responseRequired !== false),
394
- saveArtifact: async ({ dataUrl, mime, width, height }) => {
395
- const comma = typeof dataUrl === 'string' ? dataUrl.indexOf(',') : -1;
396
- if (comma < 0) throw new Error('invalid image crop');
397
- return { data: dataUrl.slice(comma + 1), mime: mime || 'image/png', width, height };
398
- },
399
- edits: state.blockEdits,
400
- onBlockEdit: (blockId, codeOrNull) => {
401
- if (codeOrNull === null || codeOrNull === undefined) delete state.blockEdits[blockId];
402
- else state.blockEdits[blockId] = codeOrNull;
403
- },
404
- };
405
- }
406
- document.addEventListener('relay:block-edit', (e) => {
407
- const d = e.detail || {};
408
- if (!d.blockId) return;
409
- if (d.value === null || d.value === undefined) delete state.blockEdits[d.blockId];
410
- else state.blockEdits[d.blockId] = d.value;
411
- });
412
- function renderBlocks(container, blocks, questionId) {
413
- if (!Array.isArray(blocks) || !blocks.length) return;
414
- const target = el('div', { class: 'blocks' });
415
- container.append(target);
416
- if (!window.RelayBlocks) {
417
- target.append(el('div', { class: 'blk' }, el('div', { class: 'blk-error' }, 'block failed to render')));
418
- return;
419
- }
420
- Promise.resolve()
421
- .then(() => window.RelayBlocks.render(target, blocks, blockCtx(questionId)))
422
- .then(reportSize)
423
- .catch(() => {
424
- target.append(el('div', { class: 'blk' }, el('div', { class: 'blk-error' }, 'block failed to render')));
425
- });
426
- }
427
-
428
- // ======================================================================
429
- // board state + answer controls (ported from the browser board)
430
- // ======================================================================
431
- let spec = null;
432
- let QS = [];
433
- const state = { answers: {}, other: {}, notes: {}, comment: '', blockEdits: {}, annotations: [] };
434
- // Element-level comments: the SAME self-contained annotate engine the browser
435
- // board uses (no server — it reports the thread list via onChange). Charts,
436
- // diagram nodes, table cells, images and text selections become commentable;
437
- // the comments ride back in the submission alongside answers.
438
- const Annotate = (window.RelayAnnotate && typeof window.RelayAnnotate.init === 'function') ? window.RelayAnnotate : null;
439
- let submitted = false;
440
- const cards = {};
441
- const app = document.getElementById('app');
442
-
443
- // ---------- display mode (host-driven) ----------
444
- // GUI hosts (Claude, Codex) render their OWN full-screen control, so relay
445
- // adds no redundant button. We still declare fullscreen support in
446
- // ui/initialize and react to the host's mode change: in fullscreen the iframe
447
- // fills the window, so we center the content to a readable column.
448
- let displayMode = 'inline';
449
- function applyDisplayMode() {
450
- document.documentElement.classList.toggle('mcp-fullscreen', displayMode === 'fullscreen');
451
- reportSize();
452
- }
453
-
454
- function seedDefaults() {
455
- for (const q of QS) if (q.default !== undefined) state.answers[q.id] = q.default;
456
- // Rank questions carry a full, valid permutation so an untouched rank still
457
- // submits a meaningful order (mirrors the browser board's seedRankOrder).
458
- for (const q of QS) {
459
- if (q.type !== 'rank') continue;
460
- const opts = (q.options || []).map((o) => o.value);
461
- const prior = Array.isArray(state.answers[q.id]) ? state.answers[q.id] : [];
462
- const order = prior.filter((v, i) => opts.includes(v) && prior.indexOf(v) === i);
463
- for (const v of opts) if (!order.includes(v)) order.push(v);
464
- state.answers[q.id] = order;
465
- }
466
- for (const q of QS) if (q.type === 'allocate') state.answers[q.id] = seedAllocate(q, state.answers[q.id]);
467
- for (const q of QS) if (q.type === 'checklist') state.answers[q.id] = seedChecklist(q, state.answers[q.id]);
468
- }
469
- function seedAllocate(q, prior) {
470
- const m = prior && typeof prior === 'object' && !Array.isArray(prior) ? prior : {};
471
- const out = {};
472
- for (const o of q.options || []) out[o.value] = Math.max(0, Number(m[o.value]) || 0);
473
- return out;
474
- }
475
- function seedChecklist(q, prior) {
476
- const m = prior && typeof prior === 'object' && !Array.isArray(prior) ? prior : {};
477
- const optVals = new Set((q.options || []).map((o) => o.value));
478
- const stVals = new Set((q.statuses || []).map((s) => s.value));
479
- const out = {};
480
- for (const k of Object.keys(m)) if (optVals.has(k) && stVals.has(m[k])) out[k] = m[k];
481
- return out;
482
- }
483
-
484
- function getValue(q) {
485
- const v = state.answers[q.id];
486
- const oth = state.other[q.id];
487
- switch (q.type) {
488
- case 'single': {
489
- if (oth && oth.on) { const t = (oth.text || '').trim(); return t || undefined; }
490
- return typeof v === 'string' && v ? v : undefined;
491
- }
492
- case 'multi': {
493
- const arr = Array.isArray(v) ? [...v] : [];
494
- if (oth && oth.on) { const t = (oth.text || '').trim(); if (t) arr.push(t); }
495
- return arr.length ? arr : undefined;
496
- }
497
- case 'yesno':
498
- return v === 'yes' || v === 'no' ? v : undefined;
499
- case 'scale':
500
- return typeof v === 'number' ? v : undefined;
501
- case 'rank':
502
- return Array.isArray(v) && v.length ? [...v] : undefined;
503
- case 'checklist': {
504
- const m = v && typeof v === 'object' && !Array.isArray(v) ? v : {};
505
- return Object.keys(m).length ? { ...m } : undefined;
506
- }
507
- case 'allocate': {
508
- const m = v && typeof v === 'object' && !Array.isArray(v) ? v : {};
509
- const sum = Object.values(m).reduce((a, n) => a + (Number(n) || 0), 0);
510
- return sum > 0 ? { ...m } : undefined;
511
- }
512
- default: {
513
- const t = typeof v === 'string' ? v.trim() : '';
514
- return t || undefined;
515
- }
516
- }
517
- }
518
-
519
- function payload() {
520
- const answers = {};
521
- const notes = {};
522
- for (const q of QS) {
523
- const v = getValue(q);
524
- if (v !== undefined) answers[q.id] = v;
525
- const n = typeof state.notes[q.id] === 'string' ? state.notes[q.id].trim() : '';
526
- if (n) notes[q.id] = n;
527
- }
528
- const skipped = QS.filter((q) => !(q.id in answers)).map((q) => q.id);
529
- const blockEdits = Object.keys(state.blockEdits).length ? state.blockEdits : null;
530
- const annotations = Array.isArray(state.annotations) && state.annotations.length ? state.annotations : null;
531
- return { answers, skipped, comment: (state.comment || '').trim(), notes, blockEdits, annotations };
532
- }
533
-
534
- function clearErr(qid) { if (cards[qid]) cards[qid].classList.remove('error'); }
535
-
536
- function syncOptSel(group) {
537
- for (const lab of group.querySelectorAll('label.opt')) {
538
- const input = lab.querySelector('input');
539
- lab.classList.toggle('sel', input.checked);
540
- const wrap = lab.closest('.optwrap');
541
- if (wrap) wrap.classList.toggle('sel', input.checked);
542
- }
543
- }
544
- function withOptionBlocks(labelEl, o, questionId) {
545
- if (!Array.isArray(o.blocks) || !o.blocks.length) return labelEl;
546
- const wrap = el('div', { class: 'optwrap' + (labelEl.classList.contains('sel') ? ' sel' : '') }, labelEl);
547
- renderBlocks(wrap, o.blocks, questionId);
548
- return wrap;
549
- }
550
-
551
- function controlSingle(q) {
552
- const group = el('div');
553
- const entries = [];
554
- let otherRadio = null;
555
- const otherOn = () => Boolean(state.other[q.id] && state.other[q.id].on);
556
- const syncSingle = () => {
557
- for (const { input, value } of entries) input.checked = state.answers[q.id] === value && !otherOn();
558
- if (otherRadio) otherRadio.checked = otherOn();
559
- syncOptSel(group);
560
- clearErr(q.id);
561
- };
562
- for (const o of q.options) {
563
- const input = el('input', { type: 'radio', name: q.id });
564
- entries.push({ input, value: o.value });
565
- input.checked = state.answers[q.id] === o.value && !otherOn();
566
- input.addEventListener('click', (e) => {
567
- e.preventDefault();
568
- if (state.answers[q.id] === o.value && !otherOn()) delete state.answers[q.id];
569
- else { state.answers[q.id] = o.value; if (state.other[q.id]) state.other[q.id].on = false; }
570
- setTimeout(syncSingle, 0);
571
- });
572
- input.addEventListener('change', () => {
573
- if (!input.checked) return;
574
- state.answers[q.id] = o.value;
575
- if (state.other[q.id]) state.other[q.id].on = false;
576
- syncSingle();
577
- });
578
- group.append(withOptionBlocks(
579
- el('label', { class: 'opt' + (input.checked ? ' sel' : '') }, input,
580
- el('div', {}, el('div', { class: 'ol' }, o.label), o.description ? el('div', { class: 'od' }, o.description) : null)),
581
- o, q.id));
582
- }
583
- if (q.other) {
584
- otherRadio = el('input', { type: 'radio', name: q.id });
585
- const text = el('textarea', { class: 'otherinput', rows: '2', placeholder: 'your own answer…' });
586
- text.value = (state.other[q.id] && state.other[q.id].text) || '';
587
- otherRadio.checked = otherOn();
588
- const ensureOther = () => state.other[q.id] || (state.other[q.id] = { on: false, text: text.value });
589
- otherRadio.addEventListener('click', (e) => { e.preventDefault(); const oth = ensureOther(); oth.on = !oth.on; if (oth.on) delete state.answers[q.id]; setTimeout(syncSingle, 0); });
590
- otherRadio.addEventListener('change', () => { if (!otherRadio.checked) return; const oth = ensureOther(); oth.on = true; delete state.answers[q.id]; syncSingle(); });
591
- text.addEventListener('input', () => { const oth = ensureOther(); oth.text = text.value; if (!oth.on) { oth.on = true; delete state.answers[q.id]; } syncSingle(); });
592
- group.append(el('label', { class: 'opt' + (otherRadio.checked ? ' sel' : '') }, otherRadio,
593
- el('div', { style: 'flex:1' }, el('div', { class: 'ol' }, 'Other'), el('div', { class: 'otherbox' }, text))));
594
- }
595
- return group;
596
- }
597
-
598
- function controlMulti(q) {
599
- const group = el('div');
600
- const selected = new Set(Array.isArray(state.answers[q.id]) ? state.answers[q.id] : []);
601
- const readChecked = () => {
602
- state.answers[q.id] = [...group.querySelectorAll('input[data-val]')].filter((i) => i.checked).map((i) => i.dataset.val);
603
- syncOptSel(group);
604
- clearErr(q.id);
605
- };
606
- for (const o of q.options) {
607
- const input = el('input', { type: 'checkbox', 'data-val': o.value });
608
- input.checked = selected.has(o.value);
609
- input.addEventListener('change', readChecked);
610
- group.append(withOptionBlocks(
611
- el('label', { class: 'opt' + (input.checked ? ' sel' : '') }, input,
612
- el('div', {}, el('div', { class: 'ol' }, o.label), o.description ? el('div', { class: 'od' }, o.description) : null)),
613
- o, q.id));
614
- }
615
- if (q.other) {
616
- const oth = state.other[q.id];
617
- const box = el('input', { type: 'checkbox' });
618
- const text = el('textarea', { class: 'otherinput', rows: '2', placeholder: 'your own answer…' });
619
- box.checked = Boolean(oth && oth.on);
620
- text.value = (oth && oth.text) || '';
621
- const sync = () => { state.other[q.id] = { on: box.checked, text: text.value }; syncOptSel(group); clearErr(q.id); };
622
- box.addEventListener('change', sync);
623
- text.addEventListener('input', () => { if (!box.checked) box.checked = true; sync(); });
624
- group.append(el('label', { class: 'opt' + (box.checked ? ' sel' : '') }, box,
625
- el('div', { style: 'flex:1' }, el('div', { class: 'ol' }, 'Other'), el('div', { class: 'otherbox' }, text))));
626
- }
627
- return group;
628
- }
629
-
630
- function segButtons(q, values, labels) {
631
- const seg = el('div', { class: q.type === 'scale' ? 'scale' : 'seg' });
632
- const buttons = [];
633
- values.forEach((v, i) => {
634
- const b = el('button', { type: 'button' }, labels[i]);
635
- if (state.answers[q.id] === v) b.classList.add('sel');
636
- b.addEventListener('click', () => {
637
- if (state.answers[q.id] === v) delete state.answers[q.id];
638
- else state.answers[q.id] = v;
639
- for (const x of buttons) x.classList.toggle('sel', state.answers[q.id] === values[buttons.indexOf(x)]);
640
- clearErr(q.id);
641
- });
642
- buttons.push(b);
643
- seg.append(b);
644
- });
645
- return seg;
646
- }
647
- function controlScale(q) {
648
- const values = [];
649
- for (let i = q.min; i <= q.max; i++) values.push(i);
650
- const seg = segButtons(q, values, values.map(String));
651
- const row = el('div', { class: 'scale' });
652
- if (q.minLabel) row.append(el('span', { class: 'slabel' }, q.minLabel));
653
- row.append(...seg.children);
654
- if (q.maxLabel) row.append(el('span', { class: 'slabel' }, q.maxLabel));
655
- return row;
656
- }
657
- function controlText(q, multiline) {
658
- const input = multiline
659
- ? el('textarea', { placeholder: q.placeholder || '' })
660
- : el('input', { type: 'text', placeholder: q.placeholder || '' });
661
- input.value = typeof state.answers[q.id] === 'string' ? state.answers[q.id] : '';
662
- input.addEventListener('input', () => { state.answers[q.id] = input.value; clearErr(q.id); });
663
- return input;
664
- }
665
- // Checklist / allocate — see the browser board's controls (no autosave here).
666
- function controlChecklist(q) {
667
- const wrap = el('div', { class: 'checklist' });
668
- const cur = () => (state.answers[q.id] && typeof state.answers[q.id] === 'object' && !Array.isArray(state.answers[q.id])
669
- ? state.answers[q.id] : (state.answers[q.id] = {}));
670
- for (const o of q.options) {
671
- const seg = el('div', { class: 'chk-seg' });
672
- const buttons = [];
673
- for (const s of q.statuses) {
674
- const b = el('button', { type: 'button', class: 'chk-status' + (s.tone ? ' tone-' + s.tone : '') }, s.label);
675
- if (cur()[o.value] === s.value) b.classList.add('sel');
676
- b.addEventListener('click', () => {
677
- const m = cur();
678
- if (m[o.value] === s.value) delete m[o.value];
679
- else m[o.value] = s.value;
680
- for (const x of buttons) x.btn.classList.toggle('sel', m[o.value] === x.val);
681
- clearErr(q.id);
682
- });
683
- buttons.push({ btn: b, val: s.value });
684
- seg.append(b);
685
- }
686
- wrap.append(el('div', { class: 'chk-row' },
687
- el('div', { class: 'chk-body' }, el('div', { class: 'ol' }, o.label), o.description ? el('div', { class: 'od' }, o.description) : null),
688
- seg));
689
- }
690
- return wrap;
691
- }
692
- function controlAllocate(q) {
693
- const wrap = el('div', { class: 'allocate' });
694
- const total = q.total || 100;
695
- const unit = q.unit ? ' ' + q.unit : '';
696
- const cur = () => (state.answers[q.id] = seedAllocate(q, state.answers[q.id]));
697
- const sumEl = el('span', { class: 'alloc-sum' });
698
- const fill = el('div', { class: 'alloc-bar-fill' });
699
- const nums = [];
700
- const refresh = () => {
701
- const m = cur();
702
- const sum = (q.options || []).reduce((a, o) => a + (Number(m[o.value]) || 0), 0);
703
- const tail = sum > total ? ' (over by ' + (sum - total) + ')' : sum < total ? ' (' + (total - sum) + ' left)' : ' ✓';
704
- sumEl.textContent = sum + ' / ' + total + unit + tail;
705
- sumEl.classList.toggle('over', sum > total);
706
- sumEl.classList.toggle('exact', sum === total);
707
- fill.style.width = Math.min(100, (sum / total) * 100) + '%';
708
- fill.classList.toggle('over', sum > total);
709
- for (const n of nums) n.el.textContent = String(m[n.value] || 0);
710
- };
711
- for (const o of q.options) {
712
- const m = cur();
713
- const range = el('input', { type: 'range', min: '0', max: String(total), step: '1', class: 'alloc-range', 'aria-label': o.label });
714
- range.value = String(m[o.value] || 0);
715
- const num = el('span', { class: 'alloc-num' }, String(m[o.value] || 0));
716
- range.addEventListener('input', () => { cur()[o.value] = Number(range.value) || 0; refresh(); clearErr(q.id); });
717
- nums.push({ value: o.value, el: num });
718
- wrap.append(el('div', { class: 'alloc-row' },
719
- el('div', { class: 'alloc-rowhead' }, el('div', { class: 'ol' }, o.label), num),
720
- range,
721
- o.description ? el('div', { class: 'od' }, o.description) : null));
722
- }
723
- wrap.append(el('div', { class: 'alloc-total' },
724
- el('div', { class: 'alloc-bar' }, fill),
725
- el('div', { class: 'alloc-sumwrap' }, 'Total: ', sumEl)));
726
- refresh();
727
- return wrap;
728
- }
729
- // Reorderable priority list — see the browser board's controlRank. Answer is
730
- // the ordered array of option values (highest first); always a full permutation.
731
- function controlRank(q) {
732
- const wrap = el('div', { class: 'rank' });
733
- const byVal = new Map(q.options.map((o) => [o.value, o]));
734
- let dragFrom = null;
735
- function move(from, to) {
736
- const arr = state.answers[q.id];
737
- if (!Array.isArray(arr) || to < 0 || to >= arr.length || from === to) return;
738
- const [x] = arr.splice(from, 1);
739
- arr.splice(to, 0, x);
740
- paint();
741
- clearErr(q.id);
742
- }
743
- function paint() {
744
- wrap.replaceChildren();
745
- const order = state.answers[q.id] || [];
746
- order.forEach((val, i) => {
747
- const o = byVal.get(val);
748
- if (!o) return;
749
- const up = el('button', { type: 'button', class: 'rank-btn', title: 'Move up', 'aria-label': 'Move "' + o.label + '" up' }, '↑');
750
- const down = el('button', { type: 'button', class: 'rank-btn', title: 'Move down', 'aria-label': 'Move "' + o.label + '" down' }, '↓');
751
- up.disabled = i === 0;
752
- down.disabled = i === order.length - 1;
753
- up.addEventListener('click', () => move(i, i - 1));
754
- down.addEventListener('click', () => move(i, i + 1));
755
- const item = el('div', { class: 'rank-item', draggable: 'true' },
756
- el('span', { class: 'rank-badge', 'aria-hidden': 'true' }, String(i + 1)),
757
- el('div', { class: 'rank-body' },
758
- el('div', { class: 'ol' }, o.label),
759
- o.description ? el('div', { class: 'od' }, o.description) : null),
760
- el('div', { class: 'rank-ctrls' }, up, down)
761
- );
762
- item.addEventListener('dragstart', (e) => {
763
- dragFrom = i; item.classList.add('dragging');
764
- try { e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('text/plain', String(i)); } catch (_) {}
765
- });
766
- item.addEventListener('dragend', () => { dragFrom = null; item.classList.remove('dragging'); });
767
- item.addEventListener('dragover', (e) => { if (dragFrom !== null) { e.preventDefault(); item.classList.add('drop-into'); } });
768
- item.addEventListener('dragleave', () => item.classList.remove('drop-into'));
769
- item.addEventListener('drop', (e) => {
770
- e.preventDefault();
771
- const from = dragFrom; dragFrom = null;
772
- if (from !== null && from !== i) move(from, i);
773
- });
774
- wrap.append(item);
775
- });
776
- }
777
- paint();
778
- return wrap;
779
- }
780
-
781
- // Resolve any CSS color (named/rgb/hsl/hex) to #rrggbb via the browser parser.
782
- function cssColorToHex(str) {
783
- const s = String(str || '').trim();
784
- let m = /^#?([0-9a-fA-F]{6})$/.exec(s);
785
- if (m) return '#' + m[1].toLowerCase();
786
- m = /^#?([0-9a-fA-F]{3})$/.exec(s);
787
- if (m) return '#' + m[1].split('').map((x) => x + x).join('').toLowerCase();
788
- try {
789
- const d = document.createElement('div');
790
- d.style.color = '';
791
- d.style.color = s;
792
- if (!d.style.color) return null;
793
- d.style.display = 'none';
794
- document.body.appendChild(d);
795
- const rgb = getComputedStyle(d).color;
796
- document.body.removeChild(d);
797
- const mm = rgb.match(/(\d+)[,\s]+(\d+)[,\s]+(\d+)/);
798
- if (!mm) return null;
799
- const h = (n) => Math.max(0, Math.min(255, Number(n))).toString(16).padStart(2, '0');
800
- return '#' + h(mm[1]) + h(mm[2]) + h(mm[3]);
801
- } catch { return null; }
802
- }
803
- function toHex6(c) { return cssColorToHex(c) || '#000000'; }
804
- function controlColor(q) {
805
- const wrap = el('div', { class: 'colorpick' });
806
- const init = (typeof state.answers[q.id] === 'string' && state.answers[q.id]) || (typeof q.default === 'string' ? q.default : '');
807
- const swatch = el('input', { type: 'color', class: 'colorswatch' });
808
- const hex = el('input', { type: 'text', class: 'colorhex', placeholder: q.placeholder || '#rrggbb / rgb() / name', spellcheck: 'false', autocapitalize: 'off' });
809
- swatch.value = toHex6(init || '#888888');
810
- if (init) { hex.value = init; state.answers[q.id] = init; }
811
- let syncPaletteSel = () => {};
812
- const set = (val) => { state.answers[q.id] = val; syncPaletteSel(); clearErr(q.id); };
813
- swatch.addEventListener('input', () => { hex.value = swatch.value; set(swatch.value); });
814
- hex.addEventListener('input', () => { const v = hex.value.trim(); const h = cssColorToHex(v); if (h) swatch.value = h; set(v); });
815
- if (Array.isArray(q.palette) && q.palette.length) {
816
- const grid = el('div', { class: 'colorpalette' });
817
- const cards = [];
818
- for (const p of q.palette) {
819
- const labelled = p.label && p.label !== p.value;
820
- const card = el('button', { type: 'button', class: 'colorpal-sw', style: 'background:' + p.value, title: (labelled ? p.label + ' · ' : '') + p.value });
821
- if (labelled) card.append(el('span', { class: 'colorpal-label' }, p.label));
822
- card.addEventListener('click', () => { const h = cssColorToHex(p.value); if (h) swatch.value = h; hex.value = p.value; set(p.value); });
823
- if (Annotate && !composing) Annotate.register(card, { blockId: null, questionId: q.id, target: { kind: 'swatch', label: (labelled ? p.label + ' · ' : '') + p.value } });
824
- cards.push({ card, val: p.value });
825
- grid.append(card);
826
- }
827
- syncPaletteSel = () => { for (const c of cards) c.card.classList.toggle('sel', state.answers[q.id] === c.val); };
828
- wrap.append(grid);
829
- }
830
- wrap.append(el('div', { class: 'colorrow' }, swatch, hex));
831
- if (Array.isArray(q.presets) && q.presets.length) {
832
- const presets = el('div', { class: 'colorpresets' });
833
- for (const c of q.presets) {
834
- const b = el('button', { type: 'button', class: 'colorpreset', style: 'background:' + c, title: c });
835
- b.addEventListener('click', () => { const h = cssColorToHex(c); if (h) swatch.value = h; hex.value = c; set(c); });
836
- presets.append(b);
837
- }
838
- wrap.append(presets);
839
- }
840
- syncPaletteSel();
841
- return wrap;
842
- }
843
-
844
- // ======================================================================
845
- // render
846
- // ======================================================================
847
- function render() {
848
- app.replaceChildren();
849
- const annotateOn = !composing && Annotate;
850
- const titleEl = el('h1', {}, spec.title);
851
- app.append(el('header', { class: 'qb-header' }, titleEl));
852
- if (annotateOn) Annotate.register(titleEl, { blockId: null, questionId: null, target: { kind: 'html-element', label: spec.title } });
853
- if (spec.intro) {
854
- const md = window.RelayBlocks && RelayBlocks.renderMarkdown;
855
- const introEl = md
856
- ? el('div', { class: 'intro blk-markdown' }, RelayBlocks.renderMarkdown(spec.intro))
857
- : el('p', { class: 'intro' }, spec.intro);
858
- app.append(introEl);
859
- if (annotateOn) Annotate.enableTextSelection(introEl, { blockId: null, questionId: null });
860
- }
861
- renderBlocks(app, spec.blocks || [], null);
862
-
863
- QS.forEach((q, idx) => {
864
- const required = q.required || !spec.allowPartial;
865
- const card = el('div', { class: 'card' },
866
- el('div', { class: 'qnum' }, 'Q' + (idx + 1)),
867
- el('p', { class: 'qlabel' }, q.label, required ? el('span', { class: 'req' }, ' *') : null),
868
- q.description ? el('p', { class: 'qdesc' }, q.description) : null);
869
- renderBlocks(card, q.blocks || [], q.id);
870
- const control = el('div', { class: 'control' });
871
- if (q.type === 'single') control.append(controlSingle(q));
872
- else if (q.type === 'multi') control.append(controlMulti(q));
873
- else if (q.type === 'yesno') control.append(segButtons(q, ['yes', 'no'], ['Yes', 'No']));
874
- else if (q.type === 'scale') control.append(controlScale(q));
875
- else if (q.type === 'color') control.append(controlColor(q));
876
- else if (q.type === 'rank') control.append(controlRank(q));
877
- else if (q.type === 'checklist') control.append(controlChecklist(q));
878
- else if (q.type === 'allocate') control.append(controlAllocate(q));
879
- else control.append(controlText(q, q.type === 'textarea'));
880
- card.append(control);
881
- if (q.note) {
882
- const noteInput = el('textarea', { class: 'qnote', rows: 2, placeholder: 'optional note about this answer…' });
883
- noteInput.value = typeof state.notes[q.id] === 'string' ? state.notes[q.id] : '';
884
- noteInput.addEventListener('input', () => { state.notes[q.id] = noteInput.value; });
885
- card.append(el('div', { class: 'qnotewrap' }, noteInput));
886
- }
887
- card.append(el('p', { class: 'errmsg' }, 'This question is required.'));
888
- cards[q.id] = card;
889
- app.append(card);
890
- });
891
-
892
- if (spec.note && spec.responseRequired !== false) {
893
- const note = el('textarea', { placeholder: 'optional note back to the agent…' });
894
- note.value = state.comment || '';
895
- note.addEventListener('input', () => { state.comment = note.value; });
896
- app.append(el('div', { class: 'card' },
897
- el('p', { class: 'qlabel' }, 'Anything else?'),
898
- el('p', { class: 'qdesc' }, 'Free-text note returned to the agent along with your answers.'),
899
- el('div', { class: 'control' }, note)));
900
- }
901
-
902
- if (composing) {
903
- // still streaming in — show a live "composing" note, no submit yet
904
- app.append(el('div', { class: 'submitbar' }, el('span', { class: 'mcp-composing' }, 'Composing this board…')));
905
- reportSize();
906
- return;
907
- }
908
- if (spec.responseRequired === false) {
909
- app.append(el('div', { class: 'submitbar display-only' },
910
- el('span', { class: 'hint' }, 'Display only · no response requested')));
911
- reportSize();
912
- return;
913
- }
914
- const submitBtn = el('button', { class: 'submit', type: 'button' }, spec.submitLabel);
915
- const saveEl = el('span', { class: 'savestate' }, '');
916
- const hint = el('span', { class: 'hint' }, QS.length && spec.allowPartial ? 'Unanswered questions are returned as skipped.' : '');
917
- submitBtn.addEventListener('click', () => onSubmit(submitBtn, saveEl));
918
- app.append(el('div', { class: 'submitbar' }, submitBtn, hint, saveEl));
919
- reportSize();
920
- }
921
-
922
- function validate() {
923
- let firstBad = null;
924
- for (const q of QS) {
925
- const required = q.required || !spec.allowPartial;
926
- const bad = required && getValue(q) === undefined;
927
- cards[q.id].classList.toggle('error', bad);
928
- if (bad && !firstBad) firstBad = cards[q.id];
929
- }
930
- if (firstBad) firstBad.scrollIntoView({ behavior: 'smooth', block: 'center' });
931
- return !firstBad;
932
- }
933
-
934
- // A human-readable transcript of the submission — so the agent reads the
935
- // answers even on a host that doesn't surface structuredContent.
936
- function summarize(data) {
937
- const lines = [];
938
- lines.push('The user submitted the relay board "' + spec.title + '".');
939
- if (QS.length) {
940
- lines.push('', 'Answers:');
941
- for (const q of QS) {
942
- const v = data.answers[q.id];
943
- let shown;
944
- if (v === undefined) shown = '(skipped)';
945
- else if (Array.isArray(v)) shown = v.join(', ');
946
- else shown = String(v);
947
- lines.push('- ' + q.label + ' [' + q.id + ']: ' + shown);
948
- if (data.notes[q.id]) lines.push(' note: ' + data.notes[q.id]);
949
- }
950
- }
951
- if (data.comment) lines.push('', 'Comment: ' + data.comment);
952
- if (data.annotations && data.annotations.length) {
953
- lines.push('', 'Inline comments (' + data.annotations.length + '):');
954
- for (const a of data.annotations) {
955
- const where = (a.target && (a.target.label || a.target.text || a.target.kind)) || a.blockId || 'element';
956
- const crop = a.target && a.target.crop;
957
- const cropNote = crop && crop.path ? ' · crop: ' + crop.path : crop && crop.data ? ' · image crop attached' : '';
958
- lines.push('- [' + where + ']: ' + a.text + cropNote);
959
- }
960
- }
961
- if (data.blockEdits) lines.push('', 'Edited diagrams: ' + Object.keys(data.blockEdits).join(', '));
962
- return lines.join('\n');
963
- }
964
-
965
- async function onSubmit(submitBtn, saveEl) {
966
- if (submitted) return;
967
- if (!validate()) return;
968
- submitBtn.disabled = true;
969
- submitBtn.textContent = 'Submitting…';
970
- const data = payload();
971
- const structured = {
972
- boardId: BOOT.boardId || null,
973
- status: QS.length ? 'submitted' : 'acknowledged',
974
- answers: data.answers,
975
- skipped: data.skipped,
976
- notes: data.notes,
977
- comment: data.comment,
978
- blockEdits: data.blockEdits,
979
- annotations: data.annotations,
980
- };
981
- const text = summarize(data);
982
- const messageContent = [{ type: 'text', text }];
983
- for (const a of data.annotations || []) {
984
- const crop = a && a.target && a.target.crop;
985
- if (!crop || typeof crop.data !== 'string' || !crop.data) continue;
986
- messageContent.push({ type: 'image', data: crop.data, mimeType: crop.mime || 'image/png' });
987
- }
988
- let messageDelivered = false;
989
- let contextDelivered = false;
990
- try {
991
- // A completed relay form is a user reply, not passive context. Some hosts
992
- // ACK `ui/update-model-context` without starting a new model turn, so send
993
- // the transcript as a user message first to wake the agent reliably.
994
- await request('ui/message', { role: 'user', content: messageContent });
995
- messageDelivered = true;
996
- } catch {
997
- // Older hosts may not advertise image content or may implement the early
998
- // single-content draft. Preserve the text wake path before giving up.
999
- try {
1000
- await request('ui/message', { role: 'user', content: [{ type: 'text', text }] });
1001
- messageDelivered = true;
1002
- } catch {
1003
- try {
1004
- await request('ui/message', { role: 'user', content: { type: 'text', text } });
1005
- messageDelivered = true;
1006
- } catch { /* app-initiated messages unavailable */ }
1007
- }
1008
- }
1009
- try {
1010
- // Keep the structured payload available to hosts that attach app context.
1011
- // This is best-effort because context updates are intentionally silent.
1012
- await request('ui/update-model-context', { content: messageContent, structuredContent: structured });
1013
- contextDelivered = true;
1014
- } catch {
1015
- try {
1016
- await request('ui/update-model-context', { content: [{ type: 'text', text }], structuredContent: structured });
1017
- contextDelivered = true;
1018
- } catch { /* ui/message may still have delivered the result */ }
1019
- }
1020
- submitted = true;
1021
- showDone(messageDelivered, contextDelivered);
1022
- }
1023
-
1024
- function showDone(messageDelivered, contextDelivered) {
1025
- // Collapse: leave fullscreen, drop the whole form for a one-line confirmation
1026
- // so the host shrinks the iframe to a small footprint in the transcript.
1027
- if (Annotate) { try { Annotate.teardown(); } catch { /* nothing to tear down */ } }
1028
- document.documentElement.classList.remove('mcp-fullscreen');
1029
- app.replaceChildren(el('div', { class: 'mcp-done' },
1030
- el('span', { class: 'mark' }, '✓'),
1031
- el('span', { class: 'lead' }, QS.length ? 'Submitted' : 'Acknowledged'),
1032
- el('span', { class: 'sub' }, messageDelivered
1033
- ? '· sent back to the agent'
1034
- : contextDelivered
1035
- ? '· saved; send the agent a message to continue'
1036
- : '· tell the agent you’ve responded')));
1037
- // Report the small height immediately, then again next frame / after layout
1038
- // settles — beats hosts that only grow on debounced size events.
1039
- reportSizeNow();
1040
- if (typeof requestAnimationFrame === 'function') requestAnimationFrame(reportSizeNow);
1041
- setTimeout(reportSizeNow, 150);
1042
- }
1043
-
1044
- // ======================================================================
1045
- // boot
1046
- // ======================================================================
1047
- function setStatus(text) {
1048
- const s = document.getElementById('mcp-status');
1049
- if (s) s.textContent = text;
1050
- }
1051
-
1052
- let booted = false;
1053
- async function boot(rawOrNormalized, alreadyNormalized) {
1054
- if (booted || submitted) return;
1055
- const next = alreadyNormalized ? rawOrNormalized : clientNormalize(rawOrNormalized);
1056
- if (!next || (!Array.isArray(next.questions)) ) { return; }
1057
- if (!next.questions.length && !(Array.isArray(next.blocks) && next.blocks.length)) return;
1058
- booted = true;
1059
- composing = false;
1060
- if (previewTimer) { clearTimeout(previewTimer); previewTimer = null; }
1061
- spec = next;
1062
- QS = spec.questions || [];
1063
- seedDefaults();
1064
- indexHtmlBlocks(spec);
1065
- setStatus('Preparing…');
1066
- if (Annotate && spec.responseRequired !== false) {
1067
- Annotate.init({ initial: [], onChange: (a) => { state.annotations = Array.isArray(a) ? a : []; } });
1068
- } else if (Annotate && typeof Annotate.teardown === 'function') {
1069
- Annotate.teardown();
1070
- }
1071
- try { await preloadVendors(spec); } catch { /* render anyway; blocks degrade individually */ }
1072
- render();
1073
- applyDisplayMode();
1074
- }
1075
-
1076
- // Progressive preview: the host MAY stream the tool call's JSON as the agent
1077
- // writes it (ui/notifications/tool-input-partial — unclosed JSON auto-closed
1078
- // into a valid object). We render whatever blocks/questions are already valid
1079
- // so the board appears incrementally instead of only after the whole spec is
1080
- // generated. It's a read-only preview — submit is withheld until the final
1081
- // input/result arrives. Degrades to nothing on hosts that don't stream.
1082
- let composing = false;
1083
- let previewTimer = null;
1084
- let vendorsKicked = false;
1085
- function renderPreview(rawArgs) {
1086
- if (booted || submitted) return;
1087
- const next = clientNormalize(rawArgs);
1088
- if (!next) return;
1089
- const hasContent = (next.questions && next.questions.length) || (Array.isArray(next.blocks) && next.blocks.length);
1090
- if (!hasContent) return;
1091
- spec = next;
1092
- QS = spec.questions || [];
1093
- composing = true;
1094
- indexHtmlBlocks(spec);
1095
- if (!vendorsKicked) { vendorsKicked = true; preloadVendors(spec).catch(() => {}); }
1096
- if (previewTimer) return; // coalesce a burst of partials into one paint
1097
- previewTimer = setTimeout(() => { previewTimer = null; if (!booted && !submitted) render(); }, 120);
1098
- }
1099
-
1100
- // The spec can arrive as the tool RESULT (preferred — server-normalized) or,
1101
- // on a leaner host, as the tool INPUT (raw). Prefer the result: when raw input
1102
- // lands first, hold briefly for a result before falling back to the input.
1103
- let rawInputTimer = null;
1104
- onNotify('ui/notifications/tool-result', (p) => {
1105
- if (rawInputTimer) { clearTimeout(rawInputTimer); rawInputTimer = null; }
1106
- const sc = p && p.structuredContent;
1107
- if (sc && sc.spec) return boot(sc.spec, true);
1108
- // Some hosts may echo the spec at the top level of structuredContent.
1109
- if (sc && Array.isArray(sc.questions)) return boot(sc, true);
1110
- });
1111
- onNotify('ui/notifications/tool-input', (p) => {
1112
- const args = p && p.arguments;
1113
- if (!args || typeof args !== 'object' || booted || rawInputTimer) return;
1114
- rawInputTimer = setTimeout(() => { rawInputTimer = null; boot(args, false); }, 250);
1115
- });
1116
- onNotify('ui/notifications/tool-input-partial', (p) => {
1117
- const args = p && p.arguments;
1118
- if (args && typeof args === 'object') renderPreview(args);
1119
- });
1120
- onNotify('ui/notifications/host-context-changed', (p) => {
1121
- if (p && typeof p === 'object') {
1122
- if ('theme' in p) host.theme = p.theme;
1123
- if ('styles' in p) host.styles = p.styles;
1124
- if ('platform' in p) host.platform = p.platform;
1125
- if ('safeAreaInsets' in p) host.safeAreaInsets = p.safeAreaInsets;
1126
- if ('deviceCapabilities' in p) host.deviceCapabilities = p.deviceCapabilities;
1127
- if (p.displayMode === 'inline' || p.displayMode === 'fullscreen' || p.displayMode === 'pip') {
1128
- displayMode = p.displayMode;
1129
- applyDisplayMode();
1130
- }
1131
- adoptHostStyles();
1132
- applyHostEnv();
1133
- applyTheme();
1134
- }
1135
- });
1136
-
1137
- // Kick off the handshake. Proceed even if the host doesn't answer init.
1138
- // SEP-1865 lifecycle: ui/initialize → (host reply) → ui/notifications/initialized.
1139
- // The host MUST NOT send tool-input / tool-result (i.e. the board spec) until
1140
- // it receives `initialized`, so this notification is mandatory — without it the
1141
- // board never gets its spec and never renders.
1142
- (async () => {
1143
- try {
1144
- const res = await request('ui/initialize', {
1145
- protocolVersion: PROTOCOL,
1146
- capabilities: {},
1147
- clientInfo: { name: 'relay', version: String(BOOT.version || '0') },
1148
- appCapabilities: { availableDisplayModes: ['inline', 'fullscreen'] },
1149
- });
1150
- host = (res && res.hostContext) || {};
1151
- } catch {
1152
- host = {};
1153
- }
1154
- if (host.displayMode === 'fullscreen' || host.displayMode === 'pip') displayMode = host.displayMode;
1155
- notify('ui/notifications/initialized', {});
1156
- adoptHostStyles();
1157
- applyHostEnv();
1158
- applyTheme();
1159
- setStatus('Waiting for the board…');
1160
- reportSize();
1161
- })();
1162
- })();