@khanglvm/relay 0.16.1 → 0.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -0
- package/docs/AGENT.md +32 -30
- package/package.json +1 -1
- package/skills/relay/SKILL.md +125 -596
- package/src/cli.js +20 -66
- package/src/file-preview.js +61 -0
- package/src/server.js +18 -5
- package/src/ui/blocks.css +52 -0
- package/src/ui/blocks.js +126 -7
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 —
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
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 =
|
|
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' &&
|
|
1074
|
-
|
|
1075
|
-
//
|
|
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
|
|
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
|
|
46
|
-
//
|
|
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="
|
|
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
|
);
|
|
@@ -2497,7 +2497,7 @@
|
|
|
2497
2497
|
if (c._rlyZoom) c._rlyZoom.reapply(); // restore the compact inline height cap
|
|
2498
2498
|
}
|
|
2499
2499
|
document.addEventListener('keydown', (e) => {
|
|
2500
|
-
if (e.key === 'Escape' && fullOpen) exitFull();
|
|
2500
|
+
if (e.key === 'Escape' && fullOpen && !document.querySelector('.rly-file-dialog[open]')) exitFull();
|
|
2501
2501
|
});
|
|
2502
2502
|
|
|
2503
2503
|
// Enter full-screen for a viewer container (shared by the toolbar button and
|
|
@@ -3018,6 +3018,125 @@
|
|
|
3018
3018
|
}
|
|
3019
3019
|
|
|
3020
3020
|
// ---------- file-link open behavior ----------
|
|
3021
|
+
let fileDialog = null;
|
|
3022
|
+
const fileAuthHeaders = () => {
|
|
3023
|
+
const token = new URLSearchParams(location.search).get('token');
|
|
3024
|
+
return token ? { 'x-relay-share-token': token } : {};
|
|
3025
|
+
};
|
|
3026
|
+
|
|
3027
|
+
async function previewFilePath(a) {
|
|
3028
|
+
const p = a.dataset.rlyOpen;
|
|
3029
|
+
if (!p) return;
|
|
3030
|
+
if (fileDialog) fileDialog.close();
|
|
3031
|
+
const dialog = el('dialog', { class: 'rly-file-dialog', 'aria-label': 'File preview' });
|
|
3032
|
+
const title = el('h2', {}, p.split(/[\\/]/).pop());
|
|
3033
|
+
const pathLabel = el('div', { class: 'rly-file-location', title: p }, p);
|
|
3034
|
+
const close = el('button', { type: 'button', class: 'btn', autofocus: '', 'aria-label': 'Close file preview' }, 'Close');
|
|
3035
|
+
const open = el('button', { type: 'button', class: 'btn' }, 'Open in app');
|
|
3036
|
+
open.dataset.rlyOpen = p;
|
|
3037
|
+
open.addEventListener('click', () => openFilePath(open));
|
|
3038
|
+
const actions = el('div', { class: 'rly-file-actions' }, open, close);
|
|
3039
|
+
const body = el('div', { class: 'rly-file-body', tabindex: '0', 'aria-busy': 'true' });
|
|
3040
|
+
const status = el('p', { role: 'status' }, 'Loading preview…');
|
|
3041
|
+
body.append(status);
|
|
3042
|
+
dialog.append(el('header', { class: 'rly-file-header' }, el('div', { class: 'rly-file-heading' }, title, pathLabel), actions), body);
|
|
3043
|
+
const controller = new AbortController();
|
|
3044
|
+
const previousFocus = document.activeElement;
|
|
3045
|
+
close.addEventListener('click', () => dialog.close());
|
|
3046
|
+
dialog.addEventListener('close', () => {
|
|
3047
|
+
controller.abort();
|
|
3048
|
+
dialog.querySelectorAll('video,audio').forEach((media) => { media.pause(); media.removeAttribute('src'); media.load(); });
|
|
3049
|
+
dialog.remove();
|
|
3050
|
+
if (fileDialog === dialog) fileDialog = null;
|
|
3051
|
+
if (previousFocus && previousFocus.isConnected) previousFocus.focus({ preventScroll: true });
|
|
3052
|
+
});
|
|
3053
|
+
document.body.append(dialog);
|
|
3054
|
+
fileDialog = dialog;
|
|
3055
|
+
dialog.showModal();
|
|
3056
|
+
try {
|
|
3057
|
+
const response = await fetch('/api/file-preview', {
|
|
3058
|
+
method: 'POST', headers: { 'content-type': 'application/json', ...fileAuthHeaders() },
|
|
3059
|
+
body: JSON.stringify({ path: p }), signal: controller.signal,
|
|
3060
|
+
});
|
|
3061
|
+
let data;
|
|
3062
|
+
try { data = await response.json(); }
|
|
3063
|
+
catch { throw new Error('File previews need a current Relay browser board. Reconnect this board with the updated CLI.'); }
|
|
3064
|
+
if (!response.ok || !data.ok) {
|
|
3065
|
+
if (response.status === 403) open.disabled = true;
|
|
3066
|
+
throw new Error(data.error || 'Preview unavailable. Reconnect this board with the updated CLI.');
|
|
3067
|
+
}
|
|
3068
|
+
if (!dialog.open) return;
|
|
3069
|
+
title.textContent = data.name;
|
|
3070
|
+
dialog.setAttribute('aria-label', 'File preview: ' + data.name);
|
|
3071
|
+
body.replaceChildren();
|
|
3072
|
+
const source = () => {
|
|
3073
|
+
body.replaceChildren();
|
|
3074
|
+
const lines = String(data.text || '').replace(/\r\n?/g, '\n').replace(/\n$/, '').split('\n');
|
|
3075
|
+
const list = el('div', { class: 'rly-file-source' });
|
|
3076
|
+
lines.forEach((line, i) => {
|
|
3077
|
+
const number = i + 1;
|
|
3078
|
+
const code = el('code');
|
|
3079
|
+
code.innerHTML = tintCode(line, data.lang) || ' ';
|
|
3080
|
+
const row = el('div', { class: 'rly-file-line', 'data-line': String(number) },
|
|
3081
|
+
el('span', { class: 'rly-file-line-number', 'aria-hidden': 'true' }, String(number)), code);
|
|
3082
|
+
if (data.line && number >= data.line && number <= data.endLine) row.classList.add('is-target');
|
|
3083
|
+
list.append(row);
|
|
3084
|
+
});
|
|
3085
|
+
if (data.line > lines.length) body.append(el('p', { role: 'status' }, 'Line ' + data.line + ' is beyond this file’s ' + lines.length + ' lines.'));
|
|
3086
|
+
body.append(list);
|
|
3087
|
+
requestAnimationFrame(() => {
|
|
3088
|
+
const target = list.querySelector('.is-target');
|
|
3089
|
+
if (!target || !dialog.open) return;
|
|
3090
|
+
body.scrollTop += target.getBoundingClientRect().top - body.getBoundingClientRect().top - body.clientHeight / 2 + target.clientHeight / 2;
|
|
3091
|
+
body.scrollLeft = 0;
|
|
3092
|
+
});
|
|
3093
|
+
};
|
|
3094
|
+
const rendered = () => {
|
|
3095
|
+
body.replaceChildren();
|
|
3096
|
+
if (data.kind === 'markdown') {
|
|
3097
|
+
const md = el('div', { class: 'blk-markdown' });
|
|
3098
|
+
md.append(renderMarkdown(data.text));
|
|
3099
|
+
body.append(md);
|
|
3100
|
+
} else if (data.kind === 'table') {
|
|
3101
|
+
body.append(renderTable(data.block, { canComment: false }, 'file-preview'));
|
|
3102
|
+
} else if (data.kind === 'html') {
|
|
3103
|
+
// Empty sandbox prevents scripts, forms and same-origin access. CSP
|
|
3104
|
+
// also prevents authored markup from fetching local or remote URLs.
|
|
3105
|
+
const frame = el('iframe', { class: 'rly-file-frame', title: data.name, sandbox: '', referrerpolicy: 'no-referrer' });
|
|
3106
|
+
frame.srcdoc = '<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src data:">' + data.text;
|
|
3107
|
+
body.append(frame);
|
|
3108
|
+
}
|
|
3109
|
+
};
|
|
3110
|
+
if (['markdown', 'html', 'table'].includes(data.kind)) {
|
|
3111
|
+
let viewingSource = !!data.line;
|
|
3112
|
+
const toggle = el('button', { type: 'button', class: 'btn' }, viewingSource ? 'Preview' : 'Source');
|
|
3113
|
+
toggle.addEventListener('click', () => {
|
|
3114
|
+
viewingSource = !viewingSource;
|
|
3115
|
+
toggle.textContent = viewingSource ? 'Preview' : 'Source';
|
|
3116
|
+
viewingSource ? source() : rendered();
|
|
3117
|
+
});
|
|
3118
|
+
actions.prepend(toggle);
|
|
3119
|
+
viewingSource ? source() : rendered();
|
|
3120
|
+
} else if (data.kind === 'code') source();
|
|
3121
|
+
else if (data.kind === 'unsupported') body.append(el('p', { role: 'status' }, data.reason));
|
|
3122
|
+
else {
|
|
3123
|
+
const params = new URLSearchParams({ path: p });
|
|
3124
|
+
const token = new URLSearchParams(location.search).get('token');
|
|
3125
|
+
if (token) params.set('token', token);
|
|
3126
|
+
const url = '/api/file-content?' + params;
|
|
3127
|
+
const tag = { image: 'img', pdf: 'iframe', video: 'video', audio: 'audio' }[data.kind];
|
|
3128
|
+
if (!tag) throw new Error('This file type cannot be previewed.');
|
|
3129
|
+
const media = el(tag, { class: 'rly-file-media rly-file-' + data.kind, src: url, title: data.name });
|
|
3130
|
+
if (tag === 'img') media.alt = data.name;
|
|
3131
|
+
if (tag === 'video' || tag === 'audio') { media.controls = true; media.preload = 'metadata'; }
|
|
3132
|
+
media.addEventListener('error', () => body.append(el('p', { role: 'status' }, 'Your browser could not display this file. Use Open in app.')), { once: true });
|
|
3133
|
+
body.append(media);
|
|
3134
|
+
}
|
|
3135
|
+
} catch (err) {
|
|
3136
|
+
if (err.name !== 'AbortError' && dialog.open) body.replaceChildren(el('p', { role: 'alert' }, err.message || 'Could not reach the board server.'));
|
|
3137
|
+
} finally { body.setAttribute('aria-busy', 'false'); }
|
|
3138
|
+
}
|
|
3139
|
+
|
|
3021
3140
|
// A small toast pinned top-center (reuses the .toast style from style.css).
|
|
3022
3141
|
// tone 'err' adds .toast-err so failures read as a problem, not a success.
|
|
3023
3142
|
function fileToast(message, tone) {
|
|
@@ -3035,7 +3154,7 @@
|
|
|
3035
3154
|
try {
|
|
3036
3155
|
const r = await fetch('/api/open', {
|
|
3037
3156
|
method: 'POST',
|
|
3038
|
-
headers: { 'content-type': 'application/json' },
|
|
3157
|
+
headers: { 'content-type': 'application/json', ...fileAuthHeaders() },
|
|
3039
3158
|
body: JSON.stringify({ path: p }),
|
|
3040
3159
|
});
|
|
3041
3160
|
let data = {};
|
|
@@ -3065,14 +3184,14 @@
|
|
|
3065
3184
|
const a = hit(e);
|
|
3066
3185
|
if (!a) return;
|
|
3067
3186
|
e.preventDefault();
|
|
3068
|
-
|
|
3187
|
+
previewFilePath(a);
|
|
3069
3188
|
});
|
|
3070
3189
|
document.addEventListener('keydown', (e) => {
|
|
3071
3190
|
if (e.key !== 'Enter' && e.key !== ' ' && e.key !== 'Spacebar') return;
|
|
3072
3191
|
const a = hit(e);
|
|
3073
3192
|
if (!a) return;
|
|
3074
3193
|
e.preventDefault();
|
|
3075
|
-
|
|
3194
|
+
previewFilePath(a);
|
|
3076
3195
|
});
|
|
3077
3196
|
}
|
|
3078
3197
|
initFileLinks();
|