Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

fix(platform): render .pptx and other office files safely on the Files page (SECRT-2437) (#15359)

Abhimanyu Yadavb9f955f85f4d
diff --git a/autogpt_platform/backend/backend/api/features/workspace/preview.py b/autogpt_platform/backend/backend/api/features/workspace/preview.py
index e577100fc2..bfcf1982c0 100644
--- a/autogpt_platform/backend/backend/api/features/workspace/preview.py
+++ b/autogpt_platform/backend/backend/api/features/workspace/preview.py
@@ -7,6 +7,7 @@ whole file to the browser:
* raster images -> resized WebP thumbnail (Pillow)
* PDFs -> first page rasterised to WebP (pypdfium2)
* Office openxml docs -> embedded ``docProps/thumbnail`` re-encoded to WebP
+ (matched by extension too, whatever the stored MIME)
* text-like files -> first N bytes (partial read, no full download)
Image/PDF/Office thumbnails are cached in Redis keyed by file checksum so
@@ -67,6 +68,9 @@ _TEXT_HINTS = (
# types fall back to a static illustration on the frontend and never request a
# preview, so they don't need an extension fallback here.
_TEXT_EXTENSIONS = frozenset({"md", "markdown", "mdx"})
+# Office files are often stored with a wrong MIME (text/plain,
+# application/octet-stream), so the extension wins over the stored MIME.
+_OFFICE_EXTENSIONS = frozenset({"pptx", "docx", "xlsx"})
_EMBEDDED_THUMBNAILS = (
"docprops/thumbnail.jpeg",
"docprops/thumbnail.jpg",
@@ -90,15 +94,15 @@ async def _dispatch_preview(
) -> Response:
mime = (file.mime_type or "").lower()
+ if mime in OFFICE_MIMES or _extension(file.name) in _OFFICE_EXTENSIONS:
+ _ensure_size(file, PREVIEW_MAX_DOC_BYTES)
+ return _webp_response(await _office_thumbnail(file, width))
if mime.startswith("image/") and "svg" not in mime:
_ensure_size(file, PREVIEW_MAX_IMAGE_BYTES)
return _webp_response(await _image_thumbnail(file, width))
if mime == "application/pdf":
_ensure_size(file, PREVIEW_MAX_DOC_BYTES)
return _webp_response(await _pdf_thumbnail(file, width))
- if mime in OFFICE_MIMES:
- _ensure_size(file, PREVIEW_MAX_DOC_BYTES)
- return _webp_response(await _office_thumbnail(file, width))
if _is_text_like(mime, file.name):
_ensure_size(file, PREVIEW_MAX_TEXT_BYTES)
content = await _text_preview(file, max_bytes)
@@ -116,8 +120,11 @@ async def _dispatch_preview(
def _is_text_like(mime: str, name: str = "") -> bool:
if mime.startswith("text/") or any(hint in mime for hint in _TEXT_HINTS):
return True
- ext = name.rsplit(".", 1)[-1].lower() if "." in name else ""
- return ext in _TEXT_EXTENSIONS
+ return _extension(name) in _TEXT_EXTENSIONS
+
+
+def _extension(name: str) -> str:
+ return name.rsplit(".", 1)[-1].lower() if "." in name else ""
def _ensure_size(file: WorkspaceFile, limit: int) -> None:
diff --git a/autogpt_platform/backend/backend/api/features/workspace/preview_test.py b/autogpt_platform/backend/backend/api/features/workspace/preview_test.py
index d7892401b8..fdb0ec5fa6 100644
--- a/autogpt_platform/backend/backend/api/features/workspace/preview_test.py
+++ b/autogpt_platform/backend/backend/api/features/workspace/preview_test.py
@@ -153,6 +153,23 @@ def test_office_preview_extracts_embedded_thumbnail(mocker):
assert response.headers["content-type"] == "image/webp"
[email protected]("mime_type", ["text/plain", "application/octet-stream"])
[email protected]("name", ["deck.pptx", "report.docx", "sheet.xlsx"])
+def test_office_preview_by_extension_despite_wrong_mime(mocker, name, mime_type):
+ # Office files often store with a wrong MIME; the extension must still
+ # route them to thumbnail extraction instead of raw text bytes or a 415.
+ _mock_lookups(mocker, _make_file(name=name, path=f"/{name}", mime_type=mime_type))
+ storage = _mock_storage(mocker, _zip_bytes(with_thumbnail=True))
+ _mock_redis(mocker)
+
+ response = client.get("/files/file-001/preview")
+
+ assert response.status_code == 200
+ assert response.headers["content-type"] == "image/webp"
+ assert response.content[:4] == b"RIFF"
+ storage.retrieve_partial.assert_not_called()
+
+
def test_office_preview_without_thumbnail_returns_415(mocker):
_mock_lookups(mocker, _make_file(mime_type=PPTX_MIME))
_mock_storage(mocker, _zip_bytes(with_thumbnail=False))
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/office-files.test.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/office-files.test.tsx
new file mode 100644
index 0000000000..2cc3b312a6
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/office-files.test.tsx
@@ -0,0 +1,225 @@
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+import {
+ fireEvent,
+ render,
+ screen,
+ within,
+} from "@/tests/integrations/test-utils";
+import { server } from "@/mocks/mock-server";
+import { resetNavigation } from "./navigation-mock";
+import { http, HttpResponse } from "msw";
+import { getListExpertIdentitiesMockHandler } from "@/app/api/__generated__/endpoints/experts/experts.msw";
+import {
+ getGetWorkspaceStorageUsageMockHandler,
+ getListWorkspaceFilesMockHandler,
+ getListWorkspaceFoldersMockHandler,
+} from "@/app/api/__generated__/endpoints/workspace/workspace.msw";
+import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";
+
+vi.mock("@/services/feature-flags/use-get-flag", () => ({
+ Flag: {
+ ARTIFACTS_PAGE: "artifacts-page",
+ AUTOGPT_NEW_LAYOUT: "autogpt-new-layout",
+ HIRE_EXPERTS: "hire-experts",
+ },
+ useGetFlag: (flag: string) => flag !== "autogpt-new-layout",
+ useFlagStatus: () => ({ enabled: true, ready: true }),
+}));
+
+vi.mock("next/navigation", async () => {
+ const { navigationMock } = await import("./navigation-mock");
+ return navigationMock();
+});
+
+vi.mock("framer-motion", async (importActual) => {
+ const actual = await importActual<typeof import("framer-motion")>();
+ return { ...actual, useReducedMotion: () => true };
+});
+
+import ArtifactsPage from "../page";
+
+const PPTX_MIME =
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation";
+
+let downloadRequests: string[] = [];
+
+beforeEach(() => {
+ resetNavigation();
+ downloadRequests = [];
+ server.use(
+ getListExpertIdentitiesMockHandler([]),
+ getListWorkspaceFoldersMockHandler({ folders: [] }),
+ getGetWorkspaceStorageUsageMockHandler({
+ used_bytes: 0,
+ limit_bytes: 1_000_000_000,
+ used_percent: 0,
+ file_count: 0,
+ }),
+ http.get("/api/proxy/api/workspace/files/:id/download", ({ params }) => {
+ downloadRequests.push(String(params.id));
+ return HttpResponse.text("PK\u0003\u0004 binary zip bytes");
+ }),
+ );
+});
+
+function makeFile(
+ overrides: Partial<WorkspaceFileItem> = {},
+): WorkspaceFileItem {
+ return {
+ id: "file-base",
+ name: "base.txt",
+ path: "/base.txt",
+ mime_type: "text/plain",
+ size_bytes: 1024,
+ metadata: {},
+ origin: "generated",
+ created_at: "2026-05-01T00:00:00Z",
+ ...overrides,
+ };
+}
+
+function useFilesHandler(files: WorkspaceFileItem[]) {
+ server.use(
+ getListWorkspaceFilesMockHandler({
+ files,
+ offset: 0,
+ has_more: false,
+ }),
+ );
+}
+
+async function openViewer() {
+ fireEvent.click(await screen.findByTestId("artifacts-card-open"));
+ return screen.findByTestId("file-viewer");
+}
+
+function expectDownloadLink(viewer: HTMLElement, fileId: string) {
+ const link = within(viewer).getByRole("link", { name: /download/i });
+ expect(link.getAttribute("href")).toBe(
+ `/api/proxy/api/workspace/files/${fileId}/download`,
+ );
+}
+
+describe("ArtifactsPage - office files in the viewer", () => {
+ test.each([
+ ["a text MIME", "text/plain"],
+ ["the openxml MIME", PPTX_MIME],
+ ])(
+ "a .pptx with %s shows the slide thumbnail, never the raw bytes",
+ async (_label, mime) => {
+ useFilesHandler([
+ makeFile({ id: "deck1", name: "deck.pptx", mime_type: mime }),
+ ]);
+
+ render(<ArtifactsPage />);
+ const viewer = await openViewer();
+
+ const img = within(viewer).getByTestId("file-viewer-office-preview");
+ expect(img.getAttribute("src")).toContain(
+ "/api/proxy/api/workspace/files/deck1/preview?w=800",
+ );
+ expect(img.getAttribute("alt")).toBe("deck.pptx");
+ expectDownloadLink(viewer, "deck1");
+ expect(viewer.querySelector("pre")).toBeNull();
+ expect(within(viewer).queryByText(/can't be previewed/i)).toBeNull();
+ expect(downloadRequests).toEqual([]);
+ },
+ );
+
+ test("a .pptx stored as text/plain shows the loaded slide thumbnail", async () => {
+ useFilesHandler([
+ makeFile({ id: "deck3", name: "deck.pptx", mime_type: "text/plain" }),
+ ]);
+
+ render(<ArtifactsPage />);
+ const viewer = await openViewer();
+
+ const img = within(viewer).getByTestId("file-viewer-office-preview");
+ expect(img.className).toContain("opacity-0");
+
+ fireEvent.load(img);
+
+ expect(img.className).toContain("opacity-100");
+ expect(within(viewer).getByText(/showing the first slide/i)).toBeDefined();
+ expect(within(viewer).queryByText(/can't be previewed/i)).toBeNull();
+ expect(viewer.querySelector("pre")).toBeNull();
+ expect(downloadRequests).toEqual([]);
+ });
+
+ test("a deck without a thumbnail falls back to the download prompt", async () => {
+ useFilesHandler([
+ makeFile({ id: "deck2", name: "deck.pptx", mime_type: PPTX_MIME }),
+ ]);
+
+ render(<ArtifactsPage />);
+ const viewer = await openViewer();
+
+ fireEvent.error(within(viewer).getByTestId("file-viewer-office-preview"));
+
+ expect(
+ await within(viewer).findByText(/can't be previewed/i),
+ ).toBeDefined();
+ expect(
+ within(viewer).queryByTestId("file-viewer-office-preview"),
+ ).toBeNull();
+ expectDownloadLink(viewer, "deck2");
+ });
+
+ test("a .docx with a text MIME shows the thumbnail and falls back the same way", async () => {
+ useFilesHandler([
+ makeFile({ id: "doc1", name: "report.docx", mime_type: "text/plain" }),
+ ]);
+
+ render(<ArtifactsPage />);
+ const viewer = await openViewer();
+
+ const img = within(viewer).getByTestId("file-viewer-office-preview");
+ expect(img.getAttribute("src")).toContain(
+ "/api/proxy/api/workspace/files/doc1/preview?w=800",
+ );
+ expect(viewer.querySelector("pre")).toBeNull();
+
+ fireEvent.error(img);
+
+ expect(
+ await within(viewer).findByText(/can't be previewed/i),
+ ).toBeDefined();
+ expectDownloadLink(viewer, "doc1");
+ expect(downloadRequests).toEqual([]);
+ });
+
+ test("a .pptx over the 50MB preview cap goes straight to the download prompt", async () => {
+ useFilesHandler([
+ makeFile({
+ id: "big1",
+ name: "huge.pptx",
+ mime_type: "text/plain",
+ size_bytes: 60_000_000,
+ }),
+ ]);
+
+ render(<ArtifactsPage />);
+ const viewer = await openViewer();
+
+ expect(within(viewer).getByText(/can't be previewed/i)).toBeDefined();
+ expect(
+ within(viewer).queryByTestId("file-viewer-office-preview"),
+ ).toBeNull();
+ expect(viewer.querySelector("pre")).toBeNull();
+ expectDownloadLink(viewer, "big1");
+ });
+
+ test("a legacy .ppt with a text MIME is download-only, not text", async () => {
+ useFilesHandler([
+ makeFile({ id: "old1", name: "old.ppt", mime_type: "text/plain" }),
+ ]);
+
+ render(<ArtifactsPage />);
+ const viewer = await openViewer();
+
+ expect(within(viewer).getByText(/can't be previewed/i)).toBeDefined();
+ expect(viewer.querySelector("pre")).toBeNull();
+ expect(downloadRequests).toEqual([]);
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/helpers.test.ts
index 882ab732b7..f165269c75 100644
--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/helpers.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/helpers.test.ts
@@ -227,6 +227,43 @@ describe("getFileTypeLabel + getFileTypeIcon", () => {
expect(typeof Icon).toBe("object");
}
});
+
+ test.each([
+ [
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",
+ undefined,
+ "Presentation",
+ ],
+ ["application/vnd.ms-powerpoint", undefined, "Presentation"],
+ [
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ undefined,
+ "Document",
+ ],
+ ["application/msword", undefined, "Document"],
+ ["text/plain", "deck.pptx", "Presentation"],
+ ["application/octet-stream", "deck.ppt", "Presentation"],
+ [undefined, "report.docx", "Document"],
+ ["application/octet-stream", "report.doc", "Document"],
+ ["application/octet-stream", "sheet.xlsx", "Spreadsheet"],
+ [undefined, "sheet.xls", "Spreadsheet"],
+ ])("getFileTypeLabel(%s, %s) === %s", (mime, name, expected) => {
+ expect(getFileTypeLabel(mime, name)).toBe(expected);
+ });
+
+ test("office files get their own icons, by MIME or by extension", () => {
+ const presentation = getFileTypeIcon(
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",
+ );
+ expect(getFileTypeIcon("text/plain", "deck.pptx")).toBe(presentation);
+ expect(getFileTypeIcon(undefined, "report.docx")).toBe(
+ getFileTypeIcon("text/plain"),
+ );
+ expect(getFileTypeIcon("application/octet-stream", "sheet.xlsx")).toBe(
+ getFileTypeIcon("text/csv"),
+ );
+ expect(presentation).not.toBe(getFileTypeIcon("application/octet-stream"));
+ });
});
describe("getPreviewKind", () => {
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/helpers.ts
index 224e70d4df..54d3726474 100644
--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/helpers.ts
@@ -5,6 +5,7 @@ import {
FileEmpty02Icon,
Image01Icon,
Pdf01Icon,
+ Presentation01Icon,
TableIcon,
Video01Icon,
} from "@hugeicons/core-free-icons";
@@ -160,12 +161,44 @@ export function isCodeFile(fileName: string | undefined): boolean {
return ext ? CODE_EXTENSIONS.has(ext[1]) : false;
}
+type OfficeDocKind = "presentation" | "document" | "spreadsheet";
+
+// Extension first: an office file stored with a wrong MIME (e.g. text/plain)
+// must still read as an office document.
+function getOfficeDocKind(
+ mimeType: string,
+ fileName: string,
+): OfficeDocKind | null {
+ if (/\.pptx?$/.test(fileName)) return "presentation";
+ if (/\.docx?$/.test(fileName)) return "document";
+ if (/\.xlsx?$/.test(fileName)) return "spreadsheet";
+ if (mimeType.includes("presentationml") || mimeType.includes("powerpoint"))
+ return "presentation";
+ if (mimeType.includes("wordprocessingml") || mimeType.includes("msword"))
+ return "document";
+ return null;
+}
+
+const OFFICE_LABEL: Record<OfficeDocKind, string> = {
+ presentation: "Presentation",
+ document: "Document",
+ spreadsheet: "Spreadsheet",
+};
+
+const OFFICE_ICON: Record<OfficeDocKind, IconSvgElement> = {
+ presentation: Presentation01Icon,
+ document: File02Icon,
+ spreadsheet: TableIcon,
+};
+
export function getFileTypeLabel(
mimeType: string | undefined,
fileName?: string,
): string {
if (isCodeFile(fileName)) return "Code";
const mt = (mimeType ?? "").toLowerCase();
+ const officeKind = getOfficeDocKind(mt, (fileName ?? "").toLowerCase());
+ if (officeKind) return OFFICE_LABEL[officeKind];
if (mt.startsWith("image/")) return "Image";
if (mt.startsWith("video/")) return "Video";
if (mt.startsWith("audio/")) return "Audio";
@@ -185,6 +218,8 @@ export function getFileTypeIcon(
): IconSvgElement {
if (isCodeFile(fileName)) return CodeIcon;
const mt = (mimeType ?? "").toLowerCase();
+ const officeKind = getOfficeDocKind(mt, (fileName ?? "").toLowerCase());
+ if (officeKind) return OFFICE_ICON[officeKind];
if (mt.startsWith("image/")) return Image01Icon;
if (mt.startsWith("video/")) return Video01Icon;
if (mt.includes("pdf")) return Pdf01Icon;
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/FileViewerModal/FileViewerModal.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/FileViewerModal/FileViewerModal.tsx
index 3ae0d6c3a1..372314f1d7 100644
--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/FileViewerModal/FileViewerModal.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/FileViewerModal/FileViewerModal.tsx
@@ -8,9 +8,15 @@ import { Button } from "@/components/atoms/Button/Button";
import { Dialog } from "@/components/molecules/Dialog/Dialog";
import { useToast } from "@/components/molecules/Toast/use-toast";
import { useState } from "react";
-import { downloadFileBlob, getFileDownloadUrl } from "../ArtifactsList/helpers";
+import {
+ downloadFileBlob,
+ getFileDownloadUrl,
+ getPreviewKind,
+} from "../ArtifactsList/helpers";
import { CodeIcon, Download04Icon, EyeIcon } from "@hugeicons/core-free-icons";
import { Icon } from "@/components/atoms/Icon/Icon";
+import { DownloadOnly } from "./components/DownloadOnly";
+import { OfficePreview } from "./components/OfficePreview";
interface Props {
file: WorkspaceFileItem | null;
@@ -36,7 +42,13 @@ export function FileViewerModal({ file, onClose }: Props) {
file.name,
file.size_bytes,
);
+ const previewKind = getPreviewKind(
+ file.mime_type,
+ file.size_bytes,
+ file.name,
+ );
const artifact = toArtifactRef(file);
+ const downloadUrl = getFileDownloadUrl(file.id);
return (
<Dialog
@@ -59,17 +71,16 @@ export function FileViewerModal({ file, onClose }: Props) {
>
<Dialog.Content>
<div className="flex h-full min-h-0 flex-col" data-testid="file-viewer">
- {classification.openable ? (
+ {previewKind === "office" ? (
+ <OfficePreview file={file} downloadUrl={downloadUrl} />
+ ) : classification.openable ? (
<ArtifactContent
artifact={artifact}
isSourceView={isSourceView}
classification={classification}
/>
) : (
- <DownloadOnly
- name={file.name}
- downloadUrl={getFileDownloadUrl(file.id)}
- />
+ <DownloadOnly name={file.name} downloadUrl={downloadUrl} />
)}
</div>
</Dialog.Content>
@@ -150,30 +161,6 @@ function Header({
);
}
-function DownloadOnly({
- name,
- downloadUrl,
-}: {
- name: string;
- downloadUrl: string;
-}) {
- return (
- <div className="flex h-full flex-col items-center justify-center gap-3 text-center">
- <p className="text-sm text-zinc-500">
- This file type can&apos;t be previewed.
- </p>
- <a
- href={downloadUrl}
- download={name}
- className="inline-flex items-center gap-1.5 rounded-md border border-zinc-200 bg-white px-3 py-1.5 text-sm font-medium text-zinc-700 transition-colors hover:bg-zinc-50"
- >
- <Icon icon={Download04Icon} size={16} />
- Download
- </a>
- </div>
- );
-}
-
function toArtifactRef(file: WorkspaceFileItem): ArtifactRef {
return {
id: file.id,
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/FileViewerModal/components/DownloadOnly.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/FileViewerModal/components/DownloadOnly.tsx
new file mode 100644
index 0000000000..d5a9afe1a0
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/FileViewerModal/components/DownloadOnly.tsx
@@ -0,0 +1,28 @@
+import { Icon } from "@/components/atoms/Icon/Icon";
+import { Download04Icon } from "@hugeicons/core-free-icons";
+
+interface Props {
+ name: string;
+ downloadUrl: string;
+ message?: string;
+}
+
+export function DownloadOnly({
+ name,
+ downloadUrl,
+ message = "This file type can't be previewed.",
+}: Props) {
+ return (
+ <div className="flex h-full flex-col items-center justify-center gap-3 text-center">
+ <p className="text-sm text-zinc-500">{message}</p>
+ <a
+ href={downloadUrl}
+ download={name}
+ className="inline-flex items-center gap-1.5 rounded-md border border-zinc-200 bg-white px-3 py-1.5 text-sm font-medium text-zinc-700 transition-colors hover:bg-zinc-50"
+ >
+ <Icon icon={Download04Icon} size={16} />
+ Download
+ </a>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/FileViewerModal/components/OfficePreview.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/FileViewerModal/components/OfficePreview.tsx
new file mode 100644
index 0000000000..4878e7ec59
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/FileViewerModal/components/OfficePreview.tsx
@@ -0,0 +1,62 @@
+"use client";
+
+import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";
+import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";
+import { cn } from "@/lib/utils";
+import { useState } from "react";
+import { PREVIEW_IMAGE_WIDTH } from "../../ArtifactsList/ArtifactsTable/FilePreviewCard";
+import {
+ getFilePreviewUrl,
+ getFileTypeLabel,
+} from "../../ArtifactsList/helpers";
+import { DownloadOnly } from "./DownloadOnly";
+
+interface Props {
+ file: WorkspaceFileItem;
+ downloadUrl: string;
+}
+
+// The preview endpoint returns the thumbnail embedded in the office file
+// (first slide or page), and 415s when there is none.
+export function OfficePreview({ file, downloadUrl }: Props) {
+ const [isLoaded, setIsLoaded] = useState(false);
+ const [hasError, setHasError] = useState(false);
+
+ if (hasError) {
+ return <DownloadOnly name={file.name} downloadUrl={downloadUrl} />;
+ }
+
+ const isPresentation =
+ getFileTypeLabel(file.mime_type, file.name) === "Presentation";
+
+ return (
+ <div className="flex h-full min-h-0 flex-col gap-4">
+ <div className="relative flex min-h-0 flex-1 items-center justify-center">
+ {isLoaded ? null : <Skeleton className="absolute inset-0" />}
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img
+ src={getFilePreviewUrl(file.id, { width: PREVIEW_IMAGE_WIDTH })}
+ alt={file.name}
+ className={cn(
+ "max-h-full max-w-full object-contain",
+ isLoaded ? "opacity-100" : "opacity-0",
+ )}
+ onLoad={() => setIsLoaded(true)}
+ onError={() => setHasError(true)}
+ data-testid="file-viewer-office-preview"
+ />
+ </div>
+ <div className="shrink-0">
+ <DownloadOnly
+ name={file.name}
+ downloadUrl={downloadUrl}
+ message={
+ isPresentation
+ ? "Showing the first slide. Download to open the full presentation."
+ : "Showing the first page. Download to open the full file."
+ }
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/__tests__/helpers.test.ts
index 4349b79a46..77ef2a2f09 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/__tests__/helpers.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/__tests__/helpers.test.ts
@@ -524,8 +524,61 @@ describe("classifyArtifact", () => {
}
});
+ // ── Office documents ────────────────────────────────────────────
+ // Office files are zip archives. Fetching one as text dumps the raw bytes
+ // into a <pre> (SECRT-2437), so the extension wins over any text-like MIME.
+
+ it.each([
+ "deck.pptx",
+ "deck.ppt",
+ "report.docx",
+ "report.doc",
+ "sheet.xlsx",
+ "sheet.xls",
+ "talk.key",
+ "slides.odp",
+ "notes.odt",
+ "table.ods",
+ ])("keeps %s download-only even with a text MIME", (name) => {
+ for (const mime of [null, "text/plain", "application/octet-stream"]) {
+ const c = classifyArtifact(mime, name);
+ expect(c.type).toBe("download-only");
+ expect(c.openable).toBe(false);
+ }
+ });
+
+ it.each([
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+ "application/vnd.ms-powerpoint",
+ "application/msword",
+ "application/vnd.ms-excel",
+ ])("treats office MIME %s as download-only without an extension", (mime) => {
+ const c = classifyArtifact(mime, "noext");
+ expect(c.type).toBe("download-only");
+ expect(c.openable).toBe(false);
+ });
+
+ it.each([
+ ["report.txt", "application/msword"],
+ [
+ "notes.md",
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ ],
+ ["data.json", "application/vnd.ms-excel"],
+ [
+ "slides.html",
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",
+ ],
+ ])("keeps %s download-only when its MIME is %s", (name, mime) => {
+ const c = classifyArtifact(mime, name);
+ expect(c.type).toBe("download-only");
+ expect(c.openable).toBe(false);
+ });
+
it("does not open certificate/key files", () => {
- // .pem and .key have no extension mapping and null MIME → download-only
+ // .pem has no extension mapping; .key maps to download-only (Keynote)
for (const file of ["cert.pem", "server.key", "ca.crt", "id.p12"]) {
expect(classifyArtifact(null, file).openable).toBe(false);
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/helpers.ts
index 796d950459..20e7139327 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/helpers.ts
@@ -130,6 +130,17 @@ const EXT_KIND: Record<string, string> = {
".webm": "video",
".m4v": "video",
".pdf": "pdf",
+ // Office documents are zip/binary containers: never fetch them as text.
+ ".pptx": "download-only",
+ ".ppt": "download-only",
+ ".docx": "download-only",
+ ".doc": "download-only",
+ ".xlsx": "download-only",
+ ".xls": "download-only",
+ ".key": "download-only",
+ ".odp": "download-only",
+ ".odt": "download-only",
+ ".ods": "download-only",
".csv": "csv",
".tsv": "csv",
".html": "html",
@@ -228,6 +239,17 @@ const BINARY_MIMES = new Set([
"application/vnd.microsoft.portable-executable",
]);
+// Office documents are zip/binary containers. Their MIME wins over an openable
+// extension, just as an office extension wins over a text MIME.
+const OFFICE_MIMES = new Set([
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+ "application/vnd.ms-powerpoint",
+ "application/msword",
+ "application/vnd.ms-excel",
+]);
+
const PREVIEWABLE_IMAGE_MIMES = new Set([
"image/png",
"image/jpeg",
@@ -302,6 +324,9 @@ function classifyByTypeOnly(
mimeType: string | null,
filename?: string,
): ArtifactClassification {
+ const mime = (mimeType ?? "").toLowerCase();
+ if (OFFICE_MIMES.has(mime)) return KIND["download-only"];
+
const basename = getBasename(filename);
const exactKind = EXACT_FILENAME_KIND[basename];
if (exactKind) return KIND[exactKind];
@@ -316,7 +341,6 @@ function classifyByTypeOnly(
if (extKind) return KIND[extKind];
// MIME fallbacks.
- const mime = (mimeType ?? "").toLowerCase();
if (PREVIEWABLE_IMAGE_MIMES.has(mime)) return KIND.image;
if (PREVIEWABLE_VIDEO_MIMES.has(mime)) return KIND.video;
const mimeKind = MIME_KIND[mime];