Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(preview): show why a linked HTML page can't open, and its real file name

AdityaUmale3dc310fb01b3
diff --git a/src/components/ChatMarkdown.test.ts b/src/components/ChatMarkdown.test.ts
index 405d82650d..d1101b80af 100644
--- a/src/components/ChatMarkdown.test.ts
+++ b/src/components/ChatMarkdown.test.ts
@@ -822,6 +822,23 @@ describe("ChatMarkdown attachments", () => {
}
});
+ it("names a linked page by its real file name, not its percent-encoded spelling", () => {
+ const filePath = String.raw`C:\Users\Maus\Downloads\2026 AI视频分析报告.html`;
+ for (const text of [`[报告](<${filePath}>)`, "已保存到 `" + filePath + "`", "[报告](file:///C:/Users/Maus/Downloads/2026%20AI%E8%A7%86%E9%A2%91%E5%88%86%E6%9E%90%E6%8A%A5%E5%91%8A.html)"]) {
+ const html = renderToStaticMarkup(createElement(ChatMarkdown, { text, message: { threadId: "thread-1", messageId: "message-1" } }));
+ expect(html).toContain('title="Preview page: 2026 AI视频分析报告.html"');
+ expect(html).toContain('aria-label="Save a copy of 2026 AI视频分析报告.html"');
+ expect(html).not.toContain("%E8");
+ }
+ });
+
+ it("decodes a linked name once: a literal %25 in a file:// link stays as written", () => {
+ const html = renderToStaticMarkup(createElement(ChatMarkdown, {
+ text: "[Report](file:///Users/maus/100%2541%20report.html)", message: { threadId: "thread-1", messageId: "message-1" },
+ }));
+ expect(html).toContain('title="Preview page: 100%41 report.html"');
+ });
+
it("preserves dollar signs in Windows file destinations", () => {
const save = vi.spyOn(AttachmentPreview, "useLocalFileSave");
const filePath = "C:\\Users\\Maus\\R$5\\receipt.pdf";
diff --git a/src/components/ChatMarkdown.tsx b/src/components/ChatMarkdown.tsx
index 3db4b0dea8..2318bb5ab2 100644
--- a/src/components/ChatMarkdown.tsx
+++ b/src/components/ChatMarkdown.tsx
@@ -69,6 +69,12 @@ export const localFilePath = (href?: string): string | null => {
return href;
};
+// A plain-path link as the server reads it: cut at ? or #, then percent-decoded once.
+export const decodedLinkPath = (href: string): string => {
+ try { return decodeURIComponent(href.split(/[?#]/, 1)[0]!); }
+ catch { return href; }
+};
+
export function chatUrlTransform(value: string, key = "href"): string {
if (looksLikeThreadRefUrl(value) || isUseMyComputerUrl(value)) return value;
// Markdown-to-HTML percent-encodes a destination's backslashes (C:%5CUsers…); restore them and leave other escapes
@@ -333,9 +339,9 @@ export function MermaidDiagram({ code }: MermaidDiagramProps) {
// Security: no href at all, since an <a href="file://…"> reaches setWindowOpenHandler on a middle or modifier click,
// which calls shell.openExternal without main's containment check.
// source: the original a delivered copy came from, offered on right-click (Show in Finder) like in the gallery.
-function LocalFileLink({ filePath, name, source, children, message }: { filePath: string; name?: string; source?: string; children?: ReactNode; message?: MessageAttachmentContext }) {
+function LocalFileLink({ filePath, shownName, name, source, children, message }: { filePath: string; shownName: string; name?: string; source?: string; children?: ReactNode; message?: MessageAttachmentContext }) {
const save = useLocalFileSave(filePath, name, message);
- const preview = useHtmlPreview(filePath, name ?? fileName(filePath), message);
+ const preview = useHtmlPreview(filePath, shownName, message);
const revealMenu = useRevealOriginalMenu();
if (!message) {
return <span title={t("chat.file.legacy")} className="break-words text-ink-secondary">{children}</span>;
@@ -352,8 +358,8 @@ function LocalFileLink({ filePath, name, source, children, message }: { filePath
<span dir="ltr" className="inline-flex flex-wrap items-center gap-x-1.5 [unicode-bidi:isolate]" {...revealMenu.targetProps(source)}>
{revealMenu.menu}
{preview.opens
- ? <SaveIconButton name={name ?? fileName(filePath)} save={save} retryable={save.retryable} />
- : <FilePreviewButton path={filePath} name={name ?? fileName(filePath)} message={message} />}
+ ? <SaveIconButton name={shownName} save={save} retryable={save.retryable} />
+ : <FilePreviewButton path={filePath} name={shownName} message={message} />}
<button
type="button"
onClick={preview.opens ? preview.show : () => void save.save()}
@@ -653,7 +659,9 @@ function MarkdownLink({ href, children, ...rest }: { href?: string; children?: R
if (localPath) {
const copy = delivered && Object.hasOwn(delivered, fileName(localPath)) ? delivered[fileName(localPath)] : undefined;
const source = copy && originals && Object.hasOwn(originals, copy) ? originals[copy] : undefined;
- return <LocalFileLink filePath={copy ?? localPath} name={copy ? fileName(localPath) : undefined} source={source} message={message}>{children}</LocalFileLink>;
+ // localFilePath already decodes a file:// URL; a plain path link is still encoded and gets the server's single decode.
+ const shownName = fileName(/^file:\/\//i.test(href) ? localPath : decodedLinkPath(localPath));
+ return <LocalFileLink filePath={copy ?? localPath} shownName={shownName} name={copy ? fileName(localPath) : undefined} source={source} message={message}>{children}</LocalFileLink>;
}
if (!/^https?:\/\//i.test(href)) {
return (
diff --git a/src/components/HtmlFilePreview.dom.test.ts b/src/components/HtmlFilePreview.dom.test.ts
new file mode 100644
index 0000000000..aef7ac5f64
--- /dev/null
+++ b/src/components/HtmlFilePreview.dom.test.ts
@@ -0,0 +1,42 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { HtmlFileButton } from "./HtmlFilePreview";
+
+const message = { threadId: "t", messageId: "m" };
+let host: HTMLDivElement, root: Root;
+
+beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ host = document.createElement("div"); document.body.append(host); root = createRoot(host);
+});
+afterEach(async () => { await act(async () => root.unmount()); host.remove(); vi.unstubAllGlobals(); });
+
+async function open(answer: () => Promise<Response>) {
+ vi.stubGlobal("fetch", vi.fn(answer));
+ await act(async () => root.render(createElement(HtmlFileButton, { path: "C:\\Users\\Maus\\Downloads\\report.html", name: "report.html", message })));
+ await act(async () => host.querySelector<HTMLButtonElement>("button")!.click());
+ await act(async () => { await new Promise(resolve => setTimeout(resolve, 20)); });
+}
+const alertText = () => document.body.querySelector("[role=alert]")?.textContent ?? "";
+
+describe("HTML file preview errors", () => {
+ it("shows the server's own reason instead of blaming the connection or the encoding", async () => {
+ await open(async () => new Response(JSON.stringify({ error: "the linked file is outside this conversation's workspace", code: "outside_workspace" }), { status: 403, headers: { "content-type": "application/json" } }));
+ expect(alertText()).toContain("the linked file is outside this conversation's workspace");
+ expect(alertText()).not.toContain("Check your connection");
+ expect(alertText()).not.toContain("UTF-8");
+ });
+
+ it("keeps the connection hint when the request itself fails", async () => {
+ await open(async () => { throw new TypeError("Failed to fetch"); });
+ expect(alertText()).toContain("Check your connection");
+ });
+
+ it("opens a page the server sends", async () => {
+ await open(async () => new Response("<h1>Report</h1>"));
+ expect(alertText()).toBe("");
+ expect(document.body.querySelector("iframe")?.getAttribute("srcdoc")).toContain("<h1>Report</h1>");
+ });
+});
diff --git a/src/components/HtmlFilePreview.tsx b/src/components/HtmlFilePreview.tsx
index 748e920555..de54cb40b1 100644
--- a/src/components/HtmlFilePreview.tsx
+++ b/src/components/HtmlFilePreview.tsx
@@ -117,7 +117,7 @@ export function OpenInBrowserButton({ source, name, onError }: { source: string;
function HtmlFileContent({ path, name, message }: { path: string; name: string; message: MessageAttachmentContext }) {
const [attempt, setAttempt] = useState(0);
const [source, setSource] = useState<string | null>(null);
- const [error, setError] = useState<"size" | "load" | null>(null);
+ const [error, setError] = useState<"size" | "load" | { reason: string } | null>(null);
const [showSource, setShowSource] = useState(false);
const [openFailed, setOpenFailed] = useState("");
const save = useLocalFileSave(path, name, message);
@@ -126,17 +126,22 @@ function HtmlFileContent({ path, name, message }: { path: string; name: string;
setError(null);
setSource(null);
void (async () => {
+ let answered = false;
try {
const response = await requestMessageFile(path, message, controller.signal);
+ answered = true;
const text = await readTableResponse(response, controller.signal, HTML_PREVIEW_MAX_BYTES);
if (!controller.signal.aborted) setSource(text);
} catch (reason) {
- if (!controller.signal.aborted) setError(reason instanceof Error && reason.message === "size" ? "size" : "load");
+ if (controller.signal.aborted) return;
+ // A refusal from the server says why; only a request that got no answer (TypeError) is the connection.
+ if (!answered && reason instanceof Error && !(reason instanceof TypeError)) setError({ reason: reason.message });
+ else setError(reason instanceof Error && reason.message === "size" ? "size" : "load");
}
})();
return () => controller.abort();
}, [path, message.threadId, message.messageId, attempt]);
- if (error) return <div className="p-8 text-center text-sm"><p role="alert" className="mb-3 text-ink-secondary">{t(error === "size" ? "html.tooLarge" : "html.loadFailed")}</p><button type="button" className="rounded-lg border border-hairline px-3 py-2 hover:bg-raised" onClick={() => setAttempt(attempt + 1)}>{t("chat.retry")}</button></div>;
+ if (error) return <div className="p-8 text-center text-sm"><p role="alert" className="mb-3 text-ink-secondary">{typeof error === "object" ? t("html.refused", { reason: error.reason }) : t(error === "size" ? "html.tooLarge" : "html.loadFailed")}</p><button type="button" className="rounded-lg border border-hairline px-3 py-2 hover:bg-raised" onClick={() => setAttempt(attempt + 1)}>{t("chat.retry")}</button></div>;
if (source === null) return <div role="status" className="flex items-center justify-center gap-2 p-12 text-sm text-ink-secondary"><LoaderCircle size={16} className="animate-spin" />{t("html.loading")}</div>;
return <div className="flex flex-col gap-2">
<div className="flex items-center justify-end gap-1">
diff --git a/src/locales/en.json b/src/locales/en.json
index 66750c1060..ca60aeea33 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -152,6 +152,7 @@
"html.loading": "Opening page…",
"html.tooLarge": "This page is too large for an in-app preview (2 MB). Download the original to view it.",
"html.loadFailed": "Could not open this page. Check your connection and try again. UTF-8 HTML files are supported.",
+ "html.refused": "Could not open this page: {reason}",
"html.source": "View source",
"html.rendered": "View page",
"html.reload": "Reload",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index b98283cb05..dda1813c32 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -135,6 +135,7 @@
"html.loading": "Abrindo a página…",
"html.tooLarge": "Esta página é grande demais para a prévia no app (2 MB). Baixe o original para vê-la.",
"html.loadFailed": "Não foi possível abrir esta página. Verifique sua conexão e tente novamente. São aceitos arquivos HTML em UTF-8.",
+ "html.refused": "Não foi possível abrir esta página: {reason}",
"html.source": "Ver código-fonte",
"html.rendered": "Ver página",
"html.reload": "Recarregar",
diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.json
index d63edea5b5..f9c2840163 100644
--- a/src/locales/source-hashes.json
+++ b/src/locales/source-hashes.json
@@ -25973,6 +25973,7 @@
"html.loading": "f53b55a15cf29dc21bbf98e3f7872fc8fabe4901181d7f9dec71bf030ba4a34f",
"html.tooLarge": "1052fb7237e6b60d1849ede58725b9fbc6b19e683e86dc3eec3972eb7c0fe20b",
"html.loadFailed": "d5a95b695583132d5aef905e1b503230bb22414faca23d9ee3c0df3aaaa08976",
+ "html.refused": "c0c7de7ab9b09ae9df076998a32215a2888a67a63ebfe0272b883b74573a9b47",
"html.source": "6ee818aa2de35ea6849319472b83678a5cb1273f3fb0383ffb279d7fa6c5b961",
"html.rendered": "1bcddf8728151cbdb50f1a43d0d628254f82238aa55d42d601c936ef5db8710b",
"html.reload": "bdc090ec61e3fcfc65f469951dfe00f3f2ecfc6003c44deac8e05b7237092de6",
@@ -40431,6 +40432,7 @@
"html.loading": "f53b55a15cf29dc21bbf98e3f7872fc8fabe4901181d7f9dec71bf030ba4a34f",
"html.tooLarge": "1052fb7237e6b60d1849ede58725b9fbc6b19e683e86dc3eec3972eb7c0fe20b",
"html.loadFailed": "d5a95b695583132d5aef905e1b503230bb22414faca23d9ee3c0df3aaaa08976",
+ "html.refused": "c0c7de7ab9b09ae9df076998a32215a2888a67a63ebfe0272b883b74573a9b47",
"html.source": "6ee818aa2de35ea6849319472b83678a5cb1273f3fb0383ffb279d7fa6c5b961",
"html.rendered": "1bcddf8728151cbdb50f1a43d0d628254f82238aa55d42d601c936ef5db8710b",
"html.reload": "bdc090ec61e3fcfc65f469951dfe00f3f2ecfc6003c44deac8e05b7237092de6",
diff --git a/src/locales/zh.json b/src/locales/zh.json
index 248195e8e7..c946eb1eeb 100644
--- a/src/locales/zh.json
+++ b/src/locales/zh.json
@@ -164,6 +164,7 @@
"html.loading": "正在打开页面…",
"html.tooLarge": "此页面过大,无法在应用内预览(上限 2 MB)。请下载原文件后再查看。",
"html.loadFailed": "无法打开此页面。请检查网络连接后重试。仅支持 UTF-8 编码的 HTML 文件。",
+ "html.refused": "无法打开此页面:{reason}",
"html.source": "查看源码",
"html.rendered": "查看页面",
"html.reload": "重新加载",