@useavalon/caelence-agent 0.2.2-canary.6 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,267 @@
1
+ import { FolderSimpleIcon } from "@phosphor-icons/react/dist/csr/FolderSimple";
2
+ import { XIcon } from "@phosphor-icons/react/dist/csr/X";
3
+ import { type ReactElement, useEffect, useRef, useState } from "react";
4
+ import { createPortal } from "react-dom";
5
+ import { type BridgeClient, fileBytesUrl, readFilePreview } from "./api";
6
+ import { renderPreviewHtml, rewritePreviewAssets } from "./preview-render";
7
+ import { type ReplySource, replySourcesForAssistant } from "./reply-sources";
8
+ import { looksLikeWebUrl, webHref } from "./rich-text";
9
+ import type { StreamLine } from "./stream";
10
+
11
+ export function ReplySources(
12
+ props: Readonly<{
13
+ lines: StreamLine[];
14
+ assistantKey: string;
15
+ bridge: BridgeClient | null;
16
+ onOpenUrl?: (url: string) => void;
17
+ onOpenFile?: (path: string, reveal: boolean) => void;
18
+ }>,
19
+ ): ReactElement | null {
20
+ const sources = replySourcesForAssistant(props.lines, props.assistantKey);
21
+ const [active, setActive] = useState<ReplySource | null>(null);
22
+ if (sources.length === 0) return null;
23
+ return (
24
+ <>
25
+ <details className="desk-sources">
26
+ <summary>Sources</summary>
27
+ <ul>
28
+ {sources.map((source) => (
29
+ <li key={`${source.kind}:${source.path}`}>
30
+ <SourceItem
31
+ source={source}
32
+ onOpenUrl={props.onOpenUrl}
33
+ onOpenFile={props.onOpenFile}
34
+ onPreview={setActive}
35
+ />
36
+ </li>
37
+ ))}
38
+ </ul>
39
+ </details>
40
+ {active ? (
41
+ <SourcePreviewModal
42
+ source={active}
43
+ bridge={props.bridge}
44
+ onClose={() => setActive(null)}
45
+ onOpenFile={props.onOpenFile}
46
+ onOpenUrl={props.onOpenUrl}
47
+ />
48
+ ) : null}
49
+ </>
50
+ );
51
+ }
52
+
53
+ function SourceItem(
54
+ props: Readonly<{
55
+ source: ReplySource;
56
+ onOpenUrl?: (url: string) => void;
57
+ onOpenFile?: (path: string, reveal: boolean) => void;
58
+ onPreview: (source: ReplySource) => void;
59
+ }>,
60
+ ): ReactElement {
61
+ const { source } = props;
62
+ if (source.kind === "web" || looksLikeWebUrl(source.path)) {
63
+ const href = webHref(source.path);
64
+ return (
65
+ <button type="button" className="desk-sources__name" onClick={() => props.onOpenUrl?.(href)}>
66
+ {source.label}
67
+ </button>
68
+ );
69
+ }
70
+ return (
71
+ <div className="desk-sources__file">
72
+ <button type="button" className="desk-sources__name" onClick={() => props.onPreview(source)}>
73
+ {source.label}
74
+ </button>
75
+ <button
76
+ type="button"
77
+ className="desk-link desk-link--icon"
78
+ aria-label={`Show ${source.label} in folder`}
79
+ onClick={() => props.onOpenFile?.(source.path, true)}
80
+ >
81
+ <FolderSimpleIcon size={14} weight="regular" aria-hidden="true" />
82
+ </button>
83
+ </div>
84
+ );
85
+ }
86
+
87
+ function SourcePreviewModal(
88
+ props: Readonly<{
89
+ source: ReplySource;
90
+ bridge: BridgeClient | null;
91
+ onClose: () => void;
92
+ onOpenFile?: (path: string, reveal: boolean) => void;
93
+ onOpenUrl?: (url: string) => void;
94
+ }>,
95
+ ): ReactElement {
96
+ const onCloseRef = useRef(props.onClose);
97
+ onCloseRef.current = props.onClose;
98
+ const { source, onClose } = props;
99
+
100
+ useEffect(() => {
101
+ const previous = document.body.style.overflow;
102
+ document.body.style.overflow = "hidden";
103
+ const onKey = (event: KeyboardEvent) => {
104
+ if (event.key !== "Escape") return;
105
+ event.preventDefault();
106
+ onCloseRef.current();
107
+ };
108
+ document.addEventListener("keydown", onKey);
109
+ return () => {
110
+ document.body.style.overflow = previous;
111
+ document.removeEventListener("keydown", onKey);
112
+ };
113
+ }, []);
114
+
115
+ return createPortal(
116
+ <div className="desk-source-modal-root">
117
+ <button
118
+ type="button"
119
+ className="desk-source-modal__scrim"
120
+ aria-label="Close preview"
121
+ onClick={onClose}
122
+ />
123
+ <div
124
+ className="desk-source-modal"
125
+ role="dialog"
126
+ aria-modal="true"
127
+ aria-labelledby="desk-source-modal-title"
128
+ >
129
+ <header className="desk-source-modal__head">
130
+ <h2 id="desk-source-modal-title">{source.label}</h2>
131
+ <button
132
+ type="button"
133
+ className="desk-link desk-link--icon"
134
+ aria-label={`Show ${source.label} in folder`}
135
+ onClick={() => props.onOpenFile?.(source.path, true)}
136
+ >
137
+ <FolderSimpleIcon size={16} weight="regular" />
138
+ </button>
139
+ <button
140
+ type="button"
141
+ className="desk-source-modal__close"
142
+ aria-label="Close preview"
143
+ onClick={onClose}
144
+ >
145
+ <XIcon size={16} weight="regular" />
146
+ </button>
147
+ </header>
148
+ <div className="desk-source-modal__body">
149
+ <FilePreview path={source.path} bridge={props.bridge} onOpenUrl={props.onOpenUrl} />
150
+ </div>
151
+ </div>
152
+ </div>,
153
+ document.body,
154
+ );
155
+ }
156
+
157
+ function FilePreview(
158
+ props: Readonly<{
159
+ path: string;
160
+ bridge: BridgeClient | null;
161
+ onOpenUrl?: (url: string) => void;
162
+ }>,
163
+ ): ReactElement {
164
+ const [html, setHtml] = useState<string | null>(null);
165
+ const [imageSrc, setImageSrc] = useState<string | null>(null);
166
+ const [text, setText] = useState<string | null>(null);
167
+ const [error, setError] = useState<string | null>(null);
168
+ const [truncated, setTruncated] = useState(false);
169
+
170
+ useEffect(() => {
171
+ const bridge = props.bridge;
172
+ if (!bridge) {
173
+ setError("Preview needs the desktop window.");
174
+ return;
175
+ }
176
+ setHtml(null);
177
+ setImageSrc(null);
178
+ setText(null);
179
+ setError(null);
180
+ setTruncated(false);
181
+ let cancelled = false;
182
+ void (async () => {
183
+ try {
184
+ const result = await readFilePreview(bridge, props.path);
185
+ if (cancelled) return;
186
+ setTruncated(result.truncated === true);
187
+ if (result.kind === "image") {
188
+ setImageSrc(fileBytesUrl(bridge, result.path));
189
+ return;
190
+ }
191
+ const raw = result.text ?? "";
192
+ if (result.kind === "markdown" || result.kind === "html") {
193
+ const rendered = rewritePreviewAssets(
194
+ renderPreviewHtml(raw, result.kind),
195
+ result.path,
196
+ (rel) => fileBytesUrl(bridge, rel),
197
+ );
198
+ setHtml(rendered);
199
+ return;
200
+ }
201
+ setText(raw);
202
+ } catch (err) {
203
+ if (!cancelled)
204
+ setError(err instanceof Error ? err.message : "Could not preview the file.");
205
+ }
206
+ })();
207
+ return () => {
208
+ cancelled = true;
209
+ };
210
+ }, [props.bridge, props.path]);
211
+
212
+ if (error) return <p className="desk-sources__empty">{error}</p>;
213
+ if (imageSrc) {
214
+ return <img className="desk-source-modal__img" src={imageSrc} alt="" />;
215
+ }
216
+ if (html != null) {
217
+ return (
218
+ <>
219
+ {truncated ? (
220
+ <p className="desk-sources__empty">Showing the first part of the file.</p>
221
+ ) : null}
222
+ <RenderedHtml html={html} onOpenUrl={props.onOpenUrl} />
223
+ </>
224
+ );
225
+ }
226
+ if (text != null) {
227
+ return (
228
+ <>
229
+ {truncated ? (
230
+ <p className="desk-sources__empty">Showing the first part of the file.</p>
231
+ ) : null}
232
+ <pre className="cel-code desk-sources__preview">{text}</pre>
233
+ </>
234
+ );
235
+ }
236
+ return <p className="desk-sources__empty">Loading</p>;
237
+ }
238
+
239
+ function RenderedHtml(
240
+ props: Readonly<{ html: string; onOpenUrl?: (url: string) => void }>,
241
+ ): ReactElement {
242
+ const rootRef = useRef<HTMLDivElement>(null);
243
+ useEffect(() => {
244
+ const root = rootRef.current;
245
+ if (!root) return;
246
+ const onClick = (event: MouseEvent) => {
247
+ const target = event.target;
248
+ if (!(target instanceof HTMLAnchorElement)) return;
249
+ const href = target.getAttribute("href");
250
+ if (!href || href.startsWith("#")) return;
251
+ if (!looksLikeWebUrl(href) && !/^https?:\/\//i.test(href)) return;
252
+ event.preventDefault();
253
+ props.onOpenUrl?.(webHref(href));
254
+ };
255
+ root.addEventListener("click", onClick);
256
+ return () => root.removeEventListener("click", onClick);
257
+ }, [props.html, props.onOpenUrl]);
258
+ return (
259
+ <div
260
+ ref={rootRef}
261
+ className="desk-md"
262
+ // Local project files only. Scripts and handlers are stripped first.
263
+ // biome-ignore lint/security/noDangerouslySetInnerHtml: sanitized local preview
264
+ dangerouslySetInnerHTML={{ __html: props.html }}
265
+ />
266
+ );
267
+ }
@@ -0,0 +1,71 @@
1
+ import { type CSSProperties, type ReactElement, useEffect, useRef, useState } from "react";
2
+
3
+ const CYCLE_MS = 2400;
4
+ const SWAP_MS = 320;
5
+
6
+ export function ShimmerPhrase(
7
+ props: Readonly<{ phrases: readonly string[]; live: boolean; tone?: "pipe" }>,
8
+ ): ReactElement {
9
+ const phrases = props.phrases.length > 0 ? props.phrases : ["Thinking"];
10
+ const key = phrases.join("\0");
11
+ const phrasesRef = useRef(phrases);
12
+ phrasesRef.current = phrases;
13
+ const [index, setIndex] = useState(0);
14
+ const [outgoing, setOutgoing] = useState<string | null>(null);
15
+ const shown = phrases[index % phrases.length] ?? phrases[0] ?? "Thinking";
16
+
17
+ useEffect(() => {
18
+ setIndex(0);
19
+ setOutgoing(null);
20
+ }, [key]);
21
+
22
+ useEffect(() => {
23
+ if (!props.live) return;
24
+ const timer = window.setInterval(() => {
25
+ const list = phrasesRef.current;
26
+ if (list.length < 2) return;
27
+ setIndex((current) => {
28
+ setOutgoing(list[current % list.length] ?? null);
29
+ return (current + 1) % list.length;
30
+ });
31
+ }, CYCLE_MS);
32
+ return () => window.clearInterval(timer);
33
+ }, [key, props.live]);
34
+
35
+ useEffect(() => {
36
+ if (!outgoing) return;
37
+ const timer = window.setTimeout(() => setOutgoing(null), SWAP_MS);
38
+ return () => window.clearTimeout(timer);
39
+ }, [outgoing]);
40
+
41
+ const tone = props.tone === "pipe" ? " desk-shimmer--pipe" : "";
42
+
43
+ if (!props.live) {
44
+ return <span className={`desk-shimmer${tone}`}>{shown}</span>;
45
+ }
46
+
47
+ return (
48
+ <span className={`desk-shimmer${tone}`} aria-live="polite">
49
+ {outgoing ? (
50
+ <span className="desk-shimmer__line is-out" aria-hidden="true">
51
+ <ShimmerLetters text={outgoing} />
52
+ </span>
53
+ ) : null}
54
+ <span className={`desk-shimmer__line${outgoing ? " is-in" : ""}`}>
55
+ <ShimmerLetters text={shown} />
56
+ </span>
57
+ </span>
58
+ );
59
+ }
60
+
61
+ function ShimmerLetters(props: Readonly<{ text: string }>): ReactElement {
62
+ return (
63
+ <span className="desk-shimmer__letters">
64
+ {[...props.text].map((letter, index) => (
65
+ <span key={`${index}-${letter}`} style={{ "--i": index } as CSSProperties}>
66
+ {letter === " " ? "\u00a0" : letter}
67
+ </span>
68
+ ))}
69
+ </span>
70
+ );
71
+ }
@@ -9,6 +9,7 @@ export type ChatTranscriptLine =
9
9
  status: "ok" | "fail";
10
10
  preview: string;
11
11
  error?: string;
12
+ output?: string;
12
13
  };
13
14
 
14
15
  export interface DesktopState {
@@ -81,6 +82,7 @@ export type AgentEvent =
81
82
  callId: string;
82
83
  success: boolean;
83
84
  result?: unknown;
85
+ output?: string;
84
86
  error?: string;
85
87
  }
86
88
  | { kind: "approval_request"; callId: string; toolName: string; input: Record<string, unknown> }
@@ -334,6 +336,24 @@ export function openPath(
334
336
  });
335
337
  }
336
338
 
339
+ export function readFilePreview(
340
+ bridge: BridgeClient,
341
+ path: string,
342
+ ): Promise<{
343
+ path: string;
344
+ kind: "markdown" | "html" | "image" | "text";
345
+ text?: string;
346
+ mime?: string;
347
+ truncated?: boolean;
348
+ }> {
349
+ return request(bridge, `/file-preview?path=${encodeURIComponent(path)}`);
350
+ }
351
+
352
+ export function fileBytesUrl(bridge: BridgeClient, path: string): string {
353
+ const params = new URLSearchParams({ path, token: bridge.token });
354
+ return `${bridge.url}/file-bytes?${params}`;
355
+ }
356
+
337
357
  export async function openLocalFile(
338
358
  path: string,
339
359
  reveal = false,
@@ -470,7 +490,9 @@ export async function filesFromDroppedPaths(paths: string[]): Promise<File[]> {
470
490
  });
471
491
  const raw = atob(item.data);
472
492
  const bytes = Uint8Array.from(raw, (ch) => ch.codePointAt(0) ?? 0);
473
- files.push(new File([bytes], item.name, { type: item.mime }));
493
+ const file = new File([bytes], item.name, { type: item.mime });
494
+ Object.assign(file, { path: trimmed });
495
+ files.push(file);
474
496
  } catch {
475
497
  // skip unreadable paths
476
498
  }
@@ -482,6 +504,7 @@ export interface TurnAttachmentPayload {
482
504
  name: string;
483
505
  mime: string;
484
506
  data: string;
507
+ sourcePath?: string;
485
508
  }
486
509
 
487
510
  export async function startTurn(
@@ -0,0 +1,86 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import {
3
+ pipelineProgress,
4
+ prettySkillName,
5
+ type SkillToolRef,
6
+ skillIdFromTool,
7
+ } from "./pipeline.ts";
8
+
9
+ function tool(
10
+ partial: Partial<SkillToolRef> & Pick<SkillToolRef, "name" | "label" | "status">,
11
+ ): SkillToolRef {
12
+ return {
13
+ preview: "",
14
+ ...partial,
15
+ };
16
+ }
17
+
18
+ describe("pipeline progress", () => {
19
+ test("pretty-prints bundled skill ids", () => {
20
+ expect(prettySkillName("copy-harry-dry")).toBe("Harry Dry");
21
+ expect(prettySkillName("owner/repo@copy-rmbc")).toBe("RMBC");
22
+ });
23
+
24
+ test("reads the skill name from preview or label", () => {
25
+ expect(
26
+ skillIdFromTool(
27
+ tool({
28
+ key: "t1",
29
+ name: "read_skill",
30
+ label: "Reading skill",
31
+ status: "running",
32
+ preview: '{"name":"copywriting"}',
33
+ }),
34
+ ),
35
+ ).toBe("copywriting");
36
+ expect(
37
+ skillIdFromTool(
38
+ tool({
39
+ key: "t2",
40
+ name: "read_skill",
41
+ label: "Reading Copy editor",
42
+ status: "ok",
43
+ }),
44
+ ),
45
+ ).toBe("Copy editor");
46
+ });
47
+
48
+ test("builds the copywriting track as skills run", () => {
49
+ const pipe = pipelineProgress([
50
+ tool({
51
+ key: "t1",
52
+ name: "read_skill",
53
+ label: "Reading Copywriting",
54
+ status: "ok",
55
+ preview: '{"name":"copywriting"}',
56
+ }),
57
+ tool({
58
+ key: "t2",
59
+ name: "read_skill",
60
+ label: "Reading RMBC",
61
+ status: "running",
62
+ preview: '{"name":"copy-rmbc"}',
63
+ }),
64
+ ]);
65
+ expect(pipe?.family).toBe("Copywriting");
66
+ expect(pipe?.title).toBe("Running RMBC");
67
+ expect(pipe?.steps.map((step) => step.status)).toEqual(["done", "run", "wait", "wait"]);
68
+ });
69
+
70
+ test("treats a lone skill as a one-step run", () => {
71
+ const pipe = pipelineProgress([
72
+ tool({
73
+ key: "t1",
74
+ name: "read_skill",
75
+ label: "Reading skill",
76
+ status: "running",
77
+ preview: '{"name":"impeccable"}',
78
+ }),
79
+ ]);
80
+ expect(pipe).toEqual({
81
+ family: "Impeccable",
82
+ title: "Running Impeccable",
83
+ steps: [{ id: "impeccable", label: "Impeccable", status: "run" }],
84
+ });
85
+ });
86
+ });
@@ -0,0 +1,131 @@
1
+ import { inputFromPreview } from "./tool-label";
2
+
3
+ export interface SkillToolRef {
4
+ name: string;
5
+ label: string;
6
+ status: "running" | "ok" | "fail";
7
+ preview: string;
8
+ }
9
+
10
+ export type PipeStepStatus = "done" | "run" | "wait";
11
+
12
+ export interface PipeStep {
13
+ id: string;
14
+ label: string;
15
+ status: PipeStepStatus;
16
+ }
17
+
18
+ export interface PipelineProgress {
19
+ family: string;
20
+ title: string;
21
+ steps: PipeStep[];
22
+ }
23
+
24
+ const COPY_STEPS = [
25
+ { id: "copywriting", label: "Copywriting" },
26
+ { id: "copy-rmbc", label: "RMBC" },
27
+ { id: "copy-harry-dry", label: "Harry Dry" },
28
+ { id: "copy-editor", label: "Copy editor" },
29
+ ] as const;
30
+
31
+ const SKILL_LABELS: Record<string, string> = {
32
+ copywriting: "Copywriting",
33
+ "copy-rmbc": "RMBC",
34
+ "copy-harry-dry": "Harry Dry",
35
+ "copy-editor": "Copy editor",
36
+ impeccable: "Impeccable",
37
+ };
38
+
39
+ export function prettySkillName(raw: string): string {
40
+ const id = skillKey(raw);
41
+ if (SKILL_LABELS[id]) return SKILL_LABELS[id];
42
+ const spaced = id.replace(/[-_]+/g, " ").trim();
43
+ return spaced ? spaced.charAt(0).toUpperCase() + spaced.slice(1) : raw.trim();
44
+ }
45
+
46
+ export function skillKey(raw: string): string {
47
+ const trimmed = raw.trim();
48
+ const at = trimmed.lastIndexOf("@");
49
+ const afterAt = at >= 0 ? trimmed.slice(at + 1) : trimmed;
50
+ const slash = afterAt.lastIndexOf("/");
51
+ return (slash >= 0 ? afterAt.slice(slash + 1) : afterAt).toLowerCase();
52
+ }
53
+
54
+ function isReadSkill(name: string): boolean {
55
+ return name === "read_skill" || name.endsWith("__read_skill");
56
+ }
57
+
58
+ export function skillIdFromTool(tool: SkillToolRef): string | undefined {
59
+ if (isReadSkill(tool.name)) {
60
+ const parsed = inputFromPreview(tool.preview);
61
+ if (typeof parsed.name === "string" && parsed.name.trim()) return parsed.name.trim();
62
+ const fromLabel = /^Reading(?: skill)?\s+(.+)$/i.exec(tool.label)?.[1];
63
+ return fromLabel?.trim();
64
+ }
65
+ if (tool.name === "task") {
66
+ const parsed = inputFromPreview(tool.preview);
67
+ if (Array.isArray(parsed.skills)) {
68
+ const first = parsed.skills.find((item): item is string => typeof item === "string");
69
+ if (first?.trim()) return first.trim();
70
+ }
71
+ if (typeof parsed.label === "string" && parsed.label.trim()) return parsed.label.trim();
72
+ }
73
+ return undefined;
74
+ }
75
+
76
+ function isCopyFamily(id: string): boolean {
77
+ const key = skillKey(id);
78
+ return COPY_STEPS.some((step) => step.id === key);
79
+ }
80
+
81
+ function seenIds(
82
+ tools: readonly SkillToolRef[],
83
+ ): Array<{ id: string; running: boolean; ok: boolean }> {
84
+ const out: Array<{ id: string; running: boolean; ok: boolean }> = [];
85
+ for (const tool of tools) {
86
+ const id = skillIdFromTool(tool);
87
+ if (!id) continue;
88
+ out.push({ id, running: tool.status === "running", ok: tool.status === "ok" });
89
+ }
90
+ return out;
91
+ }
92
+
93
+ export function pipelineProgress(tools: readonly SkillToolRef[]): PipelineProgress | undefined {
94
+ const hits = seenIds(tools);
95
+ if (hits.length === 0) return undefined;
96
+ const copy = hits.some((hit) => isCopyFamily(hit.id));
97
+ const defs = copy
98
+ ? COPY_STEPS.map((step) => ({ id: step.id, label: step.label }))
99
+ : uniqueSkillDefs(hits.map((hit) => hit.id));
100
+ const running = [...hits].reverse().find((hit) => hit.running);
101
+ const latest = running ?? [...hits].reverse().find((hit) => hit.ok) ?? hits[0];
102
+ if (!latest) return undefined;
103
+ const currentKey = skillKey(latest.id);
104
+ const steps: PipeStep[] = defs.map((def) => {
105
+ const matched = hits.filter((hit) => skillKey(hit.id) === def.id);
106
+ if (matched.some((hit) => hit.running) || def.id === currentKey) {
107
+ return { ...def, status: latest.running || def.id === currentKey ? "run" : "done" };
108
+ }
109
+ if (matched.some((hit) => hit.ok)) return { ...def, status: "done" };
110
+ return { ...def, status: "wait" };
111
+ });
112
+ const current =
113
+ steps.find((step) => step.status === "run") ?? steps.find((step) => step.status === "done");
114
+ const family = copy ? "Copywriting" : prettySkillName(latest.id);
115
+ const title = latest.running
116
+ ? `Running ${prettySkillName(latest.id)}`
117
+ : `Running ${current?.label ?? family}`;
118
+ return { family, title, steps };
119
+ }
120
+
121
+ function uniqueSkillDefs(ids: string[]): Array<{ id: string; label: string }> {
122
+ const seen = new Set<string>();
123
+ const out: Array<{ id: string; label: string }> = [];
124
+ for (const id of ids) {
125
+ const key = skillKey(id);
126
+ if (seen.has(key)) continue;
127
+ seen.add(key);
128
+ out.push({ id: key, label: prettySkillName(id) });
129
+ }
130
+ return out;
131
+ }
@@ -0,0 +1,79 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import {
3
+ renderMarkdown,
4
+ renderPreviewHtml,
5
+ resolvePreviewAsset,
6
+ rewritePreviewAssets,
7
+ sanitizePreviewHtml,
8
+ } from "./preview-render.ts";
9
+
10
+ describe("preview render", () => {
11
+ test("renders markdown headings, lists, code, and tables", () => {
12
+ const html = renderMarkdown(
13
+ [
14
+ "# Title",
15
+ "",
16
+ "A **bold** and `code` line with [docs](https://example.com).",
17
+ "",
18
+ "- one",
19
+ "- two",
20
+ "",
21
+ "```ts",
22
+ "const n = 1;",
23
+ "```",
24
+ "",
25
+ "| Path | What |",
26
+ "| --- | --- |",
27
+ "| src/ | Runtime |",
28
+ ].join("\n"),
29
+ );
30
+ expect(html).toContain("<h1>Title</h1>");
31
+ expect(html).toContain("<strong>bold</strong>");
32
+ expect(html).toContain("<code>code</code>");
33
+ expect(html).toContain('<a href="https://example.com">docs</a>');
34
+ expect(html).toContain("<ul><li>one</li><li>two</li></ul>");
35
+ expect(html).toContain("<pre><code>const n = 1;</code></pre>");
36
+ expect(html).toContain("<th>Path</th>");
37
+ expect(html).toContain("<td>Runtime</td>");
38
+ });
39
+
40
+ test("keeps raw HTML blocks and images", () => {
41
+ const html = renderMarkdown(
42
+ [
43
+ '<p align="center">',
44
+ '\t<img src="brand/logo/mark.svg" alt="Mark" />',
45
+ "</p>",
46
+ "",
47
+ "See ![shot](docs/shot.png) next.",
48
+ ].join("\n"),
49
+ );
50
+ expect(html).toContain('<p align="center">');
51
+ expect(html).toContain('src="brand/logo/mark.svg"');
52
+ expect(html).toContain('<img src="docs/shot.png" alt="shot" />');
53
+ });
54
+
55
+ test("resolves and rewrites local assets", () => {
56
+ expect(resolvePreviewAsset("README.md", "brand/logo/mark.svg")).toBe("brand/logo/mark.svg");
57
+ expect(resolvePreviewAsset("docs/guide.md", "./shot.png")).toBe("docs/shot.png");
58
+ expect(resolvePreviewAsset("docs/guide.md", "../shot.png")).toBe("shot.png");
59
+ expect(resolvePreviewAsset("docs/guide.md", "../../secret.png")).toBeUndefined();
60
+ expect(resolvePreviewAsset("README.md", "https://m8ven.ai/badge.png")).toBeUndefined();
61
+ const html = rewritePreviewAssets(
62
+ '<img src="brand/logo/mark.svg" /><source srcset="brand/logo/dark.png" />',
63
+ "README.md",
64
+ (rel) => `/bytes/${rel}`,
65
+ );
66
+ expect(html).toContain("/bytes/brand/logo/mark.svg");
67
+ expect(html).toContain("/bytes/brand/logo/dark.png");
68
+ });
69
+
70
+ test("strips scripts and handlers from html", () => {
71
+ const clean = sanitizePreviewHtml(
72
+ '<p onclick="alert(1)">Hi</p><script>alert(1)</script><img src="javascript:alert(1)" />',
73
+ );
74
+ expect(clean).not.toContain("script");
75
+ expect(clean).not.toContain("onclick");
76
+ expect(clean).not.toContain("javascript:");
77
+ expect(renderPreviewHtml("<h1>Hi</h1>", "html")).toContain("<h1>Hi</h1>");
78
+ });
79
+ });