@khanglvm/relay 0.16.1 → 0.17.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.
package/src/cli.js CHANGED
@@ -1066,72 +1066,26 @@ function stampSkillVersion() {
1066
1066
  // AGENTS.md, …). A skill is only a tier-1 hint that agents can ignore; these
1067
1067
  // rules, appended to the instructions the agent always reads, enforce usage.
1068
1068
  // Printed to stdout so `rly skill rules >> CLAUDE.md` is the whole install.
1069
- const SKILL_RULES = `## relay — show it in the browser, don't dump it in the terminal
1070
-
1071
- **Why:** your output surface — a terminal, an IDE side-panel (VS Code, JetBrains,
1072
- Cursor), a plain-text chat — can't actually render a markdown file, an image, a
1073
- chart, a table, a diagram, or a diff. It shows them as walls of monospace text, or
1074
- not at all (a terminal can't display a PNG). relay opens a real browser board that
1075
- renders them properly AND reads the user's reply back as JSON. **Rule of thumb: if
1076
- what you're about to output would look better than monospace text — or is a file
1077
- the user should view — put it in relay instead of printing it.**
1078
-
1079
- - **Markdown file / doc / README / plan / report** → \`rly view file.md\` (renders it
1080
- in the browser, no library; \`.csv\`/\`.json\` → a sortable table; \`.pdf\` → an
1081
- inline PDF viewer). Never \`cat\` a doc into the terminal for the user to read.
1082
- - **Image / screenshot / mockup / diagram / chart / table** → a relay board with an
1083
- \`image\` block (or \`mermaid\`/\`graphviz\`/\`chart\`/\`table\`/\`kpi\`/\`compare\`). The
1084
- terminal can't show pixels; relay can — with click-to-zoom and comment-in-place.
1085
- - **The user's decisions, feedback, requirements, or approval** (anything beyond one
1086
- trivial yes/no) → a relay board, NOT plain terminal text and NOT the native
1087
- \`AskUserQuestion\` / ask-user tool. Build a spec and run
1088
- \`rly ask --file spec.json --detach\`, then \`rly wait <boardId>\`. **Holds in plan
1089
- mode too**; reserve \`ExitPlanMode\` for the final plan-approval gate only.
1090
- - **Codex-specific browser-board pattern:** Codex does not have a normal,
1091
- user-facing "wake this agent turn from a browser submit" command. In Codex,
1092
- keep the waiter in the foreground until the user submits:
1093
- \`rly ask --file spec.json --detach\` then
1094
- \`rly wait <boardId> --timeout 86400 --while-active --idle-grace 3600\`.
1095
- If wait exits with \`wait-timeout\`, immediately run \`rly result <boardId>\`;
1096
- if it is still open and the user may continue, run \`rly wait\` again. Do not
1097
- use \`--on-result\` as the primary Codex return path; normal Codex CLI sessions
1098
- do not expose a portable inbound API that wakes the current agent turn.
1099
- Detached boards are durable: a board timeout hands the agent a \`timeout\`
1100
- result but keeps the same URL/port serving until Submit or \`rly stop\`. Do
1101
- not create a new board just because a wait timed out.
1102
- - **No response needed** → \`rly show --file spec.json --display-only\`. It
1103
- returns immediately and shows no note, comments, or Submit/Acknowledge action.
1104
- In MCP App mode, \`relay_show\` is display-only by default; \`relay_ask\` is the
1105
- response-bearing tool.
1106
- - **A plan, structure, architecture, data, or prototype** → a relay board with
1107
- diagram/chart/table/code/image/html blocks — never ASCII diagrams or walls of prose.
1108
- - **"Show me the diff / git diff / these changes"** → \`rly diff\` (runs git diff →
1109
- a diff board), or render diff text in a \`diff\` block — never paste a raw diff.
1110
- - **Git pick/cherry-pick/conflict decisions** → \`rly git pick\`, \`rly git cherry-pick\`,
1111
- or \`rly git conflict [files]\`. Conflict boards can also be authored with a
1112
- \`git-conflict\` block from inline \`content\` or a local \`file\`/\`path\`; user
1113
- hunk choices come back in \`result.blockEdits[blockId]\` with resolved content.
1114
- - Point the user at a file with a clickable local path in a markdown block; embed a
1115
- screen recording with a \`video\` block; when answer choices are visual, give each
1116
- option its own visual (\`options[].blocks\`) so the user picks by looking.
1117
- - Same-Wi-Fi sharing is locked by default. When the user wants another device to
1118
- review or co-fill a running board, manage explicit links with \`rly share <id>\`:
1119
- \`--role review\` creates an answer/comment link whose submissions are reference-only
1120
- side reviews (\`rly result\` exposes them but they never complete \`rly wait\`),
1121
- \`--role collab\` creates an owner-authorized edit/comment/final-submit link,
1122
- \`--role read\` creates a view-only link, and \`--revoke\` disables active links. Active
1123
- share links are durable across same-port \`rly reopen\`/\`rly rescue\` until
1124
- revoked.
1125
- - **There's a purpose-built component for most content — use the MOST SPECIFIC one,
1126
- never plain prose when a block fits.** Blocks: \`table\` (sortable/filterable/CSV,
1127
- load from .csv/.json), \`chart\`, \`kpi\` (stat cards), \`mermaid\`/\`graphviz\`/\`plantuml\`,
1128
- \`code\`, \`diff\`, \`git-conflict\`, \`image\` (drag for crop comments; Space-drag/middle-button to pan; +\`pins\` for points), \`compare\` (before/after with side-aware area crops; divider-handle drag), \`video\`, \`pdf\`, \`palette\`,
1129
- \`typography\`, \`html\`. Question types: \`single\`/\`multi\`/\`yesno\`/\`scale\`/\`color\`/
1130
- \`text\`/\`textarea\` plus \`rank\` (prioritize), \`allocate\` (split a budget), \`checklist\`
1131
- (per-item sign-off). For a business user, reach for \`kpi\`+\`chart\`+\`table\` and
1132
- \`rank\`/\`allocate\`/\`checklist\`; full menu + fields: \`rly agent\` and \`rly schema\`.
1133
- - Read the result JSON from stdout; treat \`comment\` and \`annotations\` as
1134
- first-class feedback. Full guide: \`rly agent\`.`;
1069
+ const SKILL_RULES = `## relay — visual boards and structured feedback
1070
+
1071
+ - Use Relay for files, visuals, plans, diffs, and multiple related questions.
1072
+ Keep brief answers and progress updates in chat; follow existing user authorization.
1073
+ - Show without feedback: \`rly show --file spec.json --display-only\` (no waiter).
1074
+ Collect input: \`rly ask --file spec.json --detach\`, then keep
1075
+ \`rly wait <boardId> --timeout 1800 --while-active --idle-grace 300\` in the
1076
+ foreground. If it times out, read \`rly result <boardId>\` before continuing.
1077
+ - Use the most specific block: table/chart/kpi for data, image/compare for visuals,
1078
+ code/diff for source, mermaid for flows, markdown for prose, html for custom UI.
1079
+ \`rly view\`, \`rly diff\`, and \`rly git\` are shortcuts; visual options use \`options[].blocks\`.
1080
+ - Browser file links such as \`[source](/absolute/app.js:98)\` open supported files
1081
+ in a modal and highlight source lines. Unsupported files offer Open in app.
1082
+ For inline MCP or shared reviewers, embed file content as blocks instead.
1083
+ - Reconnect existing boards by ID with \`rly rescue\` / \`rly reopen\`; update
1084
+ content with \`rly update\`. Preserve the original port and saved input.
1085
+ - Read answers, notes, comment, annotations, and blockEdits together. Use the
1086
+ returned resultFile when stdout is truncated; a timeout is not an answer.
1087
+ - Full skill: \`rly skill path\`; fields: \`rly schema\`; advanced recipes and
1088
+ sharing permissions: \`rly agent\`. Load details only when needed.`;
1135
1089
 
1136
1090
  function cmdSkill(rest) {
1137
1091
  const sub = rest[0];
@@ -0,0 +1,61 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { normalizeSpec } from './spec.js';
4
+
5
+ const TEXT_LIMIT = 1024 * 1024;
6
+ const MEDIA = {
7
+ '.png': ['image', 'image/png'], '.jpg': ['image', 'image/jpeg'], '.jpeg': ['image', 'image/jpeg'],
8
+ '.gif': ['image', 'image/gif'], '.webp': ['image', 'image/webp'], '.avif': ['image', 'image/avif'],
9
+ '.svg': ['image', 'image/svg+xml'], '.ico': ['image', 'image/x-icon'],
10
+ '.pdf': ['pdf', 'application/pdf'],
11
+ '.mp4': ['video', 'video/mp4'], '.webm': ['video', 'video/webm'], '.ogv': ['video', 'video/ogg'],
12
+ '.mov': ['video', 'video/quicktime'], '.m4v': ['video', 'video/mp4'],
13
+ '.mp3': ['audio', 'audio/mpeg'], '.wav': ['audio', 'audio/wav'], '.ogg': ['audio', 'audio/ogg'],
14
+ '.m4a': ['audio', 'audio/mp4'], '.flac': ['audio', 'audio/flac'],
15
+ };
16
+
17
+ // Source citations use :line[:column] or #Lline[-Lend]. Strip before resolving
18
+ // and allowlisting; the browser never chooses an unrelated filesystem target.
19
+ export function splitFileReference(raw) {
20
+ const value = String(raw || '').trim();
21
+ const match = value.match(/(?::([1-9]\d*)(?::([1-9]\d*))?|#L([1-9]\d*)(?:-L?([1-9]\d*))?)$/);
22
+ if (!match) return { path: value, line: null, endLine: null };
23
+ const line = Number(match[1] || match[3]);
24
+ return { path: value.slice(0, match.index), line, endLine: Math.max(line, Number(match[4]) || line) };
25
+ }
26
+
27
+ export function mediaType(target) {
28
+ return MEDIA[path.extname(target).toLowerCase()] || null;
29
+ }
30
+
31
+ export function filePreview(target, stat, reference) {
32
+ const base = { name: path.basename(target), size: stat.size, line: reference.line, endLine: reference.endLine };
33
+ const unavailable = (reason) => ({ ...base, kind: 'unsupported', reason });
34
+ if (!stat.isFile()) return unavailable('Directories cannot be previewed. Open this location in an app.');
35
+ const media = mediaType(target);
36
+ if (media) return { ...base, kind: media[0], mime: media[1] };
37
+ if (stat.size > TEXT_LIMIT) return unavailable('Text previews are limited to 1 MiB. Open this file in an app.');
38
+ // Read at most the limit + 1 even if a file grows between stat and read.
39
+ const fd = fs.openSync(target, 'r');
40
+ let bytes;
41
+ try {
42
+ const buffer = Buffer.alloc(TEXT_LIMIT + 1);
43
+ bytes = buffer.subarray(0, fs.readSync(fd, buffer, 0, buffer.length, 0));
44
+ } finally { fs.closeSync(fd); }
45
+ if (bytes.length > TEXT_LIMIT) return unavailable('Text previews are limited to 1 MiB. Open this file in an app.');
46
+ let text;
47
+ try { text = new TextDecoder('utf-8', { fatal: true }).decode(bytes); }
48
+ catch { return unavailable('This file is binary or uses an unsupported text encoding. Open it in an app.'); }
49
+ if (/[\x00-\x08\x0e-\x1f]/.test(text)) return unavailable('This binary file cannot be previewed. Open it in an app.');
50
+ if (text.split('\n').length > 20000) return unavailable('This file has too many lines to preview. Open it in an app.');
51
+ const ext = path.extname(target).slice(1).toLowerCase();
52
+ const lang = ({ js: 'javascript', mjs: 'javascript', cjs: 'javascript', ts: 'typescript', py: 'python', sh: 'bash' })[ext] || ext;
53
+ let kind = /^(md|markdown|mdown)$/.test(ext) ? 'markdown' : /^(html|htm)$/.test(ext) ? 'html' : 'code';
54
+ if (!reference.line && /^(csv|tsv)$/.test(ext)) {
55
+ try {
56
+ const block = normalizeSpec({ blocks: [{ type: 'table', rowsFile: target, sortable: true, filterable: true }] }).blocks[0];
57
+ return { ...base, kind: 'table', block, text, lang };
58
+ } catch { /* malformed tables remain readable as source */ }
59
+ }
60
+ return { ...base, kind, text, lang };
61
+ }
package/src/server.js CHANGED
@@ -17,6 +17,7 @@ import {
17
17
  } from './store.js';
18
18
  import { openUrl } from './open.js';
19
19
  import { assertSpecReady } from './spec.js';
20
+ import { splitFileReference, filePreview, mediaType } from './file-preview.js';
20
21
 
21
22
  const UI_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), 'ui');
22
23
  const PKG_ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
@@ -492,7 +493,7 @@ function looksLikeLocalPath(s) {
492
493
  // Expands ~ / file:// and resolves a (possibly relative) path to an absolute,
493
494
  // normalized one against the board's authoring cwd. null on a malformed URL.
494
495
  function resolveLocalPath(raw, baseCwd) {
495
- let p = String(raw || '').trim();
496
+ let p = splitFileReference(raw).path;
496
497
  if (!p) return null;
497
498
  if (/^file:\/\//i.test(p)) {
498
499
  try {
@@ -547,6 +548,7 @@ function buildOpenAllowlist(spec, baseCwd) {
547
548
  // Same-origin fetches send no Origin or our own; a foreign Origin is a
548
549
  // cross-site POST and must not be allowed to open a local file.
549
550
  function sameOrigin(req, port, extraHosts = []) {
551
+ if (req.headers['sec-fetch-site'] === 'cross-site') return false;
550
552
  const origin = req.headers.origin;
551
553
  if (!origin) return true;
552
554
  try {
@@ -1070,13 +1072,14 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
1070
1072
  savePref({ fontScale: body.fontScale });
1071
1073
  }
1072
1074
  sendJson(res, 200, { ok: true });
1073
- } else if (req.method === 'POST' && pathname === '/api/open') {
1074
- // Open a board-referenced local file in the OS default app. Guarded by
1075
- // a same-origin check + an allowlist of paths the board actually links.
1075
+ } else if ((req.method === 'POST' && ['/api/open', '/api/file-preview'].includes(pathname)) ||
1076
+ (['GET', 'HEAD'].includes(req.method) && pathname === '/api/file-content')) {
1077
+ // Preview, stream, or open only a board-referenced local file. All three
1078
+ // paths share the same origin, role, and reference allowlist checks.
1076
1079
  if (!sameOrigin(req, actualPort, [advertisedHost])) return sendJson(res, 403, { error: 'cross-origin requests cannot open files' });
1077
1080
  const access = accessFor(req, reqUrl);
1078
1081
  if (access.role !== 'owner' && access.role !== 'collab') return sendJson(res, 403, { error: 'this share cannot open local files' });
1079
- const body = JSON.parse((await readBody(req)) || '{}');
1082
+ const body = req.method === 'POST' ? JSON.parse((await readBody(req)) || '{}') : { path: reqUrl.searchParams.get('path') };
1080
1083
  const raw = typeof body.path === 'string' ? body.path : '';
1081
1084
  if (!raw.trim()) return sendJson(res, 400, { error: 'missing "path"' });
1082
1085
  const baseCwd = record.cwd || process.cwd();
@@ -1092,6 +1095,16 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
1092
1095
  stat = null;
1093
1096
  }
1094
1097
  if (!stat) return sendJson(res, 404, { error: 'file not found', path: target });
1098
+ if (pathname === '/api/file-preview') {
1099
+ return sendJson(res, 200, { ok: true, ...filePreview(target, stat, splitFileReference(raw)) });
1100
+ }
1101
+ if (pathname === '/api/file-content') {
1102
+ const media = mediaType(target);
1103
+ if (!stat.isFile() || !media) return sendJson(res, 415, { error: 'this file type cannot be streamed' });
1104
+ res.setHeader('X-Content-Type-Options', 'nosniff');
1105
+ res.setHeader('Content-Security-Policy', "sandbox; default-src 'none'");
1106
+ return streamFile(req, res, target, media[1]);
1107
+ }
1095
1108
  if (!openUrl(target)) return sendJson(res, 500, { error: 'could not open the file' });
1096
1109
  sendJson(res, 200, { ok: true, path: target, name: path.basename(target) });
1097
1110
  } else if (req.method === 'POST' && pathname === '/api/draft') {
package/src/ui/blocks.css CHANGED
@@ -4,6 +4,54 @@
4
4
  .blk { margin: 14px 0 0; }
5
5
  .blk:first-child { margin-top: 0; }
6
6
 
7
+ /* File previews keep the board's scroll position and use native modal focus. */
8
+ .rly-file-dialog {
9
+ width: min(1180px, calc(100vw - 32px));
10
+ height: min(900px, calc(100dvh - 32px));
11
+ max-width: none;
12
+ max-height: none;
13
+ padding: 0;
14
+ border: 1px solid var(--border);
15
+ border-radius: 14px;
16
+ background: var(--bg);
17
+ color: var(--fg);
18
+ overflow: hidden;
19
+ }
20
+ .rly-file-dialog[open] { display: flex; flex-direction: column; }
21
+ .rly-file-dialog::backdrop { background: rgb(0 0 0 / 55%); }
22
+ .rly-file-header { display: flex; align-items: center; gap: 16px; padding: 16px 20px; border-bottom: 1px solid var(--border); }
23
+ .rly-file-heading { flex: 1; min-width: 0; }
24
+ .rly-file-heading h2 { margin: 0 0 5px; font: 600 1rem var(--sans); overflow-wrap: anywhere; }
25
+ .rly-file-location { font-size: 0.8rem; color: var(--muted); overflow-wrap: anywhere; }
26
+ .rly-file-actions { display: flex; gap: 8px; flex-wrap: wrap; }
27
+ .rly-file-actions .btn {
28
+ white-space: nowrap; padding: 8px 12px; min-height: 36px;
29
+ font: 500 0.85rem var(--sans); color: var(--fg);
30
+ background: var(--bg-sunken); border: 1px solid var(--border); border-radius: 7px; cursor: pointer;
31
+ }
32
+ .rly-file-actions .btn:hover { background: var(--accent-soft); border-color: var(--accent); }
33
+ .rly-file-actions .btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
34
+ .rly-file-actions .btn:disabled { opacity: 0.5; cursor: default; }
35
+ .rly-file-body { flex: 1; min-height: 0; overflow: auto; padding: 20px; }
36
+ .rly-file-body > .blk-markdown { max-width: 75ch; margin: 0 auto; }
37
+ .rly-file-body .blk-tools { display: none; }
38
+ .rly-file-source { font: 0.85rem/1.6 var(--mono, monospace); width: max-content; min-width: 100%; }
39
+ .rly-file-line { display: flex; white-space: pre; min-height: 1.6em; }
40
+ .rly-file-line-number { flex: 0 0 5ch; padding-right: 2ch; text-align: right; color: var(--muted); user-select: none; }
41
+ .rly-file-line.is-target { background: var(--accent-soft, var(--bg-sunken)); outline: 1px solid var(--accent); outline-offset: -1px; }
42
+ .rly-file-media { display: block; max-width: 100%; margin: 0 auto; }
43
+ .rly-file-image { object-fit: contain; max-height: 100%; }
44
+ .rly-file-frame, .rly-file-pdf { width: 100%; height: 100%; min-height: 300px; border: 0; background: white; }
45
+ .rly-file-video { max-height: 100%; }
46
+ .rly-file-audio { width: min(100%, 600px); }
47
+ @media (max-width: 600px) {
48
+ .rly-file-dialog { width: calc(100vw - 12px); height: calc(100dvh - 12px); border-radius: 10px; }
49
+ .rly-file-header { padding: 12px; flex-wrap: wrap; gap: 12px; }
50
+ .rly-file-heading { flex-basis: 100%; }
51
+ .rly-file-body { padding: 12px; }
52
+ .rly-file-actions .btn { min-height: 44px; }
53
+ }
54
+
7
55
  /* ---------- shared error card ---------- */
8
56
  .blk-error {
9
57
  color: var(--muted);
@@ -140,15 +188,19 @@
140
188
  }
141
189
  /* subtle tinter colors via theme vars only */
142
190
  .blk-pre .tok-kw,
191
+ .rly-file-source .tok-kw,
143
192
  .blk-difftable .tok-kw,
144
193
  .blk-markdown .md .tok-kw { color: var(--accent); }
145
194
  .blk-pre .tok-str,
195
+ .rly-file-source .tok-str,
146
196
  .blk-difftable .tok-str,
147
197
  .blk-markdown .md .tok-str { color: var(--ok); }
148
198
  .blk-pre .tok-com,
199
+ .rly-file-source .tok-com,
149
200
  .blk-difftable .tok-com,
150
201
  .blk-markdown .md .tok-com { color: var(--muted); font-style: italic; }
151
202
  .blk-pre .tok-num,
203
+ .rly-file-source .tok-num,
152
204
  .blk-difftable .tok-num,
153
205
  .blk-markdown .md .tok-num { color: var(--fg-2); }
154
206
 
@@ -794,18 +846,23 @@ body.blk-space-pan .blk-has-regions.blk-pannable * { cursor: grab !important; }
794
846
  background: var(--accent); border-color: var(--accent); color: var(--accent-fg);
795
847
  }
796
848
  .blk-tools .tool-comment.has-comment:hover { background: var(--accent-hover); border-color: var(--accent-hover); color: var(--accent-fg); }
797
- .blk-tools .tool-region {
849
+ .blk-tools .tool-region,
850
+ .blk-tools .tool-hover-comments {
798
851
  display: inline-flex; align-items: center; gap: 5px;
799
852
  }
800
- .blk-tools .tool-region svg { display: block; }
801
- .blk-tools .tool-region.is-active {
853
+ .blk-tools .tool-region svg,
854
+ .blk-tools .tool-hover-comments svg { display: block; }
855
+ .blk-tools .tool-region.is-active,
856
+ .blk-tools .tool-hover-comments.is-active {
802
857
  background: var(--accent); border-color: var(--accent); color: var(--accent-fg);
803
858
  }
804
- .blk-tools .tool-region.is-active:hover {
859
+ .blk-tools .tool-region.is-active:hover,
860
+ .blk-tools .tool-hover-comments.is-active:hover {
805
861
  background: var(--accent-hover); border-color: var(--accent-hover); color: var(--accent-fg);
806
862
  }
807
863
  @media (max-width: 520px) {
808
- .blk-tools .tool-region-label { display: none; }
864
+ .blk-tools .tool-region-label,
865
+ .blk-tools .tool-hover-label { display: none; }
809
866
  }
810
867
 
811
868
  /* code blocks reuse the viewer toolbar (comment + full-screen); the pre keeps
package/src/ui/blocks.js CHANGED
@@ -42,8 +42,8 @@
42
42
  // ---------- local file paths → click-to-open links ----------
43
43
  // Agents routinely write a path (~/clip.mp4, ./src/app.js, /abs/file) and the
44
44
  // user expects to click it open, not copy it into a terminal. We turn such
45
- // paths into links that POST to /api/open, where the server opens them in the
46
- // OS default app. FILE_PATH_RE / looksLikeLocalPath MUST match the same logic
45
+ // paths into links that preview files in a dialog, with an explicit app-open
46
+ // fallback. FILE_PATH_RE / looksLikeLocalPath MUST match the same logic
47
47
  // in server.js so the page only links what the server will agree to open.
48
48
  // The body class also excludes \0 (the placeholder delimiter mdInline uses
49
49
  // below) so a path butted against a stashed span can't swallow it; \0 never
@@ -73,7 +73,7 @@
73
73
  const cls = 'rly-filelink' + (codeStyle ? ' rly-filelink-code' : '');
74
74
  return (
75
75
  `<a class="${cls}" role="link" tabindex="0" data-rly-open="${raw}" ` +
76
- `title="Open ${raw} in the default app">` +
76
+ `title="Preview ${raw}" aria-haspopup="dialog">` +
77
77
  `<span class="rly-filelink-ico" aria-hidden="true"></span>` +
78
78
  `<span class="rly-filelink-txt">${label}</span></a>`
79
79
  );
@@ -2483,6 +2483,9 @@
2483
2483
  '<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
2484
2484
  '<rect x="3" y="4" width="14" height="12" rx="2" stroke-dasharray="3 2"/>' +
2485
2485
  '<path d="M14 14.5h6.5v4H18l-2.5 2v-2H14z" fill="currentColor" stroke="none"/></svg>';
2486
+ const ICON_EYE =
2487
+ '<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
2488
+ '<path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"/><circle cx="12" cy="12" r="3"/></svg>';
2486
2489
 
2487
2490
  function exitFull() {
2488
2491
  if (!fullOpen) return;
@@ -2497,7 +2500,7 @@
2497
2500
  if (c._rlyZoom) c._rlyZoom.reapply(); // restore the compact inline height cap
2498
2501
  }
2499
2502
  document.addEventListener('keydown', (e) => {
2500
- if (e.key === 'Escape' && fullOpen) exitFull();
2503
+ if (e.key === 'Escape' && fullOpen && !document.querySelector('.rly-file-dialog[open]')) exitFull();
2501
2504
  });
2502
2505
 
2503
2506
  // Enter full-screen for a viewer container (shared by the toolbar button and
@@ -2784,6 +2787,30 @@
2784
2787
  }
2785
2788
  }
2786
2789
 
2790
+ if (opts && opts.comment && opts.hoverComments) {
2791
+ const hoverCtl = opts.hoverComments;
2792
+ const hoverBtn = el('button', {
2793
+ class: 'tool-hover-comments',
2794
+ type: 'button',
2795
+ 'aria-label': 'Show element comment overlays',
2796
+ });
2797
+ hoverBtn.innerHTML = ICON_EYE;
2798
+ hoverBtn.append(el('span', { class: 'tool-hover-label' }, 'Hover comments'));
2799
+ const syncHoverMode = () => {
2800
+ const enabled = hoverCtl.isEnabled();
2801
+ hoverBtn.classList.toggle('is-active', enabled);
2802
+ hoverBtn.setAttribute('aria-pressed', String(enabled));
2803
+ hoverBtn.title = enabled ? 'Hide element comment overlays' : 'Show element comment overlays';
2804
+ };
2805
+ hoverBtn.addEventListener('click', (e) => {
2806
+ e.stopPropagation();
2807
+ hoverCtl.setEnabled(!hoverCtl.isEnabled());
2808
+ syncHoverMode();
2809
+ });
2810
+ syncHoverMode();
2811
+ tools.append(hoverBtn);
2812
+ }
2813
+
2787
2814
  if (opts && opts.region) {
2788
2815
  const regionCtl = opts.region;
2789
2816
  const regionLabel = el('span', { class: 'tool-region-label' }, 'Area');
@@ -2894,19 +2921,47 @@
2894
2921
  }
2895
2922
 
2896
2923
  // ---------- html (sandboxed iframe) ----------
2924
+ function syncHtmlHoverComments(frame) {
2925
+ try {
2926
+ frame.contentWindow.postMessage({ relay: 'annotate-hover', enabled: frame.dataset.relayHoverComments !== 'off' }, '*');
2927
+ } catch (_) {}
2928
+ }
2929
+
2930
+ // The kit can load after the iframe's load event; its ready message also
2931
+ // restores the current toggle when the embedded page reloads.
2932
+ window.addEventListener('message', (e) => {
2933
+ if (!e.data || e.data.relay !== 'annotate-ready') return;
2934
+ for (const frame of document.querySelectorAll('iframe.viz[data-relay-hover-comments]')) {
2935
+ if (frame.contentWindow === e.source) { syncHtmlHoverComments(frame); break; }
2936
+ }
2937
+ });
2938
+
2897
2939
  function renderHtml(block, ctx, blockId) {
2898
2940
  const height = clampHeight(block.height, 360);
2899
2941
  const iframe = el('iframe', {
2900
2942
  class: 'viz',
2901
2943
  'data-block-id': blockId,
2902
2944
  'data-question-id': ctx.questionId || '',
2945
+ 'data-relay-hover-comments': 'on',
2903
2946
  src: ctx.htmlSrc(blockId),
2904
2947
  height: String(height),
2905
2948
  sandbox: 'allow-scripts allow-forms allow-popups allow-modals',
2906
2949
  loading: 'lazy',
2907
2950
  });
2951
+ iframe.addEventListener('load', () => syncHtmlHoverComments(iframe));
2908
2952
  const wrap = el('div', { class: 'blk-htmlwrap' }, iframe);
2909
- attachViewer(wrap, { zoomEl: null, label: 'embed', comment: wholeBlockComment(ctx, blockId, 'embed') });
2953
+ attachViewer(wrap, {
2954
+ zoomEl: null,
2955
+ label: 'embed',
2956
+ comment: wholeBlockComment(ctx, blockId, 'embed'),
2957
+ hoverComments: {
2958
+ isEnabled: () => iframe.dataset.relayHoverComments !== 'off',
2959
+ setEnabled: (enabled) => {
2960
+ iframe.dataset.relayHoverComments = enabled ? 'on' : 'off';
2961
+ syncHtmlHoverComments(iframe);
2962
+ },
2963
+ },
2964
+ });
2910
2965
  return wrap;
2911
2966
  }
2912
2967
 
@@ -3018,6 +3073,125 @@
3018
3073
  }
3019
3074
 
3020
3075
  // ---------- file-link open behavior ----------
3076
+ let fileDialog = null;
3077
+ const fileAuthHeaders = () => {
3078
+ const token = new URLSearchParams(location.search).get('token');
3079
+ return token ? { 'x-relay-share-token': token } : {};
3080
+ };
3081
+
3082
+ async function previewFilePath(a) {
3083
+ const p = a.dataset.rlyOpen;
3084
+ if (!p) return;
3085
+ if (fileDialog) fileDialog.close();
3086
+ const dialog = el('dialog', { class: 'rly-file-dialog', 'aria-label': 'File preview' });
3087
+ const title = el('h2', {}, p.split(/[\\/]/).pop());
3088
+ const pathLabel = el('div', { class: 'rly-file-location', title: p }, p);
3089
+ const close = el('button', { type: 'button', class: 'btn', autofocus: '', 'aria-label': 'Close file preview' }, 'Close');
3090
+ const open = el('button', { type: 'button', class: 'btn' }, 'Open in app');
3091
+ open.dataset.rlyOpen = p;
3092
+ open.addEventListener('click', () => openFilePath(open));
3093
+ const actions = el('div', { class: 'rly-file-actions' }, open, close);
3094
+ const body = el('div', { class: 'rly-file-body', tabindex: '0', 'aria-busy': 'true' });
3095
+ const status = el('p', { role: 'status' }, 'Loading preview…');
3096
+ body.append(status);
3097
+ dialog.append(el('header', { class: 'rly-file-header' }, el('div', { class: 'rly-file-heading' }, title, pathLabel), actions), body);
3098
+ const controller = new AbortController();
3099
+ const previousFocus = document.activeElement;
3100
+ close.addEventListener('click', () => dialog.close());
3101
+ dialog.addEventListener('close', () => {
3102
+ controller.abort();
3103
+ dialog.querySelectorAll('video,audio').forEach((media) => { media.pause(); media.removeAttribute('src'); media.load(); });
3104
+ dialog.remove();
3105
+ if (fileDialog === dialog) fileDialog = null;
3106
+ if (previousFocus && previousFocus.isConnected) previousFocus.focus({ preventScroll: true });
3107
+ });
3108
+ document.body.append(dialog);
3109
+ fileDialog = dialog;
3110
+ dialog.showModal();
3111
+ try {
3112
+ const response = await fetch('/api/file-preview', {
3113
+ method: 'POST', headers: { 'content-type': 'application/json', ...fileAuthHeaders() },
3114
+ body: JSON.stringify({ path: p }), signal: controller.signal,
3115
+ });
3116
+ let data;
3117
+ try { data = await response.json(); }
3118
+ catch { throw new Error('File previews need a current Relay browser board. Reconnect this board with the updated CLI.'); }
3119
+ if (!response.ok || !data.ok) {
3120
+ if (response.status === 403) open.disabled = true;
3121
+ throw new Error(data.error || 'Preview unavailable. Reconnect this board with the updated CLI.');
3122
+ }
3123
+ if (!dialog.open) return;
3124
+ title.textContent = data.name;
3125
+ dialog.setAttribute('aria-label', 'File preview: ' + data.name);
3126
+ body.replaceChildren();
3127
+ const source = () => {
3128
+ body.replaceChildren();
3129
+ const lines = String(data.text || '').replace(/\r\n?/g, '\n').replace(/\n$/, '').split('\n');
3130
+ const list = el('div', { class: 'rly-file-source' });
3131
+ lines.forEach((line, i) => {
3132
+ const number = i + 1;
3133
+ const code = el('code');
3134
+ code.innerHTML = tintCode(line, data.lang) || ' ';
3135
+ const row = el('div', { class: 'rly-file-line', 'data-line': String(number) },
3136
+ el('span', { class: 'rly-file-line-number', 'aria-hidden': 'true' }, String(number)), code);
3137
+ if (data.line && number >= data.line && number <= data.endLine) row.classList.add('is-target');
3138
+ list.append(row);
3139
+ });
3140
+ if (data.line > lines.length) body.append(el('p', { role: 'status' }, 'Line ' + data.line + ' is beyond this file’s ' + lines.length + ' lines.'));
3141
+ body.append(list);
3142
+ requestAnimationFrame(() => {
3143
+ const target = list.querySelector('.is-target');
3144
+ if (!target || !dialog.open) return;
3145
+ body.scrollTop += target.getBoundingClientRect().top - body.getBoundingClientRect().top - body.clientHeight / 2 + target.clientHeight / 2;
3146
+ body.scrollLeft = 0;
3147
+ });
3148
+ };
3149
+ const rendered = () => {
3150
+ body.replaceChildren();
3151
+ if (data.kind === 'markdown') {
3152
+ const md = el('div', { class: 'blk-markdown' });
3153
+ md.append(renderMarkdown(data.text));
3154
+ body.append(md);
3155
+ } else if (data.kind === 'table') {
3156
+ body.append(renderTable(data.block, { canComment: false }, 'file-preview'));
3157
+ } else if (data.kind === 'html') {
3158
+ // Empty sandbox prevents scripts, forms and same-origin access. CSP
3159
+ // also prevents authored markup from fetching local or remote URLs.
3160
+ const frame = el('iframe', { class: 'rly-file-frame', title: data.name, sandbox: '', referrerpolicy: 'no-referrer' });
3161
+ frame.srcdoc = '<meta http-equiv="Content-Security-Policy" content="default-src &#39;none&#39;; style-src &#39;unsafe-inline&#39;; img-src data:; font-src data:">' + data.text;
3162
+ body.append(frame);
3163
+ }
3164
+ };
3165
+ if (['markdown', 'html', 'table'].includes(data.kind)) {
3166
+ let viewingSource = !!data.line;
3167
+ const toggle = el('button', { type: 'button', class: 'btn' }, viewingSource ? 'Preview' : 'Source');
3168
+ toggle.addEventListener('click', () => {
3169
+ viewingSource = !viewingSource;
3170
+ toggle.textContent = viewingSource ? 'Preview' : 'Source';
3171
+ viewingSource ? source() : rendered();
3172
+ });
3173
+ actions.prepend(toggle);
3174
+ viewingSource ? source() : rendered();
3175
+ } else if (data.kind === 'code') source();
3176
+ else if (data.kind === 'unsupported') body.append(el('p', { role: 'status' }, data.reason));
3177
+ else {
3178
+ const params = new URLSearchParams({ path: p });
3179
+ const token = new URLSearchParams(location.search).get('token');
3180
+ if (token) params.set('token', token);
3181
+ const url = '/api/file-content?' + params;
3182
+ const tag = { image: 'img', pdf: 'iframe', video: 'video', audio: 'audio' }[data.kind];
3183
+ if (!tag) throw new Error('This file type cannot be previewed.');
3184
+ const media = el(tag, { class: 'rly-file-media rly-file-' + data.kind, src: url, title: data.name });
3185
+ if (tag === 'img') media.alt = data.name;
3186
+ if (tag === 'video' || tag === 'audio') { media.controls = true; media.preload = 'metadata'; }
3187
+ media.addEventListener('error', () => body.append(el('p', { role: 'status' }, 'Your browser could not display this file. Use Open in app.')), { once: true });
3188
+ body.append(media);
3189
+ }
3190
+ } catch (err) {
3191
+ if (err.name !== 'AbortError' && dialog.open) body.replaceChildren(el('p', { role: 'alert' }, err.message || 'Could not reach the board server.'));
3192
+ } finally { body.setAttribute('aria-busy', 'false'); }
3193
+ }
3194
+
3021
3195
  // A small toast pinned top-center (reuses the .toast style from style.css).
3022
3196
  // tone 'err' adds .toast-err so failures read as a problem, not a success.
3023
3197
  function fileToast(message, tone) {
@@ -3035,7 +3209,7 @@
3035
3209
  try {
3036
3210
  const r = await fetch('/api/open', {
3037
3211
  method: 'POST',
3038
- headers: { 'content-type': 'application/json' },
3212
+ headers: { 'content-type': 'application/json', ...fileAuthHeaders() },
3039
3213
  body: JSON.stringify({ path: p }),
3040
3214
  });
3041
3215
  let data = {};
@@ -3065,14 +3239,14 @@
3065
3239
  const a = hit(e);
3066
3240
  if (!a) return;
3067
3241
  e.preventDefault();
3068
- openFilePath(a);
3242
+ previewFilePath(a);
3069
3243
  });
3070
3244
  document.addEventListener('keydown', (e) => {
3071
3245
  if (e.key !== 'Enter' && e.key !== ' ' && e.key !== 'Spacebar') return;
3072
3246
  const a = hit(e);
3073
3247
  if (!a) return;
3074
3248
  e.preventDefault();
3075
- openFilePath(a);
3249
+ previewFilePath(a);
3076
3250
  });
3077
3251
  }
3078
3252
  initFileLinks();