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(frontend/copilot): artifact panel fixes (SECRT-2254/2223/2220/2255/2224/2256/2221) (#12856)

Nicholas Tindle6924cf90a562
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/ArtifactContent.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/ArtifactContent.tsx
index 506cbc3b60..7a65188b86 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/ArtifactContent.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/ArtifactContent.tsx
@@ -6,9 +6,11 @@ import { Suspense, useState } from "react";
import { Skeleton } from "@/components/ui/skeleton";
import type { ArtifactRef } from "../../../store";
import type { ArtifactClassification } from "../helpers";
+import { ArtifactErrorBoundary } from "./ArtifactErrorBoundary";
import { ArtifactReactPreview } from "./ArtifactReactPreview";
import { ArtifactSkeleton } from "./ArtifactSkeleton";
import {
+ FRAGMENT_LINK_INTERCEPTOR_SCRIPT,
TAILWIND_CDN_URL,
wrapWithHeadInjection,
} from "@/lib/iframe-sandbox-csp";
@@ -53,20 +55,35 @@ function ArtifactContentLoader({
return (
<div ref={scrollRef} className="flex-1 overflow-y-auto">
- <ArtifactRenderer
- artifact={artifact}
- content={content}
- pdfUrl={pdfUrl}
- isSourceView={isSourceView}
- classification={classification}
- />
+ <ArtifactErrorBoundary
+ artifactID={artifact.id}
+ artifactTitle={artifact.title}
+ artifactType={classification.type}
+ >
+ <ArtifactRenderer
+ artifact={artifact}
+ content={content}
+ pdfUrl={pdfUrl}
+ isSourceView={isSourceView}
+ classification={classification}
+ />
+ </ArtifactErrorBoundary>
</div>
);
}
+function withCacheBust(src: string, nonce: number): string {
+ if (nonce === 0) return src;
+ const sep = src.includes("?") ? "&" : "?";
+ return `${src}${sep}_retry=${nonce}`;
+}
+
function ArtifactImage({ src, alt }: { src: string; alt: string }) {
const [loaded, setLoaded] = useState(false);
const [error, setError] = useState(false);
+ // Incremented on every Try Again so the URL changes and the browser
+ // can't reuse a negative-cached response (SECRT-2221).
+ const [retryNonce, setRetryNonce] = useState(0);
if (error) {
return (
@@ -80,6 +97,7 @@ function ArtifactImage({ src, alt }: { src: string; alt: string }) {
onClick={() => {
setError(false);
setLoaded(false);
+ setRetryNonce((n) => n + 1);
}}
className="rounded-md border border-zinc-200 bg-white px-3 py-1.5 text-xs font-medium text-zinc-700 shadow-sm transition-colors hover:bg-zinc-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-violet-400"
>
@@ -96,7 +114,7 @@ function ArtifactImage({ src, alt }: { src: string; alt: string }) {
)}
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
- src={src}
+ src={withCacheBust(src, retryNonce)}
alt={alt}
className={`max-h-full max-w-full object-contain transition-opacity ${loaded ? "opacity-100" : "opacity-0"}`}
onLoad={() => setLoaded(true)}
@@ -109,6 +127,7 @@ function ArtifactImage({ src, alt }: { src: string; alt: string }) {
function ArtifactVideo({ src }: { src: string }) {
const [loaded, setLoaded] = useState(false);
const [error, setError] = useState(false);
+ const [retryNonce, setRetryNonce] = useState(0);
if (error) {
return (
@@ -122,6 +141,7 @@ function ArtifactVideo({ src }: { src: string }) {
onClick={() => {
setError(false);
setLoaded(false);
+ setRetryNonce((n) => n + 1);
}}
className="rounded-md border border-zinc-200 bg-white px-3 py-1.5 text-xs font-medium text-zinc-700 shadow-sm transition-colors hover:bg-zinc-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-violet-400"
>
@@ -137,7 +157,7 @@ function ArtifactVideo({ src }: { src: string }) {
<Skeleton className="absolute inset-4 h-[calc(100%-2rem)] w-[calc(100%-2rem)] rounded-md" />
)}
<video
- src={src}
+ src={withCacheBust(src, retryNonce)}
controls
preload="metadata"
className={`max-h-full max-w-full rounded-md transition-opacity ${loaded ? "opacity-100" : "opacity-0"}`}
@@ -200,7 +220,10 @@ function ArtifactRenderer({
if (classification.type === "html") {
// Inject Tailwind CDN — no CSP (see iframe-sandbox-csp.ts for why)
const tailwindScript = `<script src="${TAILWIND_CDN_URL}"></script>`;
- const wrapped = wrapWithHeadInjection(content, tailwindScript);
+ const wrapped = wrapWithHeadInjection(
+ content,
+ tailwindScript + FRAGMENT_LINK_INTERCEPTOR_SCRIPT,
+ );
return (
<iframe
sandbox="allow-scripts"
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/ArtifactDragHandle.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/ArtifactDragHandle.tsx
index 0f30ce2078..f169bec9e4 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/ArtifactDragHandle.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/ArtifactDragHandle.tsx
@@ -27,6 +27,10 @@ export function ArtifactDragHandle({
minWidthRef.current = minWidth;
maxWidthPercentRef.current = maxWidthPercent;
+ // Track the captured pointer id so pointerup can release it even after
+ // React re-renders.
+ const pointerIdRef = useRef<number | null>(null);
+
// Attach document listeners only while dragging, and always tear them down
// on unmount — otherwise closing the panel mid-drag leaves listeners bound
// to a handler that calls setState on the unmounted component.
@@ -57,7 +61,7 @@ export function ArtifactDragHandle({
};
}, [isDragging]);
- function handlePointerDown(e: React.PointerEvent) {
+ function handlePointerDown(e: React.PointerEvent<HTMLDivElement>) {
e.preventDefault();
startXRef.current = e.clientX;
@@ -67,9 +71,31 @@ export function ArtifactDragHandle({
) as HTMLElement | null;
startWidthRef.current = panel?.offsetWidth ?? DEFAULT_PANEL_WIDTH;
+ // Capture the pointer so pointermove/pointerup still reach us when the
+ // cursor drifts over sandboxed artifact iframes. Without this, the iframe
+ // eats the events and the drag gets stuck (SECRT-2256).
+ try {
+ e.currentTarget.setPointerCapture(e.pointerId);
+ pointerIdRef.current = e.pointerId;
+ } catch {
+ // Non-supporting environments (older test DOMs) — safe to ignore.
+ }
+
setIsDragging(true);
}
+ function handlePointerUp(e: React.PointerEvent<HTMLDivElement>) {
+ if (pointerIdRef.current != null) {
+ try {
+ e.currentTarget.releasePointerCapture(pointerIdRef.current);
+ } catch {
+ // Capture may already be released.
+ }
+ pointerIdRef.current = null;
+ }
+ setIsDragging(false);
+ }
+
return (
// 12px transparent hit target with the visible 1px line centered inside
// (WCAG-compliant, matches ~8-12px conventions of other resizable panels).
@@ -81,6 +107,9 @@ export function ArtifactDragHandle({
"group absolute -left-1.5 top-0 z-10 flex h-full w-3 cursor-col-resize items-stretch justify-center",
)}
onPointerDown={handlePointerDown}
+ onPointerUp={handlePointerUp}
+ onPointerCancel={handlePointerUp}
+ style={{ touchAction: "none" }}
>
<div
className={cn(
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/ArtifactErrorBoundary.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/ArtifactErrorBoundary.tsx
new file mode 100644
index 0000000000..b2377fb15b
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/ArtifactErrorBoundary.tsx
@@ -0,0 +1,100 @@
+"use client";
+
+import * as Sentry from "@sentry/nextjs";
+import { Component, type ErrorInfo, type ReactNode } from "react";
+
+interface Props {
+ children: ReactNode;
+ artifactID: string;
+ artifactTitle: string;
+ artifactType: string;
+}
+
+interface State {
+ error: Error | null;
+}
+
+export class ArtifactErrorBoundary extends Component<Props, State> {
+ state: State = { error: null };
+
+ static getDerivedStateFromError(error: Error): State {
+ return { error };
+ }
+
+ componentDidCatch(error: Error, errorInfo: ErrorInfo) {
+ Sentry.captureException(error, {
+ contexts: {
+ react: { componentStack: errorInfo.componentStack },
+ },
+ tags: { errorBoundary: "true", context: "copilot-artifact" },
+ extra: {
+ artifactID: this.props.artifactID,
+ artifactTitle: this.props.artifactTitle,
+ artifactType: this.props.artifactType,
+ },
+ });
+ }
+
+ componentDidUpdate(prevProps: Props) {
+ if (
+ this.state.error &&
+ (prevProps.artifactID !== this.props.artifactID ||
+ prevProps.artifactTitle !== this.props.artifactTitle ||
+ prevProps.artifactType !== this.props.artifactType)
+ ) {
+ this.setState({ error: null });
+ }
+ }
+
+ handleCopy = () => {
+ const { error } = this.state;
+ if (!error) return;
+ const details = [
+ `Artifact: ${this.props.artifactTitle}`,
+ `ID: ${this.props.artifactID}`,
+ `Type: ${this.props.artifactType}`,
+ `Error: ${error.message}`,
+ error.stack ? `Stack:\n${error.stack}` : "",
+ ]
+ .filter(Boolean)
+ .join("\n");
+ navigator.clipboard?.writeText(details).catch(() => {});
+ };
+
+ render() {
+ const { error } = this.state;
+ if (!error) return this.props.children;
+
+ const message = error.message || "Unknown rendering error";
+
+ return (
+ <div
+ role="alert"
+ className="flex h-full flex-col items-center justify-center gap-3 p-8 text-center"
+ >
+ <p className="text-sm font-medium text-zinc-700">
+ This artifact couldn&apos;t be rendered
+ </p>
+ <p className="max-w-md break-words text-xs text-zinc-500">
+ Something in{" "}
+ <span className="font-mono">{this.props.artifactTitle}</span> threw an
+ error while rendering. The chat and sidebar are still working.
+ </p>
+ <pre className="max-h-32 max-w-md overflow-auto whitespace-pre-wrap break-words rounded-md bg-zinc-100 px-3 py-2 text-left text-xs text-zinc-700">
+ {message}
+ </pre>
+ <button
+ type="button"
+ onClick={this.handleCopy}
+ className="rounded-md border border-zinc-200 bg-white px-3 py-1.5 text-xs font-medium text-zinc-700 shadow-sm transition-colors hover:bg-zinc-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-violet-400"
+ >
+ Copy error details
+ </button>
+ <p className="max-w-md text-xs text-zinc-400">
+ Paste this into the chat so the agent can regenerate a working
+ version.
+ </p>
+ </div>
+ );
+ }
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/__tests__/ArtifactContent.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/__tests__/ArtifactContent.test.tsx
index e4b287fa9a..6a4347cbb0 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/__tests__/ArtifactContent.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/__tests__/ArtifactContent.test.tsx
@@ -199,6 +199,82 @@ describe("ArtifactContent", () => {
});
});
+ // SECRT-2221 integration: the classification-level fix (hi-res PNGs stop
+ // being size-gated) only matters if the end-to-end rendering pipeline
+ // actually reaches the <img> path. Pass in the real classifyArtifact
+ // result for a 25 MB .png and assert the panel renders an img element
+ // rather than routing to the download-only surface.
+ it("renders a 25 MB PNG through the <img> path, not download-only (SECRT-2221)", () => {
+ const artifact = makeArtifact({
+ id: "hires-png-001",
+ title: "poster.png",
+ mimeType: "image/png",
+ sourceUrl: "/api/proxy/api/workspace/files/hires-png-001/download",
+ sizeBytes: 25 * 1024 * 1024,
+ });
+ const classification = classifyArtifact(
+ artifact.mimeType,
+ artifact.title,
+ artifact.sizeBytes,
+ );
+ expect(classification.type).toBe("image");
+ expect(classification.openable).toBe(true);
+
+ const { container } = render(
+ <ArtifactContent
+ artifact={artifact}
+ isSourceView={false}
+ classification={classification}
+ />,
+ );
+
+ const img = container.querySelector("img");
+ expect(img).toBeTruthy();
+ expect(img?.getAttribute("src")).toBe(artifact.sourceUrl);
+ });
+
+ // SECRT-2221: image retry appends a cache-busting query so the browser
+ // can't reuse a previously-failed response. Without this, a transient
+ // 5xx that gets negative-cached keeps showing "Failed to load image" no
+ // matter how many times the user clicks Try again.
+ it("image retry appends a cache-busting query so the browser re-fetches (SECRT-2221)", async () => {
+ const artifact = makeArtifact({
+ id: "img-cachebust",
+ title: "hires.png",
+ mimeType: "image/png",
+ sourceUrl: "/api/proxy/api/workspace/files/img-cachebust/download",
+ });
+ const classification = makeClassification({ type: "image" });
+
+ const { container } = render(
+ <ArtifactContent
+ artifact={artifact}
+ isSourceView={false}
+ classification={classification}
+ />,
+ );
+
+ const firstImg = container.querySelector("img");
+ const firstSrc = firstImg?.getAttribute("src");
+ expect(firstSrc).toBe(artifact.sourceUrl);
+
+ fireEvent.error(firstImg!);
+ await waitFor(() => {
+ expect(screen.queryByText("Failed to load image")).toBeTruthy();
+ });
+ fireEvent.click(screen.getByRole("button", { name: /try again/i }));
+
+ await waitFor(() => {
+ const nextImg = container.querySelector("img");
+ const nextSrc = nextImg?.getAttribute("src") ?? "";
+ expect(nextSrc).not.toBe(firstSrc);
+ expect(nextSrc.startsWith(artifact.sourceUrl)).toBe(true);
+ // Assert the specific cache-bust contract, not just that the URL
+ // changed — guards against accidental rewrites that drop the key.
+ expect(nextSrc).toContain("_retry=");
+ });
+ });
+
// ── Video ─────────────────────────────────────────────────────────
it("renders video artifact with video tag and controls", () => {
@@ -379,6 +455,117 @@ describe("ArtifactContent", () => {
expect(retryButtons.length).toBeGreaterThan(0);
});
+ // SECRT-2224: "try again doesn't do anything". The retry itself works — the
+ // user's complaint is that there's no visible feedback when the same error
+ // returns (e.g. a 404 for a deleted file). Clicking Try Again must flip the
+ // UI into the loading skeleton immediately so the user can tell their click
+ // registered, instead of the error UI re-flashing in place.
+ it("clicking Try Again shows the loading skeleton before the next fetch settles (SECRT-2224)", async () => {
+ let resolveSecond: (value: unknown) => void = () => {};
+ let callCount = 0;
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockImplementation(() => {
+ callCount++;
+ if (callCount === 1) {
+ return Promise.resolve({
+ ok: false,
+ status: 404,
+ text: () => Promise.resolve("Not found"),
+ });
+ }
+ return new Promise((resolve) => {
+ resolveSecond = resolve;
+ });
+ }),
+ );
+
+ const artifact = makeArtifact({
+ id: "retry-skeleton-001",
+ title: "flaky.html",
+ mimeType: "text/html",
+ });
+ const classification = makeClassification({ type: "html" });
+
+ const { container } = render(
+ <ArtifactContent
+ artifact={artifact}
+ isSourceView={false}
+ classification={classification}
+ />,
+ );
+
+ await screen.findByText("Failed to load content");
+ fireEvent.click(screen.getByRole("button", { name: /try again/i }));
+
+ // Before the second fetch resolves, the error must be gone and a skeleton
+ // visible (animate-pulse is the Skeleton component's signature class).
+ await waitFor(() => {
+ expect(screen.queryByText("Failed to load content")).toBeNull();
+ expect(container.querySelector('[class*="animate-pulse"]')).toBeTruthy();
+ });
+
+ // Let the second fetch complete and wait for the recovered render so
+ // pending React updates can't leak into the next test.
+ resolveSecond({
+ ok: true,
+ text: () => Promise.resolve("<html><body>ok</body></html>"),
+ });
+ await screen.findByTitle("flaky.html");
+ });
+
+ // SECRT-2224 end-to-end: Try Again actually recovers when the next fetch
+ // succeeds. Covers the full click → re-fetch → iframe-render loop.
+ it("clicking Try Again re-fetches and renders recovered HTML content (SECRT-2224)", async () => {
+ let callCount = 0;
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockImplementation(() => {
+ callCount++;
+ if (callCount === 1) {
+ return Promise.resolve({
+ ok: false,
+ status: 404,
+ text: () => Promise.resolve("Not found"),
+ });
+ }
+ return Promise.resolve({
+ ok: true,
+ text: () =>
+ Promise.resolve(
+ "<html><body><h1 id='ok'>recovered</h1></body></html>",
+ ),
+ });
+ }),
+ );
+
+ const artifact = makeArtifact({
+ id: "retry-recover-001",
+ title: "flaky.html",
+ mimeType: "text/html",
+ });
+ const classification = makeClassification({ type: "html" });
+
+ const { container } = render(
+ <ArtifactContent
+ artifact={artifact}
+ isSourceView={false}
+ classification={classification}
+ />,
+ );
+
+ await screen.findByText("Failed to load content");
+ fireEvent.click(screen.getByRole("button", { name: /try again/i }));
+
+ await waitFor(() => {
+ const iframe = container.querySelector("iframe");
+ expect(iframe).toBeTruthy();
+ expect(iframe?.getAttribute("srcdoc")).toContain("recovered");
+ });
+ expect(screen.queryByText("Failed to load content")).toBeNull();
+ expect(callCount).toBeGreaterThanOrEqual(2);
+ });
+
// ── HTML ──────────────────────────────────────────────────────────
it("renders HTML content in sandboxed iframe", async () => {
@@ -412,6 +599,41 @@ describe("ArtifactContent", () => {
expect(iframe?.getAttribute("sandbox")).toBe("allow-scripts");
});
+ it("injects the fragment-link interceptor into HTML artifact iframes (regression)", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({
+ ok: true,
+ text: () =>
+ Promise.resolve(
+ '<html><head></head><body><a href="#x">x</a><div id="x">x</div></body></html>',
+ ),
+ }),
+ );
+
+ const { container } = render(
+ <ArtifactContent
+ artifact={makeArtifact({
+ id: "html-frag",
+ title: "page.html",
+ mimeType: "text/html",
+ })}
+ isSourceView={false}
+ classification={makeClassification({ type: "html" })}
+ />,
+ );
+
+ await screen.findByTitle("page.html");
+ const srcdoc = container.querySelector("iframe")?.getAttribute("srcdoc");
+ expect(srcdoc).toBeTruthy();
+ // Markers unique to FRAGMENT_LINK_INTERCEPTOR_SCRIPT — if any of these
+ // disappear, the interceptor is no longer being injected and fragment
+ // links will navigate the parent URL again.
+ expect(srcdoc).toContain("__fragmentLinkInterceptor");
+ expect(srcdoc).toContain('a[href^="#"]');
+ expect(srcdoc).toContain("scrollIntoView");
+ });
+
// ── Source view ───────────────────────────────────────────────────
it("renders source view as pre tag", async () => {
@@ -923,6 +1145,239 @@ describe("ArtifactContent", () => {
},
);
+ // ── Error boundary ────────────────────────────────────────────────
+
+ it("shows a visible error instead of crashing when the renderer throws", async () => {
+ const consoleErr = vi.spyOn(console, "error").mockImplementation(() => {});
+ const originalImpl = vi
+ .mocked(ArtifactReactPreview)
+ .getMockImplementation();
+ vi.mocked(ArtifactReactPreview).mockImplementation(() => {
+ throw new Error("boom in renderer");
+ });
+
+ try {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({
+ ok: true,
+ text: () => Promise.resolve("source"),
+ }),
+ );
+
+ const artifact = makeArtifact({
+ id: "crash-001",
+ title: "broken.tsx",
+ mimeType: "text/tsx",
+ });
+ const classification = makeClassification({ type: "react" });
+
+ render(
+ <ArtifactContent
+ artifact={artifact}
+ isSourceView={false}
+ classification={classification}
+ />,
+ );
+
+ expect(
+ await screen.findByText(/This artifact couldn't be rendered/i),
+ ).toBeTruthy();
+ expect(screen.getByText(/boom in renderer/)).toBeTruthy();
+ expect(
+ screen.getByRole("button", { name: /copy error details/i }),
+ ).toBeTruthy();
+ } finally {
+ if (originalImpl) {
+ vi.mocked(ArtifactReactPreview).mockImplementation(originalImpl);
+ }
+ consoleErr.mockRestore();
+ }
+ });
+
+ it("copies artifact title, type, and error to the clipboard", async () => {
+ const consoleErr = vi.spyOn(console, "error").mockImplementation(() => {});
+ const writeText = vi.fn().mockResolvedValue(undefined);
+ Object.defineProperty(navigator, "clipboard", {
+ value: { writeText },
+ writable: true,
+ configurable: true,
+ });
+
+ const originalImpl = vi
+ .mocked(ArtifactReactPreview)
+ .getMockImplementation();
+ vi.mocked(ArtifactReactPreview).mockImplementation(() => {
+ throw new Error("jsx parse failed at line 42");
+ });
+
+ try {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({
+ ok: true,
+ text: () => Promise.resolve("source"),
+ }),
+ );
+
+ render(
+ <ArtifactContent
+ artifact={makeArtifact({
+ id: "crash-002",
+ title: "report.tsx",
+ mimeType: "text/tsx",
+ })}
+ isSourceView={false}
+ classification={makeClassification({ type: "react" })}
+ />,
+ );
+
+ fireEvent.click(
+ await screen.findByRole("button", { name: /copy error details/i }),
+ );
+
+ await waitFor(() => {
+ expect(writeText).toHaveBeenCalled();
+ });
+ const payload = writeText.mock.calls[0]![0] as string;
+ expect(payload).toContain("report.tsx");
+ expect(payload).toContain("crash-002");
+ expect(payload).toContain("react");
+ expect(payload).toContain("jsx parse failed at line 42");
+ } finally {
+ if (originalImpl) {
+ vi.mocked(ArtifactReactPreview).mockImplementation(originalImpl);
+ }
+ consoleErr.mockRestore();
+ }
+ });
+
+ // Regression: two different artifacts can share the same title+type (e.g.
+ // two "App.tsx" files from different sessions). The boundary must reset
+ // when artifact.id changes, not only on title/type changes, otherwise
+ // opening a second artifact after a crash stays stuck on the first's error.
+ it("resets the error fallback when the artifact id changes (same title/type)", async () => {
+ const consoleErr = vi.spyOn(console, "error").mockImplementation(() => {});
+ const originalImpl = vi
+ .mocked(ArtifactReactPreview)
+ .getMockImplementation();
+
+ // First render: throws.
+ vi.mocked(ArtifactReactPreview).mockImplementation(() => {
+ throw new Error("first render boom");
+ });
+
+ try {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({
+ ok: true,
+ text: () => Promise.resolve("source"),
+ }),
+ );
+ const classification = makeClassification({ type: "react" });
+
+ const { rerender } = render(
+ <ArtifactContent
+ artifact={makeArtifact({
+ id: "id-one",
+ title: "App.tsx",
+ mimeType: "text/tsx",
+ })}
+ isSourceView={false}
+ classification={classification}
+ />,
+ );
+
+ await screen.findByText(/This artifact couldn't be rendered/i);
+
+ // Swap in a working renderer and a different artifact id (same title/type).
+ if (originalImpl) {
+ vi.mocked(ArtifactReactPreview).mockImplementation(originalImpl);
+ }
+
+ rerender(
+ <ArtifactContent
+ artifact={makeArtifact({
+ id: "id-two",
+ title: "App.tsx",
+ mimeType: "text/tsx",
+ })}
+ isSourceView={false}
+ classification={classification}
+ />,
+ );
+
+ await waitFor(() => {
+ expect(
+ screen.queryByText(/This artifact couldn't be rendered/i),
+ ).toBeNull();
+ expect(screen.getByTestId("react-preview")).toBeTruthy();
+ });
+ } finally {
+ if (originalImpl) {
+ vi.mocked(ArtifactReactPreview).mockImplementation(originalImpl);
+ }
+ consoleErr.mockRestore();
+ }
+ });
+
+ it("renders the user-reported plotly HTML artifact into a sandboxed iframe", async () => {
+ const html = `<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8">
+<title>AutoGPT Beta Launch Interactive Report</title>
+<script src="https://cdn.plot.ly/plotly-2.27.0.min.js"></script>
+<style>
+ :root { --bg: #f8f9fa; --primary: #6c5ce7; }
+ * { margin: 0; padding: 0; box-sizing: border-box; }
+ body { font-family: 'Segoe UI', system-ui, sans-serif; }
+</style>
+</head>
+<body>
+<header><h1>\u{1F4CA} AutoGPT Beta Launch Interactive Report</h1></header>
+<div class="chart-container" id="globalActivationChart"></div>
+<script>
+ function showTab(tabId, groupId) {
+ const group = document.getElementById(groupId);
+ group.querySelectorAll('.tab-content').forEach(t => t.classList.remove('active'));
+ document.getElementById(tabId).classList.add('active');
+ }
+ Plotly.newPlot('globalActivationChart', [{ type: 'pie', values: [1, 2] }], {});
+</script>
+</body>
+</html>`;
+
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({
+ ok: true,
+ text: () => Promise.resolve(html),
+ }),
+ );
+
+ const artifact = makeArtifact({
+ id: "html-big-report",
+ title: "report.html",
+ mimeType: "text/html",
+ });
+
+ const { container } = render(
+ <ArtifactContent
+ artifact={artifact}
+ isSourceView={false}
+ classification={makeClassification({ type: "html" })}
+ />,
+ );
+
+ await screen.findByTitle("report.html");
+ const iframe = container.querySelector("iframe");
+ expect(iframe).toBeTruthy();
+ expect(iframe?.getAttribute("sandbox")).toBe("allow-scripts");
+ expect(screen.queryByText(/couldn't be rendered/i)).toBeNull();
+ });
+
it("falls back to pre tag when no renderer matches", async () => {
const { globalRegistry } = await import(
"@/components/contextual/OutputRenderers"
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/__tests__/ArtifactDragHandle.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/__tests__/ArtifactDragHandle.test.tsx
new file mode 100644
index 0000000000..53706fc209
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/__tests__/ArtifactDragHandle.test.tsx
@@ -0,0 +1,181 @@
+import { cleanup, fireEvent, render } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { ArtifactDragHandle } from "../ArtifactDragHandle";
+
+function renderHandle(onWidthChange = vi.fn(), panelWidth = 600) {
+ const utils = render(
+ <div
+ data-artifact-panel
+ style={{
+ width: `${panelWidth}px`,
+ height: "400px",
+ position: "relative",
+ }}
+ >
+ <ArtifactDragHandle onWidthChange={onWidthChange} />
+ </div>,
+ );
+ const panel = utils.container.querySelector(
+ "[data-artifact-panel]",
+ ) as HTMLElement;
+ // happy-dom doesn't compute layout; stub offsetWidth so the handle reads
+ // the intended starting width.
+ Object.defineProperty(panel, "offsetWidth", {
+ value: panelWidth,
+ configurable: true,
+ });
+ const handle = utils.container.querySelector(
+ '[role="separator"]',
+ ) as HTMLElement;
+ return { handle, onWidthChange, ...utils };
+}
+
+// jsdom/happy-dom don't implement pointer capture by default — spy on the
+// prototype so vi.restoreAllMocks() can tear the spies down. We also seed
+// no-op base implementations where the prototype lacks them so vi.spyOn has
+// something to wrap. Both the seeded properties and window.innerWidth are
+// manual mutations that vi.restoreAllMocks() won't undo, so capture their
+// original descriptors and restore them in `restoreGlobals`.
+function installPointerCaptureStub() {
+ const proto = HTMLElement.prototype as unknown as {
+ setPointerCapture?: (id: number) => void;
+ releasePointerCapture?: (id: number) => void;
+ };
+ const originalSetPointerCapture = Object.getOwnPropertyDescriptor(
+ proto,
+ "setPointerCapture",
+ );
+ const originalReleasePointerCapture = Object.getOwnPropertyDescriptor(
+ proto,
+ "releasePointerCapture",
+ );
+
+ if (!proto.setPointerCapture) proto.setPointerCapture = () => {};
+ if (!proto.releasePointerCapture) proto.releasePointerCapture = () => {};
+ const setPointerCapture = vi
+ .spyOn(HTMLElement.prototype, "setPointerCapture")
+ .mockImplementation(() => {});
+ const releasePointerCapture = vi
+ .spyOn(HTMLElement.prototype, "releasePointerCapture")
+ .mockImplementation(() => {});
+
+ function restoreGlobals() {
+ if (originalSetPointerCapture) {
+ Object.defineProperty(
+ proto,
+ "setPointerCapture",
+ originalSetPointerCapture,
+ );
+ } else {
+ delete proto.setPointerCapture;
+ }
+ if (originalReleasePointerCapture) {
+ Object.defineProperty(
+ proto,
+ "releasePointerCapture",
+ originalReleasePointerCapture,
+ );
+ } else {
+ delete proto.releasePointerCapture;
+ }
+ }
+
+ return { setPointerCapture, releasePointerCapture, restoreGlobals };
+}
+
+describe("ArtifactDragHandle", () => {
+ let spies: ReturnType<typeof installPointerCaptureStub>;
+ const originalInnerWidth = Object.getOwnPropertyDescriptor(
+ window,
+ "innerWidth",
+ );
+
+ beforeEach(() => {
+ spies = installPointerCaptureStub();
+ Object.defineProperty(window, "innerWidth", {
+ value: 1200,
+ writable: true,
+ configurable: true,
+ });
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ spies.restoreGlobals();
+ if (originalInnerWidth) {
+ Object.defineProperty(window, "innerWidth", originalInnerWidth);
+ }
+ });
+
+ // SECRT-2256: when the cursor drifts over a sandboxed iframe mid-drag, the
+ // iframe eats pointermove/pointerup and the drag gets stuck. setPointerCapture
+ // routes all subsequent pointer events to the handle regardless of what's
+ // under the cursor, which fixes both "can't drag right" and "drag doesn't
+ // stop on release".
+ it("captures the pointer on pointerdown so drags survive the cursor drifting over iframes (SECRT-2256)", () => {
+ const { handle } = renderHandle();
+
+ fireEvent.pointerDown(handle, { clientX: 500, pointerId: 7 });
+
+ expect(spies.setPointerCapture).toHaveBeenCalledWith(7);
+ });
+
+ it("releases the pointer capture when the drag ends", () => {
+ const { handle } = renderHandle();
+
+ fireEvent.pointerDown(handle, { clientX: 500, pointerId: 7 });
+ fireEvent.pointerUp(handle, { clientX: 400, pointerId: 7 });
+
+ expect(spies.releasePointerCapture).toHaveBeenCalledWith(7);
+ });
+
+ it("calls onWidthChange with the expanded width when dragging leftwards", () => {
+ const onWidthChange = vi.fn();
+ const { handle } = renderHandle(onWidthChange);
+
+ fireEvent.pointerDown(handle, { clientX: 800, pointerId: 1 });
+ fireEvent.pointerMove(document, { clientX: 700, pointerId: 1 });
+
+ // startWidth is 600 (container), delta = 800 - 700 = 100 → newWidth 700
+ expect(onWidthChange).toHaveBeenCalledWith(700);
+ });
+
+ it("calls onWidthChange with the shrunk width when dragging rightwards", () => {
+ const onWidthChange = vi.fn();
+ const { handle } = renderHandle(onWidthChange);
+
+ fireEvent.pointerDown(handle, { clientX: 800, pointerId: 1 });
+ fireEvent.pointerMove(document, { clientX: 900, pointerId: 1 });
+
+ // delta = -100 → newWidth 500
+ expect(onWidthChange).toHaveBeenCalledWith(500);
+ });
+
+ it("clamps to minWidth and maxWidth", () => {
+ const onWidthChange = vi.fn();
+ const { handle } = renderHandle(onWidthChange);
+
+ fireEvent.pointerDown(handle, { clientX: 800, pointerId: 1 });
+
+ // Drag way left → want huge width, should clamp at 85% of 1200 = 1020
+ fireEvent.pointerMove(document, { clientX: -5000, pointerId: 1 });
+ expect(onWidthChange).toHaveBeenLastCalledWith(1020);
+
+ // Drag way right → want tiny width, should clamp at minWidth 320
+ fireEvent.pointerMove(document, { clientX: 5000, pointerId: 1 });
+ expect(onWidthChange).toHaveBeenLastCalledWith(320);
+ });
+
+ it("stops dragging on pointerup so subsequent cursor moves don't resize", () => {
+ const onWidthChange = vi.fn();
+ const { handle } = renderHandle(onWidthChange);
+
+ fireEvent.pointerDown(handle, { clientX: 800, pointerId: 1 });
+ fireEvent.pointerUp(handle, { clientX: 800, pointerId: 1 });
+ onWidthChange.mockClear();
+
+ fireEvent.pointerMove(document, { clientX: 500, pointerId: 1 });
+ expect(onWidthChange).not.toHaveBeenCalled();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/reactArtifactPreview.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/__tests__/reactArtifactPreview.test.ts
similarity index 92%
rename from autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/reactArtifactPreview.test.ts
rename to autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/__tests__/reactArtifactPreview.test.ts
index 934573fc01..ff1b950470 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/reactArtifactPreview.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/__tests__/reactArtifactPreview.test.ts
@@ -3,7 +3,7 @@ import {
buildReactArtifactSrcDoc,
collectPreviewStyles,
escapeHtml,
-} from "./reactArtifactPreview";
+} from "../reactArtifactPreview";
describe("escapeHtml", () => {
it("escapes &, <, >, \", '", () => {
@@ -116,4 +116,11 @@ describe("buildReactArtifactSrcDoc", () => {
expect(doc).toContain("/^[A-Z]/.test(name)");
expect(doc).toContain("wrapWithProviders");
});
+
+ it("injects the fragment-link interceptor so #anchor clicks stay inside the iframe (regression)", () => {
+ const doc = buildReactArtifactSrcDoc("module.exports = {};", "A", STYLES);
+ expect(doc).toContain("__fragmentLinkInterceptor");
+ expect(doc).toContain('a[href^="#"]');
+ expect(doc).toContain("scrollIntoView");
+ });
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/reactArtifactPreview.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/reactArtifactPreview.ts
index f98fe9f684..7be9ef9d19 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/reactArtifactPreview.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/reactArtifactPreview.ts
@@ -19,7 +19,10 @@
* React is loaded from unpkg with pinned version and SRI integrity hashes.
*/
-import { TAILWIND_CDN_URL } from "@/lib/iframe-sandbox-csp";
+import {
+ FRAGMENT_LINK_INTERCEPTOR_SCRIPT,
+ TAILWIND_CDN_URL,
+} from "@/lib/iframe-sandbox-csp";
export { transpileReactArtifactSource } from "./transpileReactArtifact";
@@ -95,6 +98,7 @@ export function buildReactArtifactSrcDoc(
}
</style>
<script src="${TAILWIND_CDN_URL}"></script>
+ ${FRAGMENT_LINK_INTERCEPTOR_SCRIPT}
<script crossorigin="anonymous" src="https://unpkg.com/[email protected]/umd/react.production.min.js" integrity="sha384-DGyLxAyjq0f9SPpVevD6IgztCFlnMF6oW/XQGmfe+IsZ8TqEiDrcHkMLKI6fiB/Z"></script><!-- pragma: allowlist secret -->
<script crossorigin="anonymous" src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js" integrity="sha384-gTGxhz21lVGYNMcdJOyq01Edg0jhn/c22nsx0kyqP0TxaV5WVdsSH1fSDUf5YJj1"></script><!-- pragma: allowlist secret -->
</head>
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/useArtifactContent.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/useArtifactContent.ts
index 1479da7a37..8368b18643 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/useArtifactContent.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/useArtifactContent.ts
@@ -141,6 +141,11 @@ export function useArtifactContent(
function retry() {
// Drop any cached failure/content for this id so we actually re-fetch.
contentCache.delete(artifact.id);
+ // Flip into loading + clear error synchronously with the click so the
+ // user always sees the skeleton (rather than the error UI re-flashing
+ // instantly for same-error retries). See SECRT-2224.
+ setIsLoading(true);
+ setError(null);
setRetryNonce((n) => n + 1);
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/helpers.test.ts
index 18738768ea..6346450606 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/helpers.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/helpers.test.ts
@@ -45,12 +45,33 @@ describe("classifyArtifact", () => {
expect(classifyArtifact("text/markdown", "x").type).toBe("markdown");
});
- it("gates files > 10MB to download-only", () => {
+ it("gates text/code files > 10MB to download-only", () => {
const c = classifyArtifact("text/plain", "big.txt", 20 * 1024 * 1024);
expect(c.openable).toBe(false);
expect(c.type).toBe("download-only");
});
+ // SECRT-2221: large images (hi-res PNGs, etc.) were getting force-classified
+ // as download-only by the generic >10MB gate, so clicking them started a
+ // download instead of previewing — and the preview was "broken" in the
+ // sense that it never appeared. Images, videos, and PDFs are decoded
+ // natively by the browser and don't run through our JS render pipeline,
+ // so the size gate shouldn't apply to them.
+ it("does NOT size-gate large images, videos, or PDFs (SECRT-2221)", () => {
+ expect(
+ classifyArtifact("image/png", "hires.png", 25 * 1024 * 1024).type,
+ ).toBe("image");
+ expect(
+ classifyArtifact("image/jpeg", "huge.jpg", 50 * 1024 * 1024).type,
+ ).toBe("image");
+ expect(
+ classifyArtifact("video/mp4", "long.mp4", 500 * 1024 * 1024).type,
+ ).toBe("video");
+ expect(
+ classifyArtifact("application/pdf", "book.pdf", 80 * 1024 * 1024).type,
+ ).toBe("pdf");
+ });
+
it("treats binary/octet-stream MIME as download-only", () => {
expect(classifyArtifact("application/zip", "a.zip").openable).toBe(false);
expect(classifyArtifact("application/octet-stream", "x").openable).toBe(
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 89a9e023c3..16a8e3fddb 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
@@ -257,14 +257,34 @@ function getExtension(filename?: string): string {
return filename.slice(lastDot).toLowerCase();
}
+// Types the browser renders natively — we don't run their bytes through our
+// React/JS pipeline, so the size gate doesn't need to apply.
+const NATIVELY_RENDERED = new Set<ArtifactClassification["type"]>([
+ "image",
+ "video",
+ "pdf",
+]);
+
export function classifyArtifact(
mimeType: string | null,
filename?: string,
sizeBytes?: number,
): ArtifactClassification {
- // Size gate: >10MB is download-only regardless of type.
- if (sizeBytes && sizeBytes > TEN_MB) return KIND["download-only"];
+ const kind = classifyByTypeOnly(mimeType, filename);
+ // Size gate: >10MB is download-only, but only for content we actually
+ // render in JS. Images, videos, and PDFs are handled natively by the
+ // browser — gating them produced "broken previews" for hi-res files
+ // (SECRT-2221).
+ if (sizeBytes && sizeBytes > TEN_MB && !NATIVELY_RENDERED.has(kind.type)) {
+ return KIND["download-only"];
+ }
+ return kind;
+}
+function classifyByTypeOnly(
+ mimeType: string | null,
+ filename?: string,
+): ArtifactClassification {
const basename = getBasename(filename);
const exactKind = EXACT_FILENAME_KIND[basename];
if (exactKind) return KIND[exactKind];
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/useAutoOpenArtifacts.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/useAutoOpenArtifacts.test.ts
index 8ff3046d55..237e9b80f5 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/useAutoOpenArtifacts.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/useAutoOpenArtifacts.test.ts
@@ -1,5 +1,5 @@
-import { act, renderHook } from "@testing-library/react";
-import { beforeEach, describe, expect, it } from "vitest";
+import { act, cleanup, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { useCopilotUIStore } from "../../store";
import { useAutoOpenArtifacts } from "./useAutoOpenArtifacts";
@@ -31,6 +31,11 @@ function resetStore() {
describe("useAutoOpenArtifacts", () => {
beforeEach(resetStore);
+ // Testing Library auto-cleanup isn't registered in our Vitest setup, so
+ // mounted `renderHook` instances (and their unmount cleanups) would leak
+ // between tests — here the unmount effect in useAutoOpenArtifacts would
+ // fire after the next test had already run and corrupt its assertions.
+ afterEach(cleanup);
it("does not auto-open on initial render", () => {
renderHook(() => useAutoOpenArtifacts({ sessionId: "s1" }));
@@ -88,4 +93,53 @@ describe("useAutoOpenArtifacts", () => {
expect(s.activeArtifact?.id).toBe("c");
expect(s.history).toEqual([]);
});
+
+ // SECRT-2254: "had agent panel open then went to profile then went to home
+ // and agent panel was still open". Nav-away unmounts the copilot page; if
+ // the panel state persists in the store, coming back re-renders it open.
+ it("closes the panel on unmount so nav-away → nav-back doesn't resurrect it (SECRT-2254)", () => {
+ useCopilotUIStore.getState().openArtifact(makeArtifact(A_ID, "a.txt"));
+ expect(useCopilotUIStore.getState().artifactPanel.isOpen).toBe(true);
+
+ const { unmount } = renderHook(() =>
+ useAutoOpenArtifacts({ sessionId: "s1" }),
+ );
+
+ act(() => {
+ unmount();
+ });
+
+ const s = useCopilotUIStore.getState().artifactPanel;
+ expect(s.isOpen).toBe(false);
+ expect(s.activeArtifact).toBeNull();
+ expect(s.history).toEqual([]);
+ });
+
+ // SECRT-2220: "keep closed by default" — a fresh mount (e.g. user returns to
+ // /copilot) must start with a closed panel even if the store somehow carries
+ // stale state from a prior life.
+ it("does not re-open a panel whose store state is stale on fresh mount (SECRT-2220)", () => {
+ // Simulate the store being left in an open state by a previous page life.
+ useCopilotUIStore.setState({
+ artifactPanel: {
+ isOpen: true,
+ isMinimized: false,
+ isMaximized: false,
+ width: 600,
+ activeArtifact: makeArtifact(A_ID, "stale.txt"),
+ history: [],
+ },
+ });
+
+ const { unmount } = renderHook(() =>
+ useAutoOpenArtifacts({ sessionId: "s1" }),
+ );
+ act(() => {
+ unmount();
+ });
+
+ // Next mount of the page should see a clean store.
+ renderHook(() => useAutoOpenArtifacts({ sessionId: "s1" }));
+ expect(useCopilotUIStore.getState().artifactPanel.isOpen).toBe(false);
+ });
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/useAutoOpenArtifacts.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/useAutoOpenArtifacts.ts
index a8b867009c..04ef7d2631 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/useAutoOpenArtifacts.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/useAutoOpenArtifacts.ts
@@ -26,4 +26,13 @@ export function useAutoOpenArtifacts({
resetArtifactPanel();
}
}, [sessionId, resetArtifactPanel]);
+
+ // Reset on unmount so navigating away from /copilot (to /profile, /home,
+ // etc.) can't leave the panel open in the Zustand store, which would then
+ // render the panel re-open when the user returns. See SECRT-2254/2220.
+ useEffect(() => {
+ return () => {
+ resetArtifactPanel();
+ };
+ }, [resetArtifactPanel]);
}
diff --git a/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/HTMLRenderer.test.tsx b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/HTMLRenderer.test.tsx
new file mode 100644
index 0000000000..2e6408ebf4
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/HTMLRenderer.test.tsx
@@ -0,0 +1,54 @@
+import { cleanup, render } from "@testing-library/react";
+import { afterEach, describe, expect, it } from "vitest";
+import { htmlRenderer } from "./HTMLRenderer";
+
+describe("HTMLRenderer", () => {
+ afterEach(() => {
+ cleanup();
+ });
+
+ it("renders text/html content in a sandboxed iframe", () => {
+ const { container } = render(
+ <>
+ {htmlRenderer.render("<h1>Hi</h1>", {
+ mimeType: "text/html",
+ filename: "page.html",
+ })}
+ </>,
+ );
+ const iframe = container.querySelector("iframe");
+ expect(iframe).toBeTruthy();
+ expect(iframe?.getAttribute("sandbox")).toBe("allow-scripts");
+ });
+
+ it("injects the fragment-link interceptor into the srcDoc (regression)", () => {
+ const { container } = render(
+ <>
+ {htmlRenderer.render(
+ '<html><head></head><body><a href="#x">x</a><div id="x">x</div></body></html>',
+ { mimeType: "text/html", filename: "page.html" },
+ )}
+ </>,
+ );
+ const srcdoc = container.querySelector("iframe")?.getAttribute("srcdoc");
+ expect(srcdoc).toBeTruthy();
+ expect(srcdoc).toContain("__fragmentLinkInterceptor");
+ expect(srcdoc).toContain('a[href^="#"]');
+ expect(srcdoc).toContain("scrollIntoView");
+ });
+
+ it("canRender recognises text/html mime type and .html/.htm filenames", () => {
+ expect(
+ htmlRenderer.canRender("<h1>Hi</h1>", { mimeType: "text/html" }),
+ ).toBe(true);
+ expect(
+ htmlRenderer.canRender("<h1>Hi</h1>", { filename: "report.html" }),
+ ).toBe(true);
+ expect(
+ htmlRenderer.canRender("<h1>Hi</h1>", { filename: "report.htm" }),
+ ).toBe(true);
+ expect(
+ htmlRenderer.canRender("<h1>Hi</h1>", { mimeType: "text/plain" }),
+ ).toBe(false);
+ });
+});
diff --git a/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/HTMLRenderer.tsx b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/HTMLRenderer.tsx
index 40a28e3c0a..a855a990e9 100644
--- a/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/HTMLRenderer.tsx
+++ b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/HTMLRenderer.tsx
@@ -1,5 +1,6 @@
import React from "react";
import {
+ FRAGMENT_LINK_INTERCEPTOR_SCRIPT,
TAILWIND_CDN_URL,
wrapWithHeadInjection,
} from "@/lib/iframe-sandbox-csp";
@@ -13,7 +14,10 @@ import {
function HTMLPreview({ value }: { value: string }) {
// Inject Tailwind CDN — no CSP (see iframe-sandbox-csp.ts for why)
const tailwindScript = `<script src="${TAILWIND_CDN_URL}"></script>`;
- const srcDoc = wrapWithHeadInjection(value, tailwindScript);
+ const srcDoc = wrapWithHeadInjection(
+ value,
+ tailwindScript + FRAGMENT_LINK_INTERCEPTOR_SCRIPT,
+ );
return (
<iframe
sandbox="allow-scripts"
diff --git a/autogpt_platform/frontend/src/lib/__tests__/iframe-sandbox-csp.test.ts b/autogpt_platform/frontend/src/lib/__tests__/iframe-sandbox-csp.test.ts
index ce51bee485..25575cff58 100644
--- a/autogpt_platform/frontend/src/lib/__tests__/iframe-sandbox-csp.test.ts
+++ b/autogpt_platform/frontend/src/lib/__tests__/iframe-sandbox-csp.test.ts
@@ -1,5 +1,9 @@
-import { describe, expect, it } from "vitest";
-import { TAILWIND_CDN_URL, wrapWithHeadInjection } from "../iframe-sandbox-csp";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ FRAGMENT_LINK_INTERCEPTOR_SCRIPT,
+ TAILWIND_CDN_URL,
+ wrapWithHeadInjection,
+} from "../iframe-sandbox-csp";
describe("wrapWithHeadInjection", () => {
const injection = '<script src="https://example.com/lib.js"></script>';
@@ -45,6 +49,142 @@ describe("TAILWIND_CDN_URL", () => {
});
});
+describe("FRAGMENT_LINK_INTERCEPTOR_SCRIPT", () => {
+ // Evaluate the script body (without <script> tags) against the current
+ // document. Because sandboxed srcdoc iframes run their scripts in isolation
+ // anyway, the behavior we care about is just "this code, when executed in
+ // a document, intercepts #anchor clicks and calls scrollIntoView".
+ //
+ // Parse the exported <script> via the DOM rather than regex — CodeQL flags
+ // regex-based HTML stripping, and the test already runs in a DOM env.
+ function installInterceptor() {
+ const template = document.createElement("template");
+ template.innerHTML = FRAGMENT_LINK_INTERCEPTOR_SCRIPT;
+ const script = template.content.querySelector("script");
+ if (!script) throw new Error("Interceptor script tag not found");
+ new Function(script.textContent ?? "")();
+ }
+
+ let cleanup: (() => void) | null = null;
+
+ beforeEach(() => {
+ document.body.innerHTML = "";
+ });
+
+ afterEach(() => {
+ if (cleanup) cleanup();
+ cleanup = null;
+ document.body.innerHTML = "";
+ const doc = document as Document & {
+ __fragmentLinkInterceptor?: EventListener;
+ };
+ if (doc.__fragmentLinkInterceptor) {
+ document.removeEventListener("click", doc.__fragmentLinkInterceptor);
+ delete doc.__fragmentLinkInterceptor;
+ }
+ });
+
+ it("exports a <script> tag wrapping the interceptor", () => {
+ expect(FRAGMENT_LINK_INTERCEPTOR_SCRIPT.startsWith("<script>")).toBe(true);
+ expect(FRAGMENT_LINK_INTERCEPTOR_SCRIPT.endsWith("</script>")).toBe(true);
+ expect(FRAGMENT_LINK_INTERCEPTOR_SCRIPT).toContain("addEventListener");
+ expect(FRAGMENT_LINK_INTERCEPTOR_SCRIPT).toContain("scrollIntoView");
+ expect(FRAGMENT_LINK_INTERCEPTOR_SCRIPT).toContain('a[href^="#"]');
+ });
+
+ // Install the interceptor first, then a tail listener that records
+ // defaultPrevented. Listeners fire in registration order, so the tail
+ // sees the post-interceptor state.
+ function installWithObserver() {
+ installInterceptor();
+ const observed = { defaulted: false };
+ const listener = (e: Event) => {
+ observed.defaulted = e.defaultPrevented;
+ };
+ document.addEventListener("click", listener);
+ cleanup = () => document.removeEventListener("click", listener);
+ return observed;
+ }
+
+ it("intercepts fragment-link clicks, calls preventDefault, and scrolls the target into view", () => {
+ document.body.innerHTML = `
+ <nav><a id="nav-link" href="#activation">Activation</a></nav>
+ <section id="activation">Target</section>
+ `;
+ const scrollSpy = vi.fn();
+ document.getElementById("activation")!.scrollIntoView = scrollSpy;
+
+ const observed = installWithObserver();
+
+ document.getElementById("nav-link")!.click();
+
+ expect(scrollSpy).toHaveBeenCalledTimes(1);
+ expect(observed.defaulted).toBe(true);
+ });
+
+ it("does not intercept bare '#' links (no target id)", () => {
+ document.body.innerHTML = `<a id="top" href="#">Back to top</a>`;
+ const observed = installWithObserver();
+
+ document.getElementById("top")!.click();
+
+ expect(observed.defaulted).toBe(false);
+ });
+
+ it("does not intercept links with no matching target in the document", () => {
+ document.body.innerHTML = `<a id="dangle" href="#missing">Nowhere</a>`;
+ const observed = installWithObserver();
+
+ document.getElementById("dangle")!.click();
+
+ expect(observed.defaulted).toBe(false);
+ });
+
+ it("does not intercept non-fragment links", () => {
+ document.body.innerHTML = `<a id="ext" href="https://example.com/x">Ext</a>`;
+ installInterceptor();
+ const observed = { defaulted: false };
+ const listener = (e: Event) => {
+ observed.defaulted = e.defaultPrevented;
+ e.preventDefault();
+ };
+ document.addEventListener("click", listener);
+ cleanup = () => document.removeEventListener("click", listener);
+
+ document.getElementById("ext")!.click();
+
+ expect(observed.defaulted).toBe(false);
+ });
+
+ it("scrolls to target when click originates from a nested child of the anchor", () => {
+ document.body.innerHTML = `
+ <a id="outer" href="#costs"><span id="inner">💰 Costs</span></a>
+ <section id="costs">Target</section>
+ `;
+ const scrollSpy = vi.fn();
+ document.getElementById("costs")!.scrollIntoView = scrollSpy;
+
+ installInterceptor();
+ document.getElementById("inner")!.click();
+
+ expect(scrollSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it("handles percent-encoded ids", () => {
+ document.body.innerHTML = `
+ <a id="enc" href="#top%20costs">Jump</a>
+ <section id="top costs">Target</section>
+ `;
+ const scrollSpy = vi.fn();
+ document.getElementById("top costs")!.scrollIntoView = scrollSpy;
+
+ installInterceptor();
+ document.getElementById("enc")!.click();
+
+ expect(scrollSpy).toHaveBeenCalledTimes(1);
+ });
+});
+
describe("no CSP is exported", () => {
it("does not export ARTIFACT_IFRAME_CSP", async () => {
const mod = await import("../iframe-sandbox-csp");
diff --git a/autogpt_platform/frontend/src/lib/iframe-sandbox-csp.ts b/autogpt_platform/frontend/src/lib/iframe-sandbox-csp.ts
index 65990f1e13..0d281c5e8d 100644
--- a/autogpt_platform/frontend/src/lib/iframe-sandbox-csp.ts
+++ b/autogpt_platform/frontend/src/lib/iframe-sandbox-csp.ts
@@ -32,6 +32,38 @@
// changes (SRI is not possible because the JIT runtime is generated on demand).
export const TAILWIND_CDN_URL = "https://cdn.tailwindcss.com/3.4.16";
+// Sandboxed srcdoc iframes without `allow-same-origin` resolve `href="#id"` links
+// against the parent's URL as base. The default click then either navigates the
+// iframe to `<parent-url>#id` (reloading our app inside the iframe) or updates
+// the parent window's hash — both of which break the artifact preview.
+//
+// This script stays inside the iframe document and handles in-page anchor
+// navigation locally by scrolling to the element with the matching id.
+export const FRAGMENT_LINK_INTERCEPTOR_SCRIPT = `<script>
+(function() {
+ if (document.__fragmentLinkInterceptor) return;
+ function handler(e) {
+ var t = e.target;
+ if (!t || typeof t.closest !== 'function') return;
+ var a = t.closest('a[href^="#"]');
+ if (!a) return;
+ var href = a.getAttribute('href');
+ if (!href || href === '#') return;
+ var id;
+ try { id = decodeURIComponent(href.slice(1)); } catch (_) { id = href.slice(1); }
+ if (!id) return;
+ var target = document.getElementById(id);
+ if (!target) return;
+ e.preventDefault();
+ if (typeof target.scrollIntoView === 'function') {
+ target.scrollIntoView({ behavior: 'smooth', block: 'start' });
+ }
+ }
+ document.__fragmentLinkInterceptor = handler;
+ document.addEventListener('click', handler);
+})();
+</script>`;
+
/**
* Inject content into the <head> of an HTML document string.
* If the content has no <head> tag, wraps it in a full document skeleton.