Skip to content

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

Open Windows-1252 Markdown files in the preview and show the server's reason (#5618)

Bugfixer 22a4303b1890d
diff --git a/src/components/MarkdownFilePreview.dom.test.ts b/src/components/MarkdownFilePreview.dom.test.ts
new file mode 100644
index 0000000000..63e3f835ec
--- /dev/null
+++ b/src/components/MarkdownFilePreview.dom.test.ts
@@ -0,0 +1,56 @@
+// @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 MarkdownFileContent from "./MarkdownFilePreview";
+
+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(MarkdownFileContent, { path: "/workspace/copy-v3.md", name: "copy-v3.md", message })));
+ await act(async () => { await new Promise(resolve => setTimeout(resolve, 20)); });
+ return host;
+}
+const alertText = () => host.querySelector("[role=alert]")?.textContent ?? "";
+
+describe("Markdown file preview errors and encodings (#5618)", () => {
+ it("opens a file saved as Windows-1252 instead of failing", async () => {
+ // "# Relatório\n\nAção concluída" in Windows-1252: ó=F3, ç=E7, ã=E3, í=ED.
+ const bytes = new Uint8Array([0x23, 0x20, 0x52, 0x65, 0x6c, 0x61, 0x74, 0xf3, 0x72, 0x69, 0x6f, 0x0a, 0x0a, 0x41, 0xe7, 0xe3, 0x6f, 0x20, 0x63, 0x6f, 0x6e, 0x63, 0x6c, 0x75, 0xed, 0x64, 0x61]);
+ await open(async () => new Response(bytes));
+ expect(alertText()).toBe("");
+ expect(host.textContent).toContain("Relatório");
+ expect(host.textContent).toContain("Ação concluída");
+ });
+
+ it("still opens UTF-8 files as UTF-8", async () => {
+ await open(async () => new Response(new TextEncoder().encode("# Relatório\n\nAção")));
+ expect(host.textContent).toContain("Relatório");
+ expect(host.textContent).toContain("Ação");
+ });
+
+ it("does not show a UTF-16 file as garbage", async () => {
+ const bytes = new Uint8Array([0xff, 0xfe, 0x23, 0x00, 0x20, 0x00, 0x41, 0x00, 0xe7, 0x00]);
+ await open(async () => new Response(bytes));
+ expect(alertText()).toContain("Could not open this file");
+ });
+
+ it("shows the server's own reason instead of blaming the connection", async () => {
+ await open(async () => new Response(JSON.stringify({ error: "That file is no longer in the bot's folder." }), { status: 404, headers: { "content-type": "application/json" } }));
+ expect(alertText()).toContain("That file is no longer in the bot's folder.");
+ expect(alertText()).not.toContain("Check your connection");
+ });
+
+ 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");
+ });
+});
diff --git a/src/components/MarkdownFilePreview.tsx b/src/components/MarkdownFilePreview.tsx
index 1a6912012e..1daac89738 100644
--- a/src/components/MarkdownFilePreview.tsx
+++ b/src/components/MarkdownFilePreview.tsx
@@ -12,7 +12,7 @@ export const MARKDOWN_PREVIEW_MAX_BYTES = 2 * 1024 * 1024;
export default function MarkdownFileContent({ 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 save = useLocalFileSave(path, name, message);
useEffect(() => {
@@ -20,19 +20,25 @@ export default function MarkdownFileContent({ path, name, message }: { path: str
setError(null);
setSource(null);
void (async () => {
+ let answered = false;
try {
const response = await requestMessageFile(path, message, controller.signal);
- const text = await readTableResponse(response, controller.signal, MARKDOWN_PREVIEW_MAX_BYTES);
+ answered = true;
+ // Notes saved by Windows apps are often Windows-1252, not UTF-8 (#5618).
+ const text = await readTableResponse(response, controller.signal, MARKDOWN_PREVIEW_MAX_BYTES, "windows-1252");
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 (#5618); 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]);
// Save and Retry stay on screen while loading too, so a stalled request never leaves only a spinner; they wrap so a long name can't push Retry off a narrow dialog.
const recovery = <><div className="mt-3 flex flex-wrap justify-center gap-2"><button type="button" className="inline-flex max-w-full min-w-0 items-center gap-1.5 rounded-lg border border-hairline px-3 py-2 hover:bg-raised" disabled={save.state === "saving"} onClick={() => void save.save()}><Download size={14} className="shrink-0" /><span className="min-w-0 break-all">{t("attach.saveAria", { name })}</span></button><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>{save.state === "failed" && <p role="alert" className="mt-2 text-[12px] text-danger">{save.reason}</p>}</>;
- if (error) return <div className="p-8 text-center text-sm"><p role="alert" className="text-ink-secondary">{t(error === "size" ? "markdown.tooLarge" : "markdown.loadFailed")}</p>{recovery}</div>;
+ if (error) return <div className="p-8 text-center text-sm"><p role="alert" className="text-ink-secondary">{typeof error === "object" ? t("markdown.refused", { reason: error.reason }) : t(error === "size" ? "markdown.tooLarge" : "markdown.loadFailed")}</p>{recovery}</div>;
if (source === null) return <div className="p-12 text-center text-sm text-ink-secondary"><span role="status" className="inline-flex items-center gap-2"><LoaderCircle size={16} className="animate-spin" />{t("markdown.loading")}</span>{recovery}</div>;
return <div className="flex flex-col gap-2">
<div className="flex items-center justify-end gap-1">
diff --git a/src/components/TableFilePreview.tsx b/src/components/TableFilePreview.tsx
index 4f973c2051..bf74ea01cf 100644
--- a/src/components/TableFilePreview.tsx
+++ b/src/components/TableFilePreview.tsx
@@ -5,15 +5,17 @@ import { RichTable, TableDialog } from "./RichTable";
import { TABLE_FILE_MAX_BYTES, tableDelimiter, type TextTable } from "@/lib/table-data";
import { t } from "@/lib/i18n";
-/** A preview limit, not a download limit: chunked responses are bounded too. */
-export async function readTableResponse(response: Response, signal: AbortSignal, maxBytes = TABLE_FILE_MAX_BYTES): Promise<string> {
+/** A preview limit, not a download limit: chunked responses are bounded too. Text that is not UTF-8 is refused, unless
+ * `fallback` names a single-byte encoding to read it in instead (#5618); a NUL byte (UTF-16, binary) is refused even
+ * then, since such an encoding would only show it as garbage. */
+export async function readTableResponse(response: Response, signal: AbortSignal, maxBytes = TABLE_FILE_MAX_BYTES, fallback?: string): Promise<string> {
if (Number(response.headers.get("content-length")) > maxBytes) {
await response.body?.cancel().catch(() => {}); throw new Error("size"); // A body that already errored must not hide "size".
}
const reader = response.body?.getReader();
if (!reader) return "";
- const decoder = new TextDecoder("utf-8", { fatal: true });
- let size = 0, text = "";
+ const parts: Uint8Array[] = [];
+ let size = 0;
try {
while (true) {
signal.throwIfAborted();
@@ -21,10 +23,14 @@ export async function readTableResponse(response: Response, signal: AbortSignal,
if (part.done) break;
size += part.value.byteLength;
if (size > maxBytes) throw new Error("size");
- text += decoder.decode(part.value, { stream: true });
+ parts.push(part.value);
}
- return text + decoder.decode();
} finally { await reader.cancel().catch(() => {}); reader.releaseLock(); }
+ const bytes = new Uint8Array(await new Blob(parts as BlobPart[]).arrayBuffer());
+ try { return new TextDecoder("utf-8", { fatal: true }).decode(bytes); } catch (error) {
+ if (!fallback || bytes.includes(0)) throw error;
+ return new TextDecoder(fallback).decode(bytes);
+ }
}
export function TableFileButton({ path, name, message }: { path: string; name: string; message: MessageAttachmentContext }) {
diff --git a/src/locales/en.json b/src/locales/en.json
index aefd5b77e7..42df858d23 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -160,6 +160,7 @@
"markdown.loading": "Opening file…",
"markdown.tooLarge": "This file is too large for an in-app preview (2 MB). Download the original to view it.",
"markdown.loadFailed": "Could not open this file. Check your connection and try again. UTF-8 text files are supported.",
+ "markdown.refused": "Could not open this file: {reason}",
"markdown.rendered": "View formatted",
"table.loading": "Opening table…",
"table.tooLarge": "This file is too large for an in-app preview (10 MB, 100,000 rows, 200 columns or 500,000 cells). Download the original to view it all.",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index aba9105544..2ffd7b116e 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -143,6 +143,7 @@
"markdown.loading": "Abrindo arquivo…",
"markdown.tooLarge": "Este arquivo é grande demais para a prévia no app (2 MB). Baixe o original para vê-lo.",
"markdown.loadFailed": "Não foi possível abrir este arquivo. Verifique sua conexão e tente novamente. Arquivos de texto UTF-8 são compatíveis.",
+ "markdown.refused": "Não foi possível abrir este arquivo: {reason}",
"markdown.rendered": "Ver formatado",
"table.loading": "Abrindo a tabela…",
"table.tooLarge": "Este arquivo é grande demais para a prévia no app (10 MB, 100.000 linhas, 200 colunas ou 500.000 células). Baixe o original para ver tudo.",