Skip to content

Your lightweight open-source personal agent.

feat(webui): preview Markdown files with a source toggle

Xubin Ren0869c928a22e
diff --git a/docs/webui.md b/docs/webui.md
index 8b96d95b3..9f2ee3874 100644
--- a/docs/webui.md
+++ b/docs/webui.md
@@ -121,7 +121,9 @@ When the agent writes or edits files, the activity item shows the target path, s
Files open as tabs in one preview pane. Select another file to add or switch a tab without reopening the pane; close a tab with its **×**, or close the pane with **Escape**. Tabs and width follow each session while the WebUI remains open. They are kept only in memory and cleared when that session is deleted or the connection ends. The pane overlays the conversation on narrow screens.
-Text previews include up to 384 KiB, with a notice when the file is truncated. Large previews show readable text before adding syntax colors; very large or minified source stays plain text. All previewed text remains available for selection and browser search, and the code pane scrolls in both directions.
+Markdown files open in **Preview**, with formatted headings, lists, tables and code blocks. Select **Source** to see the original Markdown with line numbers, then **Preview** to return. The control changes only the display; it does not edit or read the file again. Each newly opened or selected file starts in Preview. Images in Markdown appear as links and do not load automatically. Local links open through the same file access checks; relative paths start from the document's folder. Section-only links remain text. HTML and MDX components do not execute.
+
+Text previews include up to 384 KiB, with a notice when the file is truncated. Large source previews show readable text before adding syntax colors; very large or minified source stays plain text. All previewed text remains available for selection and browser search, and the source pane scrolls in both directions.
PNG, JPEG, GIF and WebP files up to 8 MiB can be previewed as images. Hover or focus an image file reference for a compact quick look, or select it to open the pane. Select the preview image for the full-size viewer, which supports zoom controls, pinch-to-zoom and panning. HTML and SVG files remain read-only source previews rather than executable pages.
diff --git a/webui/src/components/FilePreviewPanel.tsx b/webui/src/components/FilePreviewPanel.tsx
index 0e57b4309..856cf4a98 100644
--- a/webui/src/components/FilePreviewPanel.tsx
+++ b/webui/src/components/FilePreviewPanel.tsx
@@ -9,6 +9,7 @@ interface FilePreviewPanelProps {
token: string;
loadPreview?: (path: string) => Promise<FilePreviewPayload>;
initialPreview?: FilePreviewPayload;
+ onOpenFilePreview?: (path: string) => void;
}
export function FilePreviewPanel({
@@ -17,6 +18,7 @@ export function FilePreviewPanel({
token,
loadPreview,
initialPreview,
+ onOpenFilePreview,
}: FilePreviewPanelProps) {
const [state, setState] = useState<FilePreviewPanelState>(() => initialPreview
? { status: "ready", payload: initialPreview } : { status: "loading" });
@@ -55,6 +57,7 @@ export function FilePreviewPanel({
}, [path, sessionKey, loadPreview]);
const reportImageError = useCallback(() => setState({ status: "error" }), []);
- return <FilePreviewPanelView path={path} state={state} imageOpen={imageOpen}
+ return <FilePreviewPanelView key={`${sessionKey}:${path}`} path={path} state={state} imageOpen={imageOpen}
+ onOpenFilePreview={onOpenFilePreview}
onImageOpenChange={setImageOpen} onImageError={reportImageError} />;
}
diff --git a/webui/src/components/FilePreviewPanelView.tsx b/webui/src/components/FilePreviewPanelView.tsx
index 04d570252..08714dae0 100644
--- a/webui/src/components/FilePreviewPanelView.tsx
+++ b/webui/src/components/FilePreviewPanelView.tsx
@@ -1,7 +1,10 @@
+import { useState } from "react";
import { useTranslation } from "react-i18next";
import { AlertCircle } from "lucide-react";
import { CodeBlock } from "@/components/CodeBlock";
+import { MarkdownText } from "@/components/MarkdownText";
+import { SegmentedControl } from "@/components/ui/segmented-control";
import { ImageLightbox } from "@/components/ImageLightbox";
import { fileKindForPath, splitFilePath } from "@/components/FileReferenceChip";
import type { FilePreviewPayload } from "@/lib/types";
@@ -11,14 +14,18 @@ export type FilePreviewPanelState =
| { status: "error"; message?: string; routeMissing?: boolean }
| { status: "ready"; payload: FilePreviewPayload };
-export function FilePreviewPanelView({ path, state, imageOpen, onImageOpenChange, onImageError }: {
+export function FilePreviewPanelView({ path, state, imageOpen, onImageOpenChange, onImageError, onOpenFilePreview }: {
path: string;
state: FilePreviewPanelState;
imageOpen: boolean;
onImageOpenChange: (open: boolean) => void;
onImageError: () => void;
+ onOpenFilePreview?: (path: string) => void;
}) {
const { t } = useTranslation();
+ const [mode, setMode] = useState<"preview" | "source">("preview");
+ const markdown = state.status === "ready" && state.payload.kind !== "image"
+ && state.payload.language === "markdown";
const displayPath = state.status === "ready" ? state.payload.display_path : path;
const { name } = splitFilePath(displayPath);
const fileName = name || displayPath;
@@ -32,7 +39,14 @@ export function FilePreviewPanelView({ path, state, imageOpen, onImageOpenChange
return (
<section aria-label={t("filePreview.aria")} data-testid="file-preview-panel" className="flex min-h-0 flex-1 flex-col">
- <div data-file-preview-scroll tabIndex={0}
+ {markdown ? (
+ <div className="flex shrink-0 items-center justify-end px-4 py-2">
+ <SegmentedControl value={mode} onChange={setMode} ariaLabel={t("filePreview.displayMode")}
+ options={[{ value: "preview", label: t("filePreview.preview") }, { value: "source", label: t("filePreview.source") }]}
+ itemClassName="px-3 [@media(pointer:coarse)]:min-h-9" />
+ </div>
+ ) : null}
+ <div key={mode} data-file-preview-scroll tabIndex={0}
className="min-h-0 flex-1 overflow-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/60">
{state.status === "loading" ? (
<div role="status" aria-label={t("filePreview.loading", { defaultValue: "Loading preview..." })}
@@ -77,7 +91,12 @@ export function FilePreviewPanelView({ path, state, imageOpen, onImageOpenChange
})}
</div>
) : null}
- <CodeBlock
+ {markdown && mode === "preview" ? (
+ <MarkdownText documentPath={state.payload.path} onOpenFilePreview={onOpenFilePreview}
+ className="px-5 pb-6 pt-1 text-sm [overflow-wrap:anywhere] sm:px-6 [&>:first-child]:mt-0">
+ {state.payload.content}
+ </MarkdownText>
+ ) : <CodeBlock
language={state.payload.language}
code={state.payload.content}
chrome="none"
@@ -86,7 +105,7 @@ export function FilePreviewPanelView({ path, state, imageOpen, onImageOpenChange
wrapLongLines={false}
viewportHighlight
className="min-h-full"
- />
+ />}
</div>
)}
</div>
diff --git a/webui/src/components/MarkdownText.tsx b/webui/src/components/MarkdownText.tsx
index dd1f23386..42fb4c601 100644
--- a/webui/src/components/MarkdownText.tsx
+++ b/webui/src/components/MarkdownText.tsx
@@ -15,6 +15,7 @@ interface MarkdownTextProps {
streaming?: boolean;
preserveStreamingLayout?: boolean;
onOpenFilePreview?: (path: string) => void;
+ documentPath?: string;
}
const loadMarkdownRenderer = () => import("@/components/MarkdownTextRenderer");
@@ -27,6 +28,7 @@ const MemoizedMarkdownRenderer = memo(function MemoizedMarkdownRenderer({
streaming,
preserveStreamingLayout,
onOpenFilePreview,
+ documentPath,
}: {
source: string;
className?: string;
@@ -34,6 +36,7 @@ const MemoizedMarkdownRenderer = memo(function MemoizedMarkdownRenderer({
streaming: boolean;
preserveStreamingLayout: boolean;
onOpenFilePreview?: (path: string) => void;
+ documentPath?: string;
}) {
return (
<LazyMarkdownRenderer
@@ -42,6 +45,7 @@ const MemoizedMarkdownRenderer = memo(function MemoizedMarkdownRenderer({
streaming={streaming}
preserveStreamingLayout={preserveStreamingLayout}
onOpenFilePreview={onOpenFilePreview}
+ documentPath={documentPath}
>
{source}
</LazyMarkdownRenderer>
@@ -80,6 +84,7 @@ export function MarkdownText({
streaming = false,
preserveStreamingLayout = false,
onOpenFilePreview,
+ documentPath,
}: MarkdownTextProps) {
const renderedSource = children;
const renderPhase = streaming ? "streaming" : "complete";
@@ -111,6 +116,7 @@ export function MarkdownText({
streaming={streaming}
preserveStreamingLayout={preserveStreamingLayout}
onOpenFilePreview={onOpenFilePreview}
+ documentPath={documentPath}
/>
</Suspense>
</MarkdownRendererBoundary>
diff --git a/webui/src/components/MarkdownTextRenderer.tsx b/webui/src/components/MarkdownTextRenderer.tsx
index 2fbc84f57..448498ed7 100644
--- a/webui/src/components/MarkdownTextRenderer.tsx
+++ b/webui/src/components/MarkdownTextRenderer.tsx
@@ -33,6 +33,7 @@ import {
FileReferenceChip,
isFilePatternReference,
isLikelyFilePath,
+ splitFilePath,
} from "@/components/FileReferenceChip";
import { useLogoFallback } from "@/hooks/useLogoFallback";
import { inferMediaKind } from "@/lib/media";
@@ -50,6 +51,8 @@ interface MarkdownTextRendererProps {
streaming?: boolean;
preserveStreamingLayout?: boolean;
onOpenFilePreview?: (path: string) => void;
+ /** Read-only documents must not load embedded resources or use chat routing. */
+ documentPath?: string;
}
type MarkdownAstNode = {
@@ -388,6 +391,29 @@ function fileReferenceFromLink(href: string | undefined): string | null {
return isPreviewableFileTarget(target) ? target : null;
}
+function DocumentLink({ href, path, onOpen, children }: {
+ href: string;
+ path: string;
+ onOpen?: (path: string) => void;
+ children: ReactNode;
+}) {
+ // Fragment-only links must not replace the application's hash route.
+ if (!href || href.startsWith("#")) return <>{children}</>;
+ if (/^(https?:\/\/|mailto:)/i.test(href)) {
+ return <WebLink href={href} className="text-blue-500 underline underline-offset-2 dark:text-blue-300">{children}</WebLink>;
+ }
+ if (/^[a-z][a-z\d+.-]*:/i.test(href) || href.startsWith("//")) return <>{children}</>;
+ let target = href.split(/[?#]/, 1)[0];
+ try { target = decodeURIComponent(target); } catch { return <>{children}</>; }
+ if (!target) return <>{children}</>;
+ // Resolve against the document, not the WebUI origin or the project root.
+ // The gateway still resolves and authorizes the resulting path.
+ const resolved = /^[\\/]|^[a-z]:[\\/]/i.test(target)
+ ? target : `${splitFilePath(path).directory}${target}`;
+ return <FileReferenceChip path={nodeText(children) || target} previewPath={resolved}
+ tooltipPath={resolved} onOpen={onOpen} />;
+}
+
function sessionReferenceHref(href: string): string | null {
const prefix = href.startsWith("#session/")
? "#session/"
@@ -554,6 +580,7 @@ export default function MarkdownTextRenderer({
streaming = false,
preserveStreamingLayout = false,
onOpenFilePreview,
+ documentPath,
}: MarkdownTextRendererProps) {
const { t } = useTranslation();
const [mathPlugin, setMathPlugin] = useState(() => loadedMathPlugin);
@@ -588,7 +615,7 @@ export default function MarkdownTextRenderer({
);
}
const raw = String(kids).replace(/\n$/, "");
- if (isLikelyFilePath(raw)) {
+ if (!documentPath && isLikelyFilePath(raw)) {
return (
<InferredFileReferenceChip
path={raw}
@@ -663,6 +690,9 @@ export default function MarkdownTextRenderer({
if (href === "streamdown:incomplete-link") {
return <>{markdownChildren}</>;
}
+ if (documentPath) {
+ return <DocumentLink href={href} path={documentPath} onOpen={onOpenFilePreview}>{markdownChildren}</DocumentLink>;
+ }
const sessionHref = sessionReferenceHref(href);
if (sessionHref) {
return (
@@ -764,7 +794,7 @@ export default function MarkdownTextRenderer({
);
},
li({ children: markdownChildren, className: itemClassName }) {
- const link = inlineLinkPreviewFromChildren(markdownChildren);
+ const link = !documentPath && inlineLinkPreviewFromChildren(markdownChildren);
if (link) {
return (
<li className={cn("list-none pl-0", itemClassName)}>
@@ -837,6 +867,9 @@ export default function MarkdownTextRenderer({
const source = typeof src === "string" ? src : "";
if (!source) return null;
const label = typeof alt === "string" ? alt : "";
+ if (documentPath) {
+ return <DocumentLink href={source} path={documentPath} onOpen={onOpenFilePreview}>{label || source}</DocumentLink>;
+ }
const kind = markdownAttachmentKind(source, label);
return (
<AttachmentTile
@@ -850,7 +883,7 @@ export default function MarkdownTextRenderer({
);
},
}),
- [highlightCode, onOpenFilePreview, t],
+ [highlightCode, onOpenFilePreview, documentPath, t],
);
return (
diff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsx
index 1d7d39304..b6529a871 100644
--- a/webui/src/components/thread/ThreadShell.tsx
+++ b/webui/src/components/thread/ThreadShell.tsx
@@ -2134,6 +2134,7 @@ export function ThreadShell({
token={token}
loadPreview={filePreviews.load}
initialPreview={filePreviews.peek(activePreview.value)}
+ onOpenFilePreview={openFilePreview}
/>
) : <WebPreviewPanel key={activePreview.id} url={activePreview.value} />}
</PreviewPane>
diff --git a/webui/src/dev/gallery/content.tsx b/webui/src/dev/gallery/content.tsx
index 2ee355062..35c4842ce 100644
--- a/webui/src/dev/gallery/content.tsx
+++ b/webui/src/dev/gallery/content.tsx
@@ -8,20 +8,22 @@ import type { AutomationUpdatePayload, SessionAutomationJob, UIMessage } from "@
import { StatePicker, type ComponentExample } from "./example";
function FilePreview() {
- const [mode, setMode] = useState<"text" | "image" | "truncated" | "loading" | "error" | "route_missing">("text");
+ const [mode, setMode] = useState<"markdown" | "text" | "image" | "truncated" | "loading" | "error" | "route_missing">("markdown");
const [imageOpen, setImageOpen] = useState(false);
- const path = mode === "image" ? "nanobot.png" : "greeting.ts";
+ const path = mode === "image" ? "nanobot.png" : mode === "markdown" || mode === "truncated" ? "REPORT.md" : "greeting.ts";
const state: FilePreviewPanelState = mode === "loading" ? { status: "loading" }
: mode === "error" || mode === "route_missing" ? { status: "error", routeMissing: mode === "route_missing" }
: { status: "ready", payload: mode === "image"
? { kind: "image", path, display_path: path, project_path: "/workspace", size: 24_576, mime_type: "image/png", data_url: "/brand/nanobot_icon_512.png" }
- : { path, display_path: path, project_path: "/workspace", size: 128, language: "typescript", truncated: mode === "truncated",
- content: 'export const greeting = "Hello, Nanobot";\n\nexport function greet(name: string) {\n return `${greeting}, ${name}`;\n}\n' } };
+ : { path, display_path: path, project_path: "/workspace", size: 128, language: path.endsWith(".md") ? "markdown" : "typescript", truncated: mode === "truncated",
+ content: path.endsWith(".md")
+ ? '# Skills 迁移报告\n\n已完成迁移,**原文件保持不变**。\n\n## 验证结果\n\n| 项目 | 结果 |\n| --- | --- |\n| 文件数量 | 1,199 个 |\n| 校验 | SHA-256 一致 |\n\n- [x] 保留原目录\n- [x] 检查引用\n\n## 下一步\n\n打开技能目录,确认所需服务已连接。\n\n```sh\nls skills/\n```\n\n![示意图](https://example.com/chart.png)\n'
+ : 'export const greeting = "Hello, Nanobot";\n\nexport function greet(name: string) {\n return `${greeting}, ${name}`;\n}\n' } };
return <div className="space-y-4">
- <StatePicker label="文件预览状态" value={mode} options={["text", "image", "truncated", "loading", "error", "route_missing"]}
+ <StatePicker label="文件预览状态" value={mode} options={["markdown", "text", "image", "truncated", "loading", "error", "route_missing"]}
onChange={(next) => { setMode(next); setImageOpen(false); }} />
- <div className="flex h-80 flex-col overflow-hidden rounded-control border">
- <FilePreviewPanelView path={path} state={state} imageOpen={imageOpen} onImageOpenChange={setImageOpen}
+ <div className="flex h-[32rem] flex-col overflow-hidden rounded-control border">
+ <FilePreviewPanelView key={path} path={path} state={state} imageOpen={imageOpen} onImageOpenChange={setImageOpen}
onImageError={() => { setMode("error"); setImageOpen(false); }} />
</div>
</div>;
diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json
index 27d2b411f..d6d61f29e 100644
--- a/webui/src/i18n/locales/en/common.json
+++ b/webui/src/i18n/locales/en/common.json
@@ -2437,6 +2437,9 @@
"gatewayPath": "Paths refer to the gateway machine."
},
"filePreview": {
+ "displayMode": "Display mode",
+ "preview": "Preview",
+ "source": "Source",
"aria": "File preview",
"breadcrumb": "File path",
"close": "Close file preview",
diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json
index ccf1f7528..88c08899e 100644
--- a/webui/src/i18n/locales/es/common.json
+++ b/webui/src/i18n/locales/es/common.json
@@ -2238,6 +2238,9 @@
"gatewayPath": "Las rutas pertenecen al equipo del gateway."
},
"filePreview": {
+ "displayMode": "Modo de visualización",
+ "preview": "Vista previa",
+ "source": "Código fuente",
"aria": "Vista previa de archivo",
"breadcrumb": "Ruta del archivo",
"close": "Cerrar vista previa de archivo",
diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json
index 4ab330ebb..ae061a5d1 100644
--- a/webui/src/i18n/locales/fr/common.json
+++ b/webui/src/i18n/locales/fr/common.json
@@ -2237,6 +2237,9 @@
"gatewayPath": "Les chemins désignent la machine de la passerelle."
},
"filePreview": {
+ "displayMode": "Mode d’affichage",
+ "preview": "Aperçu",
+ "source": "Source",
"aria": "Aperçu du fichier",
"breadcrumb": "Chemin du fichier",
"close": "Fermer l’aperçu du fichier",
diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json
index f2f3bfd73..46cacbfcf 100644
--- a/webui/src/i18n/locales/id/common.json
+++ b/webui/src/i18n/locales/id/common.json
@@ -2237,6 +2237,9 @@
"gatewayPath": "Jalur merujuk ke komputer gateway."
},
"filePreview": {
+ "displayMode": "Mode tampilan",
+ "preview": "Pratinjau",
+ "source": "Sumber",
"aria": "Pratinjau file",
"breadcrumb": "Jalur file",
"close": "Tutup pratinjau file",
diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json
index 81206ead0..77b1f0cb5 100644
--- a/webui/src/i18n/locales/ja/common.json
+++ b/webui/src/i18n/locales/ja/common.json
@@ -2237,6 +2237,9 @@
"gatewayPath": "パスはゲートウェイのマシンを指します。"
},
"filePreview": {
+ "displayMode": "表示モード",
+ "preview": "プレビュー",
+ "source": "ソース",
"aria": "ファイルプレビュー",
"breadcrumb": "ファイルパス",
"close": "ファイルプレビューを閉じる",
diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json
index 860e9dcea..f1d22cd5e 100644
--- a/webui/src/i18n/locales/ko/common.json
+++ b/webui/src/i18n/locales/ko/common.json
@@ -2237,6 +2237,9 @@
"gatewayPath": "경로는 게이트웨이 컴퓨터를 가리킵니다."
},
"filePreview": {
+ "displayMode": "표시 방식",
+ "preview": "미리 보기",
+ "source": "원문",
"aria": "파일 미리보기",
"breadcrumb": "파일 경로",
"close": "파일 미리보기 닫기",
diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json
index a0ce4cfc6..16506615e 100644
--- a/webui/src/i18n/locales/pt-BR/common.json
+++ b/webui/src/i18n/locales/pt-BR/common.json
@@ -2251,6 +2251,9 @@
"gatewayPath": "Os caminhos se referem à máquina do gateway."
},
"filePreview": {
+ "displayMode": "Modo de exibição",
+ "preview": "Prévia",
+ "source": "Código-fonte",
"aria": "Pré-visualização de arquivo",
"breadcrumb": "Caminho do arquivo",
"close": "Fechar pré-visualização de arquivo",
diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json
index 4fc1c9a8b..a1048a16a 100644
--- a/webui/src/i18n/locales/vi/common.json
+++ b/webui/src/i18n/locales/vi/common.json
@@ -2237,6 +2237,9 @@
"gatewayPath": "Đường dẫn thuộc máy chạy gateway."
},
"filePreview": {
+ "displayMode": "Chế độ hiển thị",
+ "preview": "Xem trước",
+ "source": "Mã nguồn",
"aria": "Xem trước tệp",
"breadcrumb": "Đường dẫn tệp",
"close": "Đóng xem trước tệp",
diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json
index 6b0dfa6dd..8ba6b4031 100644
--- a/webui/src/i18n/locales/zh-CN/common.json
+++ b/webui/src/i18n/locales/zh-CN/common.json
@@ -2437,6 +2437,9 @@
"gatewayPath": "路径指向网关所在的机器。"
},
"filePreview": {
+ "displayMode": "显示方式",
+ "preview": "预览",
+ "source": "原文",
"aria": "文件预览",
"breadcrumb": "文件路径",
"close": "关闭文件预览",
diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json
index d8876dcff..272e90ac6 100644
--- a/webui/src/i18n/locales/zh-TW/common.json
+++ b/webui/src/i18n/locales/zh-TW/common.json
@@ -2237,6 +2237,9 @@
"gatewayPath": "路徑指向閘道所在的電腦。"
},
"filePreview": {
+ "displayMode": "顯示方式",
+ "preview": "預覽",
+ "source": "原文",
"aria": "檔案預覽",
"breadcrumb": "檔案路徑",
"close": "關閉檔案預覽",
diff --git a/webui/src/tests/file-preview-panel.test.tsx b/webui/src/tests/file-preview-panel.test.tsx
index eb9aeaa2d..a4b9a445f 100644
--- a/webui/src/tests/file-preview-panel.test.tsx
+++ b/webui/src/tests/file-preview-panel.test.tsx
@@ -168,13 +168,82 @@ describe("FilePreviewPanel", () => {
/>,
);
- await screen.findByTestId("mock-code-block");
+ await screen.findByRole("heading", { name: "Notes" });
expect(fetchFilePreview).toHaveBeenCalledTimes(1);
await act(async () => {
await setAppLanguage("zh-CN");
});
+ expect(screen.getByRole("button", { name: "预览" })).toHaveAttribute("aria-pressed", "true");
+ expect(screen.getByRole("button", { name: "原文" })).toBeInTheDocument();
+ expect(fetchFilePreview).toHaveBeenCalledTimes(1);
+ });
+
+ it("defaults old Markdown payloads to preview and switches to exact source without another read", async () => {
+ const content = "# Report\n\n**Done**\n\n| Item | Status |\n| --- | --- |\n| Copy | OK |\n";
+ vi.mocked(fetchFilePreview).mockResolvedValue({ path: "/workspace/REPORT.md", display_path: "REPORT.md",
+ language: "markdown", content, truncated: true });
+ render(<FilePreviewPanel sessionKey="a" path="REPORT.md" token="test" />);
+ await screen.findByRole("heading", { name: "Report" });
+ expect(screen.getByRole("table")).toHaveTextContent("CopyOK");
+ const notice = "Preview is truncated because this file is large.";
+ expect(screen.getByText(notice)).toBeInTheDocument();
+ const source = screen.getByRole("button", { name: "Source" });
+ source.focus();
+ fireEvent.click(source);
+ expect(source).toHaveFocus();
+ expect(source).toHaveAttribute("aria-pressed", "true");
+ expect(screen.getByTestId("mock-code-block").textContent).toBe(content);
+ expect(CodeBlock).toHaveBeenLastCalledWith(expect.objectContaining({
+ code: content, chrome: "none", showLineNumbers: true, wrapLongLines: false, viewportHighlight: true,
+ }), expect.anything());
+ expect(screen.getByText(notice)).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Preview" }));
+ await screen.findByRole("heading", { name: "Report" });
+ expect(fetchFilePreview).toHaveBeenCalledTimes(1);
+ });
+
+ it("resets the display for another file or session but keeps source on credential renewal", async () => {
+ const payload = { path: "/workspace/notes.md", display_path: "notes.md", language: "markdown",
+ content: "# Notes", truncated: false };
+ vi.mocked(fetchFilePreview).mockResolvedValue(payload);
+ const view = (path: string, sessionKey = "a", token = "old") =>
+ <FilePreviewPanel sessionKey={sessionKey} path={path} token={token} />;
+ const { rerender } = render(view("notes.md"));
+ await screen.findByRole("heading", { name: "Notes" });
+ fireEvent.click(screen.getByRole("button", { name: "Source" }));
+ rerender(view("notes.md", "a", "new"));
+ expect(screen.getByRole("button", { name: "Source" })).toHaveAttribute("aria-pressed", "true");
+ expect(fetchFilePreview).toHaveBeenCalledTimes(1);
+ rerender(view("other.md"));
+ await screen.findByRole("heading", { name: "Notes" });
+ fireEvent.click(screen.getByRole("button", { name: "Source" }));
+ rerender(view("other.md", "b"));
+ await screen.findByRole("heading", { name: "Notes" });
+ expect(fetchFilePreview).toHaveBeenCalledTimes(3);
+ });
+
+ it("keeps document resources inert and opens relative links through the session preview callback", async () => {
+ const open = vi.fn();
+ vi.mocked(fetchFilePreview).mockResolvedValue({ path: "/workspace/reports/REPORT.mdx", display_path: "reports/REPORT.mdx",
+ language: "markdown", truncated: false, content: [
+ "# Report", "[Local](../notes%20one.md)", "![Chart](https://example.com/chart.png)",
+ "- Reference — [Website](https://example.com)", "[Section](#details)", "[Chat](#/chat/websocket:other)",
+ "[Unsafe](javascript:alert(1))", '<img src="https://example.com/raw.png" onerror="alert(1)">',
+ '<iframe src="https://example.com/frame"></iframe>', '<script>alert(1)</script>',
+ "`skills/cron/SKILL.md`", "<CustomComponent />",
+ ].join("\n\n") });
+ const { container } = render(<FilePreviewPanel sessionKey="a" path="reports/REPORT.mdx" token="test" onOpenFilePreview={open} />);
+ await screen.findByRole("heading", { name: "Report" });
+ expect(container.querySelector("img, iframe, script, video, audio")).toBeNull();
+ expect(screen.getByRole("link", { name: "Chart" })).toHaveAttribute("href", "https://example.com/chart.png");
+ expect(screen.getByRole("link", { name: "Website" })).toHaveAttribute("rel", "noreferrer noopener");
+ expect(screen.queryByRole("link", { name: /Section|Chat|Unsafe/ })).not.toBeInTheDocument();
+ expect(container.querySelector("code")?.textContent).toBe("skills/cron/SKILL.md");
+ expect(open).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole("button", { name: "/workspace/reports/../notes one.md" }));
+ expect(open).toHaveBeenCalledWith("/workspace/reports/../notes one.md");
expect(fetchFilePreview).toHaveBeenCalledTimes(1);
});