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): load YouTube embeds only after marketing consent (#15751)
Krzysztof Czerwinski6c07c09d4ca9
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/AgentImageItem/AgentImageItem.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/AgentImageItem/AgentImageItem.tsxindex 0b13c7868b..3e86438fbe 100644--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/AgentImageItem/AgentImageItem.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/AgentImageItem/AgentImageItem.tsx@@ -3,15 +3,13 @@ import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";import Image from "next/image";import { isLocalStoreMediaUrl } from "@/lib/store-media";import { useEffect, useState } from "react";-import {- getYouTubeVideoId,- isValidVideoFile,- isValidVideoUrl,-} from "./helpers";+import { isValidVideoFile, isValidVideoUrl } from "./helpers";import { useAgentImageItem } from "./useAgentImageItem";import { ImageNotFound01Icon, PlayIcon } from "@hugeicons/core-free-icons";import { Icon } from "@/components/atoms/Icon/Icon";import { useImageFallback } from "@/hooks/useImageFallback";+import { YouTubeEmbed } from "@/components/molecules/YouTubeEmbed/YouTubeEmbed";+import { isYouTubeUrl } from "@/components/molecules/YouTubeEmbed/helpers";interface AgentImageItemProps {image: string;@@ -41,15 +39,8 @@ export function AgentImageItem({<div className="relative"><div className="h-[15rem] overflow-hidden rounded-xl border border-neutral-100 bg-[#a8a8a8] sm:h-[20rem] sm:w-full md:h-[25rem] lg:h-[30rem]">{isValidVideoUrl(image) ? (- getYouTubeVideoId(image) ? (- <iframe- width="100%"- height="100%"- src={`https://www.youtube.com/embed/${getYouTubeVideoId(image)}`}- allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"- allowFullScreen- title="YouTube video player"- ></iframe>+ isYouTubeUrl(image) ? (+ <YouTubeEmbed url={image} />) : (<div className="relative h-full w-full overflow-hidden"><videodiff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/AgentImageItem/__tests__/AgentImageItem.test.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/AgentImageItem/__tests__/AgentImageItem.test.tsxindex 4523b48bf9..7a50e7207e 100644--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/AgentImageItem/__tests__/AgentImageItem.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/AgentImageItem/__tests__/AgentImageItem.test.tsx@@ -1,5 +1,10 @@-import { describe, expect, test } from "vitest";+import { afterEach, describe, expect, test, vi } from "vitest";import { fireEvent, render, screen } from "@/tests/integrations/test-utils";+import {+ configureCookiebot,+ installCookiebot,+ removeCookiebot,+} from "@/tests/integrations/cookiebot";import { AgentImageItem } from "../AgentImageItem";@@ -16,6 +21,11 @@ function renderItem(image: string) {}describe("AgentImageItem", () => {+ afterEach(() => {+ removeCookiebot();+ vi.unstubAllEnvs();+ });+test("renders the preview image while the URL loads", () => {renderItem("https://cdn.test/preview.png");expect(screen.getByAltText("Image")).toBeDefined();@@ -29,4 +39,63 @@ describe("AgentImageItem", () => {expect(screen.queryByAltText("Image")).toBeNull();expect(container.querySelector("svg")).not.toBeNull();});++ test("shows the cookie notice instead of a YouTube video without consent", () => {+ configureCookiebot();+ installCookiebot({ marketing: false });++ const { container } = renderItem(+ "https://www.youtube.com/watch?v=dQw4w9WgXcQ",+ );++ expect(container.querySelector("iframe")).toBeNull();+ expect(+ screen.getByRole("link", { name: "Watch on YouTube" }),+ ).toBeDefined();+ });++ test("embeds the privacy-enhanced YouTube player with consent", () => {+ configureCookiebot();+ installCookiebot({ marketing: true });++ const { container } = renderItem(+ "https://www.youtube.com/watch?v=dQw4w9WgXcQ",+ );++ expect(container.querySelector("iframe")?.getAttribute("src")).toBe(+ "https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ",+ );+ });++ test.each([+ "https://www.youtube.com/shorts/dQw4w9WgXcQ",+ "https://www.youtube.com/live/dQw4w9WgXcQ",+ "https://www.youtube.com/watch?feature=shared&v=dQw4w9WgXcQ",+ ])("gates %s behind consent like any other video", (url) => {+ configureCookiebot();+ installCookiebot({ marketing: false });++ const { container } = renderItem(url);++ expect(container.querySelector("iframe")).toBeNull();+ expect(container.querySelector("video")).toBeNull();+ expect(+ screen+ .getByRole("link", { name: "Watch on YouTube" })+ .getAttribute("href"),+ ).toBe("https://www.youtube.com/watch?v=dQw4w9WgXcQ");+ });++ test("never puts a YouTube page it can't play into a video element", () => {+ configureCookiebot();+ installCookiebot({ marketing: true });++ const { container } = renderItem("https://www.youtube.com/@somechannel");++ expect(container.querySelector("video")).toBeNull();+ expect(container.querySelector("iframe")).toBeNull();+ expect(+ screen.getByRole("link", { name: "Watch on YouTube" }),+ ).toBeDefined();+ });});diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/AgentImageItem/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/AgentImageItem/helpers.tsindex c852ab5989..f2834f452e 100644--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/AgentImageItem/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/AgentImageItem/helpers.ts@@ -1,17 +1,10 @@+import { isYouTubeUrl } from "@/components/molecules/YouTubeEmbed/helpers";+export const isValidVideoFile = (url: string): boolean => {const videoExtensions = /\.(mp4|webm|ogg)$/i;return videoExtensions.test(url);};export const isValidVideoUrl = (url: string): boolean => {- const videoExtensions = /\.(mp4|webm|ogg)$/i;- const youtubeRegex = /^(https?:\/\/)?(www\.)?(youtube\.com|youtu\.?be)\/.+$/;- return videoExtensions.test(url) || youtubeRegex.test(url);-};--export const getYouTubeVideoId = (url: string) => {- const regExp =- /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*/;- const match = url.match(regExp);- return match && match[7].length === 11 ? match[7] : null;+ return isValidVideoFile(url) || isYouTubeUrl(url);};diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/AgentImages/AgentImage.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/AgentImages/AgentImage.tsxindex b11b971d44..71c5e28ec7 100644--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/AgentImages/AgentImage.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/AgentImages/AgentImage.tsx@@ -2,11 +2,12 @@import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";import { Icon } from "@/components/atoms/Icon/Icon";-import { ImageNotFound01Icon } from "@hugeicons/core-free-icons";+import { ImageNotFound01Icon, YoutubeIcon } from "@hugeicons/core-free-icons";import { cn } from "@/lib/utils";import { useEffect, useState } from "react";import { AgentImageItem } from "../AgentImageItem/AgentImageItem";-import { getYouTubeVideoId, isValidVideoUrl } from "../AgentImageItem/helpers";+import { useConsent } from "@/services/consent/useConsent";+import { getThumbnail } from "./helpers";import { useAgentImage } from "./useAgentImage";interface AgentImagesProps {@@ -15,6 +16,9 @@ interface AgentImagesProps {export function AgentImages({ images }: AgentImagesProps) {const { playingVideoIndex, handlePlay, handlePause } = useAgentImage();+ // YouTube thumbnails come from YouTube, so they wait for the same consent+ // as the player.+ const { advertising } = useConsent();const [selectedIndex, setSelectedIndex] = useState(0);const [loadedThumbs, setLoadedThumbs] = useState<Set<number>>(new Set());// Keyed by URL: the component stays mounted when a listing's images change.@@ -45,12 +49,9 @@ export function AgentImages({ images }: AgentImagesProps) {{images.length > 1 && (<div className="mt-3 flex gap-2 overflow-x-auto pb-1 sm:mt-4 sm:gap-3">{images.map((image, index) => {- const isVideo = isValidVideoUrl(image);- const youtubeId = isVideo ? getYouTubeVideoId(image) : null;- const thumbnailUrl = youtubeId- ? `https://img.youtube.com/vi/${youtubeId}/mqdefault.jpg`- : image;- const thumbnailFailed = failedThumbs.has(thumbnailUrl);+ const thumbnail = getThumbnail(image, advertising);+ const thumbnailFailed =+ thumbnail.kind === "image" && failedThumbs.has(thumbnail.src);return (<button@@ -64,7 +65,7 @@ export function AgentImages({ images }: AgentImagesProps) {: "border-zinc-100 opacity-70 hover:opacity-100",)}>- {(!isVideo || youtubeId) &&+ {thumbnail.kind === "image" &&!loadedThumbs.has(index) &&!thumbnailFailed && (<Skeleton className="absolute inset-0 rounded-lg" />@@ -76,32 +77,30 @@ export function AgentImages({ images }: AgentImagesProps) {className="h-5 w-5 text-zinc-400"/></div>- ) : youtubeId ? (+ ) : thumbnail.kind === "image" ? (<img- src={thumbnailUrl}+ src={thumbnail.src}alt={`Thumbnail ${index + 1}`}loading="lazy"className="absolute inset-0 h-full w-full object-cover"onLoad={() =>setLoadedThumbs((prev) => new Set(prev).add(index))}- onError={() => markThumbFailed(thumbnailUrl)}+ onError={() => markThumbFailed(thumbnail.src)}/>- ) : isVideo ? (+ ) : thumbnail.kind === "youtube" ? (+ <div className="flex h-full w-full items-center justify-center bg-zinc-100">+ <Icon+ icon={YoutubeIcon}+ aria-hidden+ className="h-6 w-6 text-zinc-400"+ />+ <span className="sr-only">{thumbnail.label}</span>+ </div>+ ) : (<div className="flex h-full w-full items-center justify-center bg-neutral-200 text-xs text-neutral-500">Video</div>- ) : (- <img- src={thumbnailUrl}- alt={`Thumbnail ${index + 1}`}- loading="lazy"- className="absolute inset-0 h-full w-full object-cover"- onLoad={() =>- setLoadedThumbs((prev) => new Set(prev).add(index))- }- onError={() => markThumbFailed(thumbnailUrl)}- />)}</button>);diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/AgentImages/__tests__/AgentImage.test.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/AgentImages/__tests__/AgentImage.test.tsxindex cdc8d816ed..9cf2b316d8 100644--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/AgentImages/__tests__/AgentImage.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/AgentImages/__tests__/AgentImage.test.tsx@@ -1,5 +1,16 @@-import { describe, expect, test } from "vitest";-import { fireEvent, render, screen } from "@/tests/integrations/test-utils";+import { afterEach, describe, expect, test, vi } from "vitest";+import {+ act,+ fireEvent,+ render,+ screen,+} from "@/tests/integrations/test-utils";+import {+ answerCookiebot,+ configureCookiebot,+ installCookiebot,+ removeCookiebot,+} from "@/tests/integrations/cookiebot";import { AgentImages } from "../AgentImage";@@ -33,3 +44,65 @@ describe("AgentImages thumbnails", () => {expect(replacement.src).toBe("https://cdn.test/replacement.png");});});++describe("AgentImages YouTube thumbnails", () => {+ const WITH_SHORT = [+ "https://cdn.test/one.png",+ "https://www.youtube.com/shorts/dQw4w9WgXcQ",+ ];++ afterEach(() => {+ removeCookiebot();+ vi.unstubAllEnvs();+ });++ test("loads nothing from YouTube before marketing consent", () => {+ configureCookiebot();+ installCookiebot({ marketing: false });++ const { container } = render(<AgentImages images={WITH_SHORT} />);++ expect(screen.queryByAltText("Thumbnail 2")).toBeNull();+ expect(screen.getByText("YouTube video")).toBeDefined();+ const requested = Array.from(container.querySelectorAll("img, iframe"))+ .map((node) => node.getAttribute("src") ?? "")+ .filter((src) => src.includes("youtube"));+ expect(requested).toEqual([]);+ });++ test("shows the YouTube thumbnail once marketing cookies are allowed", () => {+ configureCookiebot();+ installCookiebot({ marketing: false });+ render(<AgentImages images={WITH_SHORT} />);++ act(() => answerCookiebot({ marketing: true }));++ expect(screen.getByAltText("Thumbnail 2").getAttribute("src")).toBe(+ "https://img.youtube.com/vi/dQw4w9WgXcQ/mqdefault.jpg",+ );+ });++ test.each([+ "https://img.youtube.com/vi/dQw4w9WgXcQ/maxresdefault.jpg",+ "https://i.ytimg.com/vi/dQw4w9WgXcQ/hqdefault.jpg",+ "https://i.ytimg.com./vi/dQw4w9WgXcQ/mqdefault.jpg",+ "https://img.youtube.com./vi/dQw4w9WgXcQ/0.jpg",+ ])("waits for consent before a listing image hosted at %s", (image) => {+ configureCookiebot();+ installCookiebot({ marketing: false });+ const { container } = render(+ <AgentImages images={["https://cdn.test/one.png", image]} />,+ );++ expect(screen.queryByAltText("Thumbnail 2")).toBeNull();+ expect(screen.getByText("Image from YouTube")).toBeDefined();+ const requested = Array.from(container.querySelectorAll("img"))+ .map((node) => node.getAttribute("src") ?? "")+ .filter((src) => src.includes("youtube") || src.includes("ytimg"));+ expect(requested).toEqual([]);++ act(() => answerCookiebot({ marketing: true }));++ expect(screen.getByAltText("Thumbnail 2").getAttribute("src")).toBe(image);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/AgentImages/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/AgentImages/helpers.tsnew file mode 100644index 0000000000..2aa54962de--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/AgentImages/helpers.ts@@ -0,0 +1,33 @@+import {+ getYouTubeVideoId,+ isYouTubeImageUrl,+} from "@/components/molecules/YouTubeEmbed/helpers";+import { isValidVideoUrl } from "../AgentImageItem/helpers";++type Thumbnail =+ | { kind: "image"; src: string }+ | { kind: "youtube"; label: string }+ | { kind: "video" };++// Anything served by YouTube (a video's thumbnail, or a listing image hosted+// there) waits for the same marketing consent as the player.+export function getThumbnail(+ image: string,+ hasAdvertisingConsent: boolean,+): Thumbnail {+ if (isValidVideoUrl(image)) {+ const videoId = getYouTubeVideoId(image);+ if (!videoId) return { kind: "video" };+ if (!hasAdvertisingConsent) {+ return { kind: "youtube", label: "YouTube video" };+ }+ return {+ kind: "image",+ src: `https://img.youtube.com/vi/${videoId}/mqdefault.jpg`,+ };+ }+ if (isYouTubeImageUrl(image) && !hasAdvertisingConsent) {+ return { kind: "youtube", label: "Image from YouTube" };+ }+ return { kind: "image", src: image };+}diff --git a/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/MarkdownRenderer.tsx b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/MarkdownRenderer.tsxindex 8bc7f9752c..bc1d5c9ee6 100644--- a/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/MarkdownRenderer.tsx+++ b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/MarkdownRenderer.tsx@@ -1,7 +1,7 @@"use client";import React from "react";-import ReactMarkdown from "react-markdown";+import ReactMarkdown, { type Components } from "react-markdown";import remarkGfm from "remark-gfm";import remarkMath from "remark-math";import rehypeKatex from "rehype-katex";@@ -17,6 +17,12 @@ import {import "highlight.js/styles/github-dark.css";import "katex/dist/katex.min.css";import { escapeCurrencyAmounts } from "@/lib/markdown-math";+import { YouTubeEmbed } from "@/components/molecules/YouTubeEmbed/YouTubeEmbed";+import {+ getYouTubeVideoId,+ getYouTubeWatchUrl,+ isYouTubeUrl,+} from "@/components/molecules/YouTubeEmbed/helpers";const markdownPatterns = [/```[\s\S]*?```/u, // Fenced code blocks (check first)@@ -40,8 +46,10 @@ const markdownPatterns = [const videoExtensions = [".mp4", ".webm", ".ogg", ".mov", ".avi"];function isVideoUrl(url: string): boolean {- if (url.includes("youtube.com/watch") || url.includes("youtu.be/")) {- return true;+ // A YouTube link is a video only when it names one; a channel or playlist+ // stays a link.+ if (isYouTubeUrl(url)) {+ return getYouTubeVideoId(url) !== null;}try {const parsed = new URL(url);@@ -58,13 +66,6 @@ function isVideoUrl(url: string): boolean {}function getVideoEmbedUrl(url: string): string | null {- const youtubeMatch = url.match(- /(?:youtube\.com\/watch\?v=|youtu\.be\/)([^&\s]+)/,- );- if (youtubeMatch) {- return `https://www.youtube.com/embed/${youtubeMatch[1]}`;- }-const vimeoMatch = url.match(/vimeo\.com\/(\d+)/);if (vimeoMatch) {return `https://player.vimeo.com/video/${vimeoMatch[1]}`;@@ -77,20 +78,58 @@ function getVideoEmbedUrl(url: string): string | null {return null;}+function renderPlainLink(url: string, label: React.ReactNode = url) {+ return (+ <a+ href={url}+ target="_blank"+ rel="noopener noreferrer"+ className="text-blue-600 underline"+ >+ {label}+ </a>+ );+}++// Set inside a markdown link, so content rendered there doesn't add an+// anchor of its own (anchors can't nest).+const InsideLinkContext = React.createContext(false);++interface MarkdownVideoImageProps {+ src: string;+ alt?: string;+}++// An image whose source is a video, or a YouTube page that isn't one video+// (shown as a link, since an <img> would fetch it before consent). Inside a+// link only its text is shown: a player or a second link can't sit in an+// anchor.+function MarkdownVideoImage({ src, alt }: MarkdownVideoImageProps) {+ const insideLink = React.useContext(InsideLinkContext);+ if (insideLink) return <>{alt || src}</>;+ if (isVideoUrl(src)) return renderVideoEmbed(src);+ // Written without a scheme, the link would resolve against this site.+ return renderPlainLink(getYouTubeWatchUrl(src) ?? src, alt || src);+}+function renderVideoEmbed(url: string): React.ReactNode {+ if (getYouTubeVideoId(url)) {+ return (+ <div className="my-4">+ <div className="relative aspect-video">+ <YouTubeEmbed+ url={url}+ className="absolute left-0 top-0 rounded-lg shadow-md"+ />+ </div>+ </div>+ );+ }+const embedUrl = getVideoEmbedUrl(url);if (!embedUrl) {- return (- <a- href={url}- target="_blank"- rel="noopener noreferrer"- className="text-blue-600 underline"- >- {url}- </a>- );+ return renderPlainLink(url);}if (videoExtensions.some((ext) => embedUrl.toLowerCase().includes(ext))) {@@ -155,6 +194,237 @@ function canRenderMarkdown(value: unknown, metadata?: OutputMetadata): boolean {return false;}+// Module-level, so each render passes the same component types and React+// keeps the subtree (a playing video, a one-off "Load video") mounted.+const MARKDOWN_COMPONENTS: Components = {+ // Custom components for better rendering+ pre: ({ children, ...props }) => (+ <pre+ className="my-4 overflow-x-auto rounded-md bg-gray-900 p-4 dark:bg-gray-950"+ {...props}+ >+ {children}+ </pre>+ ),+ code: ({ children, ...props }: any) => {+ // Check if it's inline code by looking at the parent+ const isInline = !props.className?.includes("language-");+ if (isInline) {+ return (+ <code+ className="rounded bg-gray-100 px-1.5 py-0.5 font-mono text-sm text-gray-800 dark:bg-gray-800 dark:text-gray-200"+ {...props}+ >+ {children}+ </code>+ );+ }+ // Block code is handled by rehype-highlight+ return (+ <code className="font-mono text-sm text-gray-100" {...props}>+ {children}+ </code>+ );+ },+ a: ({ children, href, ...props }) => (+ <a+ href={href}+ target="_blank"+ rel="noopener noreferrer"+ className="text-black underline decoration-1 underline-offset-2 transition-colors"+ {...props}+ >+ <InsideLinkContext.Provider value={true}>+ {children}+ </InsideLinkContext.Provider>+ </a>+ ),+ blockquote: ({ children, ...props }) => (+ <blockquote+ className="my-4 border-l-4 border-blue-500 pl-4 italic text-gray-700 dark:border-blue-400 dark:text-gray-300"+ {...props}+ >+ {children}+ </blockquote>+ ),+ table: ({ children, ...props }) => (+ <div className="my-4 overflow-x-auto">+ <table+ className="min-w-full divide-y divide-gray-200 border-y border-gray-200 dark:divide-gray-700 dark:border-gray-700"+ {...props}+ >+ {children}+ </table>+ </div>+ ),+ th: ({ children, ...props }) => (+ <th+ className="bg-gray-50 px-4 py-3.5 text-left text-xs font-semibold uppercase tracking-wider text-gray-700 dark:bg-gray-800 dark:text-gray-300"+ {...props}+ >+ {children}+ </th>+ ),+ td: ({ children, ...props }) => (+ <td+ className="border-t border-gray-200 px-4 py-3.5 text-sm text-gray-600 dark:border-gray-700 dark:text-gray-400"+ {...props}+ >+ {children}+ </td>+ ),+ // GitHub Flavored Markdown task lists+ input: ({ ...props }: any) => {+ if (props.type === "checkbox") {+ return (+ <input+ type="checkbox"+ className="mr-2 h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500 disabled:cursor-not-allowed disabled:opacity-70"+ disabled+ {...props}+ />+ );+ }+ return <input {...props} />;+ },+ // Better list styling+ ul: ({ children, ...props }: any) => (+ <ul+ className={`my-4 list-disc space-y-2 pl-6 ${+ props.className?.includes("contains-task-list") ? "list-none pl-0" : ""+ }`}+ {...props}+ >+ {children}+ </ul>+ ),+ ol: ({ children, ...props }) => (+ <ol className="my-4 list-decimal space-y-2 pl-6" {...props}>+ {children}+ </ol>+ ),+ li: ({ children, ...props }: any) => (+ <li+ className={`text-gray-700 dark:text-gray-300 ${+ props.className?.includes("task-list-item") ? "flex items-start" : ""+ }`}+ {...props}+ >+ {children}+ </li>+ ),+ // Better heading styles+ h1: ({ children, ...props }) => (+ <h1+ className="my-6 text-3xl font-bold text-gray-900 dark:text-gray-100"+ {...props}+ >+ {children}+ </h1>+ ),+ h2: ({ children, ...props }) => (+ <h2+ className="my-5 text-2xl font-semibold text-gray-800 dark:text-gray-200"+ {...props}+ >+ {children}+ </h2>+ ),+ h3: ({ children, ...props }) => (+ <h3+ className="my-4 text-xl font-semibold text-gray-800 dark:text-gray-200"+ {...props}+ >+ {children}+ </h3>+ ),+ h4: ({ children, ...props }) => (+ <h4+ className="my-3 text-lg font-medium text-gray-700 dark:text-gray-300"+ {...props}+ >+ {children}+ </h4>+ ),+ h5: ({ children, ...props }) => (+ <h5+ className="my-2 text-base font-medium text-gray-700 dark:text-gray-300"+ {...props}+ >+ {children}+ </h5>+ ),+ h6: ({ children, ...props }) => (+ <h6+ className="my-2 text-sm font-medium text-gray-600 dark:text-gray-400"+ {...props}+ >+ {children}+ </h6>+ ),+ // Horizontal rule+ hr: ({ ...props }) => (+ <hr className="my-6 border-gray-300 dark:border-gray-700" {...props} />+ ),+ // Strikethrough (GFM)+ del: ({ children, ...props }) => (+ <del className="text-gray-500 line-through dark:text-gray-500" {...props}>+ {children}+ </del>+ ),+ // Image handling+ img: ({ src, alt, ...props }) => {+ if (+ src &&+ typeof src === "string" &&+ (isVideoUrl(src) || isYouTubeUrl(src))+ ) {+ return <MarkdownVideoImage src={src} alt={alt} />;+ }++ return (+ // eslint-disable-next-line @next/next/no-img-element+ <img+ src={src}+ alt={alt}+ className="my-4 h-auto max-w-full rounded-lg shadow-md"+ loading="lazy"+ {...props}+ />+ );+ },+ // Custom paragraph to handle standalone video URLs+ p: ({ children, ...props }) => {+ // Check if paragraph contains just a video URL+ if (typeof children === "string" && isVideoUrl(children.trim())) {+ return renderVideoEmbed(children.trim());+ }++ // Check for video URLs in link children+ if (React.Children.count(children) === 1) {+ const child = React.Children.toArray(children)[0];+ if (+ React.isValidElement<{ href?: string }>(child) &&+ child.type === "a"+ ) {+ const href = child.props.href;+ if (href && isVideoUrl(href)) {+ return renderVideoEmbed(href);+ }+ }+ }++ return (+ <p+ className="my-3 leading-relaxed text-gray-700 dark:text-gray-300"+ {...props}+ >+ {children}+ </p>+ );+ },+};+function renderMarkdown(value: unknown,_metadata?: OutputMetadata,@@ -175,239 +445,7 @@ function renderMarkdown(rehypeSlug, // Add IDs to headings[rehypeAutolinkHeadings, { behavior: "wrap" }], // Make headings clickable]}- components={{- // Custom components for better rendering- pre: ({ children, ...props }) => (- <pre- className="my-4 overflow-x-auto rounded-md bg-gray-900 p-4 dark:bg-gray-950"- {...props}- >- {children}- </pre>- ),- code: ({ children, ...props }: any) => {- // Check if it's inline code by looking at the parent- const isInline = !props.className?.includes("language-");- if (isInline) {- return (- <code- className="rounded bg-gray-100 px-1.5 py-0.5 font-mono text-sm text-gray-800 dark:bg-gray-800 dark:text-gray-200"- {...props}- >- {children}- </code>- );- }- // Block code is handled by rehype-highlight- return (- <code className="font-mono text-sm text-gray-100" {...props}>- {children}- </code>- );- },- a: ({ children, href, ...props }) => (- <a- href={href}- target="_blank"- rel="noopener noreferrer"- className="text-black underline decoration-1 underline-offset-2 transition-colors"- {...props}- >- {children}- </a>- ),- blockquote: ({ children, ...props }) => (- <blockquote- className="my-4 border-l-4 border-blue-500 pl-4 italic text-gray-700 dark:border-blue-400 dark:text-gray-300"- {...props}- >- {children}- </blockquote>- ),- table: ({ children, ...props }) => (- <div className="my-4 overflow-x-auto">- <table- className="min-w-full divide-y divide-gray-200 border-y border-gray-200 dark:divide-gray-700 dark:border-gray-700"- {...props}- >- {children}- </table>- </div>- ),- th: ({ children, ...props }) => (- <th- className="bg-gray-50 px-4 py-3.5 text-left text-xs font-semibold uppercase tracking-wider text-gray-700 dark:bg-gray-800 dark:text-gray-300"- {...props}- >- {children}- </th>- ),- td: ({ children, ...props }) => (- <td- className="border-t border-gray-200 px-4 py-3.5 text-sm text-gray-600 dark:border-gray-700 dark:text-gray-400"- {...props}- >- {children}- </td>- ),- // GitHub Flavored Markdown task lists- input: ({ ...props }: any) => {- if (props.type === "checkbox") {- return (- <input- type="checkbox"- className="mr-2 h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500 disabled:cursor-not-allowed disabled:opacity-70"- disabled- {...props}- />- );- }- return <input {...props} />;- },- // Better list styling- ul: ({ children, ...props }: any) => (- <ul- className={`my-4 list-disc space-y-2 pl-6 ${- props.className?.includes("contains-task-list")- ? "list-none pl-0"- : ""- }`}- {...props}- >- {children}- </ul>- ),- ol: ({ children, ...props }) => (- <ol className="my-4 list-decimal space-y-2 pl-6" {...props}>- {children}- </ol>- ),- li: ({ children, ...props }: any) => (- <li- className={`text-gray-700 dark:text-gray-300 ${- props.className?.includes("task-list-item")- ? "flex items-start"- : ""- }`}- {...props}- >- {children}- </li>- ),- // Better heading styles- h1: ({ children, ...props }) => (- <h1- className="my-6 text-3xl font-bold text-gray-900 dark:text-gray-100"- {...props}- >- {children}- </h1>- ),- h2: ({ children, ...props }) => (- <h2- className="my-5 text-2xl font-semibold text-gray-800 dark:text-gray-200"- {...props}- >- {children}- </h2>- ),- h3: ({ children, ...props }) => (- <h3- className="my-4 text-xl font-semibold text-gray-800 dark:text-gray-200"- {...props}- >- {children}- </h3>- ),- h4: ({ children, ...props }) => (- <h4- className="my-3 text-lg font-medium text-gray-700 dark:text-gray-300"- {...props}- >- {children}- </h4>- ),- h5: ({ children, ...props }) => (- <h5- className="my-2 text-base font-medium text-gray-700 dark:text-gray-300"- {...props}- >- {children}- </h5>- ),- h6: ({ children, ...props }) => (- <h6- className="my-2 text-sm font-medium text-gray-600 dark:text-gray-400"- {...props}- >- {children}- </h6>- ),- // Horizontal rule- hr: ({ ...props }) => (- <hr- className="my-6 border-gray-300 dark:border-gray-700"- {...props}- />- ),- // Strikethrough (GFM)- del: ({ children, ...props }) => (- <del- className="text-gray-500 line-through dark:text-gray-500"- {...props}- >- {children}- </del>- ),- // Image handling- img: ({ src, alt, ...props }) => {- // Check if it's a video URL pattern- if (src && typeof src === "string" && isVideoUrl(src)) {- return renderVideoEmbed(src);- }-- return (- // eslint-disable-next-line @next/next/no-img-element- <img- src={src}- alt={alt}- className="my-4 h-auto max-w-full rounded-lg shadow-md"- loading="lazy"- {...props}- />- );- },- // Custom paragraph to handle standalone video URLs- p: ({ children, ...props }) => {- // Check if paragraph contains just a video URL- if (typeof children === "string" && isVideoUrl(children.trim())) {- return renderVideoEmbed(children.trim());- }-- // Check for video URLs in link children- if (React.Children.count(children) === 1) {- const child = React.Children.toArray(children)[0];- if (- React.isValidElement<{ href?: string }>(child) &&- child.type === "a"- ) {- const href = child.props.href;- if (href && isVideoUrl(href)) {- return renderVideoEmbed(href);- }- }- }-- return (- <p- className="my-3 leading-relaxed text-gray-700 dark:text-gray-300"- {...props}- >- {children}- </p>- );- },- }}+ components={MARKDOWN_COMPONENTS}>{markdownContent}</ReactMarkdown>diff --git a/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/VideoRenderer.tsx b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/VideoRenderer.tsxindex 624749cd18..f20b076c6e 100644--- a/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/VideoRenderer.tsx+++ b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/VideoRenderer.tsx@@ -1,4 +1,10 @@import React from "react";+import { YouTubeEmbed } from "@/components/molecules/YouTubeEmbed/YouTubeEmbed";+import {+ getYouTubeVideoId,+ getYouTubeWatchUrl,+ isYouTubeUrl,+} from "@/components/molecules/YouTubeEmbed/helpers";import {OutputRenderer,OutputMetadata,@@ -43,14 +49,10 @@ function guessMimeType(url: string): string | null {return extension ? mimeMap[extension] || null : null;}-const YOUTUBE_REGEX =- /^https?:\/\/(?:www\.)?(?:youtube\.com\/(?:watch\?.*v=|embed\/|v\/|shorts\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/;-const VIMEO_REGEX = /^https?:\/\/(?:www\.)?vimeo\.com\/(\d+)/;-function getYouTubeVideoID(url: string): string | null {- const match = url.match(YOUTUBE_REGEX);- return match ? match[1] : null;+function isYouTubeVideoURL(url: string): boolean {+ return /^https?:\/\//i.test(url) && getYouTubeVideoId(url) !== null;}function getVimeoVideoID(url: string): string | null {@@ -59,7 +61,7 @@ function getVimeoVideoID(url: string): string | null {}function isEmbeddableVideoURL(url: string): boolean {- return getYouTubeVideoID(url) !== null || getVimeoVideoID(url) !== null;+ return isYouTubeVideoURL(url) || getVimeoVideoID(url) !== null;}function canRenderVideo(value: unknown, metadata?: OutputMetadata): boolean {@@ -102,22 +104,32 @@ function renderVideo(): React.ReactNode {const videoUrl = String(value);- const youtubeID = getYouTubeVideoID(videoUrl);- if (youtubeID) {+ if (isYouTubeVideoURL(videoUrl)) {return (<div className="group relative aspect-video w-full">- <iframe- className="h-full w-full rounded-md border border-gray-200"- src={`https://www.youtube.com/embed/${youtubeID}`}- allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"- allowFullScreen- sandbox="allow-scripts allow-same-origin allow-presentation allow-fullscreen allow-popups"- title="YouTube video"+ <YouTubeEmbed+ url={videoUrl}+ className="rounded-md border border-gray-200"/></div>);}+ // Video metadata can bring any other YouTube page here. It stays a link,+ // like in markdown: a <video> would fetch it before consent.+ if (isYouTubeUrl(videoUrl)) {+ return (+ <a+ href={getYouTubeWatchUrl(videoUrl) ?? undefined}+ target="_blank"+ rel="noopener noreferrer"+ className="text-blue-600 underline"+ >+ {videoUrl}+ </a>+ );+ }+const vimeoID = getVimeoVideoID(videoUrl);if (vimeoID) {return (diff --git a/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/__tests__/MarkdownRenderer.test.tsx b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/__tests__/MarkdownRenderer.test.tsxindex ce0bd91e71..71e3b627a2 100644--- a/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/__tests__/MarkdownRenderer.test.tsx+++ b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/__tests__/MarkdownRenderer.test.tsx@@ -96,15 +96,13 @@ describe("MarkdownRenderer images", () => {);});- it("embeds an image whose URL is a YouTube link as an iframe", () => {+ it("loads nothing from YouTube for an image whose URL is a YouTube video until consent", () => {const container = renderMarkdown(- "",+ "",);expect(container.querySelector("img")).toBeNull();- expect(container.querySelector("iframe")?.getAttribute("src")).toBe(- "https://www.youtube.com/embed/abc123",- );+ expect(container.querySelector("iframe")).toBeNull();});it("renders any other image as an image", () => {diff --git a/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/__tests__/youtube-embeds.test.tsx b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/__tests__/youtube-embeds.test.tsxnew file mode 100644index 0000000000..6201b38b21--- /dev/null+++ b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/__tests__/youtube-embeds.test.tsx@@ -0,0 +1,196 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ configureCookiebot,+ installCookiebot,+ removeCookiebot,+} from "@/tests/integrations/cookiebot";+import { fireEvent, render, screen } from "@/tests/integrations/test-utils";+import { markdownRenderer } from "../MarkdownRenderer";+import { videoRenderer } from "../VideoRenderer";++const VIDEO_ID = "dQw4w9WgXcQ";+const WATCH_URL = `https://www.youtube.com/watch?v=${VIDEO_ID}`;+const NOCOOKIE_URL = `https://www.youtube-nocookie.com/embed/${VIDEO_ID}`;++function renderMarkdown(markdown: string) {+ return render(+ <>{markdownRenderer.render(markdown, { mimeType: "text/markdown" })}</>,+ ).container;+}++function renderVideo(url: string, metadata?: { type: "video" }) {+ return render(<>{videoRenderer.render(url, metadata)}</>).container;+}++afterEach(() => {+ removeCookiebot();+ vi.unstubAllEnvs();+});++describe("YouTube links in run output", () => {+ it.each([+ ["markdown", () => renderMarkdown(`# Demo\n\n`)],+ ["video", () => renderVideo(`https://youtu.be/${VIDEO_ID}`)],+ ])(+ "shows the cookie notice in %s output without marketing consent",+ (_name, renderOutput) => {+ configureCookiebot();+ installCookiebot({ marketing: false });++ const container = renderOutput();++ expect(container.querySelector("iframe")).toBeNull();+ expect(+ screen.getByRole("link", { name: "Watch on YouTube" }),+ ).toBeDefined();+ },+ );++ it.each([+ ["markdown", () => renderMarkdown(`# Demo\n\n`)],+ ["video", () => renderVideo(`https://youtu.be/${VIDEO_ID}`)],+ ])(+ "embeds the privacy-enhanced player in %s output with consent",+ (_name, renderOutput) => {+ configureCookiebot();+ installCookiebot({ marketing: true });++ const container = renderOutput();++ expect(container.querySelector("iframe")?.getAttribute("src")).toBe(+ NOCOOKIE_URL,+ );+ },+ );++ it("drops the share tracking from a youtu.be link in markdown", () => {+ configureCookiebot();+ installCookiebot({ marketing: true });++ const container = renderMarkdown(+ `# Demo\n\n`,+ );++ expect(container.querySelector("iframe")?.getAttribute("src")).toBe(+ NOCOOKIE_URL,+ );+ });++ it("keeps a YouTube thumbnail in markdown as an image", () => {+ const thumbnail = `https://img.youtube.com/vi/${VIDEO_ID}/0.jpg`;++ const container = renderMarkdown(`# Demo\n\n`);++ expect(container.querySelector("img")?.getAttribute("src")).toBe(thumbnail);+ expect(screen.queryByRole("link", { name: "Watch on YouTube" })).toBeNull();+ });++ it("keeps a YouTube channel link in markdown as a plain link", () => {+ configureCookiebot();+ installCookiebot({ marketing: true });+ const channel = "https://www.youtube.com/@somechannel";++ const container = renderMarkdown(+ `# Demo\n\nSee [the channel](${channel}) and `,+ );++ const links = screen.getAllByRole("link", { name: /channel/i });+ expect(links.map((link) => link.getAttribute("href"))).toEqual([+ channel,+ channel,+ ]);+ expect(container.querySelector("img, video, iframe")).toBeNull();+ expect(+ screen.queryByText("This video can only be watched on YouTube."),+ ).toBeNull();+ });++ it("links a YouTube channel given as video output instead of playing it", () => {+ configureCookiebot();+ installCookiebot({ marketing: true });+ const channel = "https://www.youtube.com/@somechannel";++ expect(videoRenderer.canRender(channel)).toBe(false);+ const container = renderVideo(channel, { type: "video" });++ expect(container.querySelector("video, iframe, img")).toBeNull();+ expect(screen.getByRole("link", { name: channel })).toBeDefined();+ });++ it("keeps one link for a linked image of a YouTube channel", () => {+ configureCookiebot();+ installCookiebot({ marketing: true });+ const channel = "https://www.youtube.com/@somechannel";++ const container = renderMarkdown(+ `# Demo\n\n[](${channel})`,+ );++ const anchors = container.querySelectorAll(`a[href="${channel}"]`);+ expect(anchors).toHaveLength(1);+ expect(anchors[0].getAttribute("href")).toBe(channel);+ expect(anchors[0].textContent).toBe("Channel");+ expect(container.querySelector("a a, img, video, iframe")).toBeNull();+ });++ it("shows only the text of a linked YouTube video image", () => {+ configureCookiebot();+ installCookiebot({ marketing: false });++ const container = renderMarkdown(+ `# Demo\n\n[](https://example.com/page)`,+ );++ const anchor = container.querySelector(+ 'a[href="https://example.com/page"]',+ );+ expect(anchor?.textContent).toBe("Watch the demo");+ expect(anchor?.querySelector("a, button, iframe, video, img")).toBeNull();+ });++ it("gives a YouTube channel image written without a scheme a full link", () => {+ const container = renderMarkdown(`# Demo\n\n`);++ expect(+ container.querySelector('a[href="https://youtube.com/@foo"]')+ ?.textContent,+ ).toBe("Channel");+ expect(container.querySelector("img")).toBeNull();+ });++ describe("when the output around the player re-renders", () => {+ const markdown = `# Demo\n\n`;++ function renderInParent(pass: number) {+ return (+ <div data-pass={pass}>+ {markdownRenderer.render(markdown, { mimeType: "text/markdown" })}+ </div>+ );+ }++ it("keeps the same player element", () => {+ configureCookiebot();+ installCookiebot({ marketing: true });+ const { container, rerender } = render(renderInParent(1));+ const player = container.querySelector("iframe");+ expect(player).not.toBeNull();++ rerender(renderInParent(2));++ expect(container.querySelector("iframe")).toBe(player);+ });++ it("keeps a video loaded with Load video", () => {+ vi.stubEnv("NEXT_PUBLIC_COOKIEBOT_CBID", "");+ const { container, rerender } = render(renderInParent(1));+ fireEvent.click(screen.getByRole("button", { name: "Load video" }));+ const player = container.querySelector("iframe");+ expect(player).not.toBeNull();++ rerender(renderInParent(2));++ expect(container.querySelector("iframe")).toBe(player);+ });+ });+});diff --git a/autogpt_platform/frontend/src/components/molecules/YouTubeEmbed/YouTubeEmbed.stories.tsx b/autogpt_platform/frontend/src/components/molecules/YouTubeEmbed/YouTubeEmbed.stories.tsxnew file mode 100644index 0000000000..04e0047cd9--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/YouTubeEmbed/YouTubeEmbed.stories.tsx@@ -0,0 +1,29 @@+import type { Meta, StoryObj } from "@storybook/nextjs";+import { YouTubeEmbed } from "./YouTubeEmbed";++const meta = {+ title: "Molecules/YouTubeEmbed",+ component: YouTubeEmbed,+ parameters: {+ layout: "padded",+ },+ tags: ["autodocs"],+ decorators: [+ (Story) => (+ <div className="aspect-video w-full max-w-2xl overflow-hidden rounded-lg">+ <Story />+ </div>+ ),+ ],+} satisfies Meta<typeof YouTubeEmbed>;++export default meta;+type Story = StoryObj<typeof meta>;++// Storybook has no consent banner, so this shows the notice with "Load video".+export const WithoutConsent: Story = {+ args: {+ url: "https://www.youtube.com/watch?v=dQw4w9WgXcQ",+ title: "Demo video",+ },+};diff --git a/autogpt_platform/frontend/src/components/molecules/YouTubeEmbed/YouTubeEmbed.tsx b/autogpt_platform/frontend/src/components/molecules/YouTubeEmbed/YouTubeEmbed.tsxnew file mode 100644index 0000000000..a1ff917b85--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/YouTubeEmbed/YouTubeEmbed.tsx@@ -0,0 +1,96 @@+"use client";++import { Button } from "@/components/atoms/Button/Button";+import { Icon } from "@/components/atoms/Icon/Icon";+import { Text } from "@/components/atoms/Text/Text";+import { cn } from "@/lib/utils";+import { YoutubeIcon } from "@hugeicons/core-free-icons";+import { getNoticeText } from "./helpers";+import { useYouTubeEmbed } from "./useYouTubeEmbed";++interface Props {+ /** Any YouTube link; one that names no single video only gets a link out. */+ url: string;+ title?: string;+ className?: string;+}++// YouTube sets advertising cookies (Cookiebot's Marketing category) as soon as+// its player loads, so the iframe waits for that consent. Nothing else here+// requests anything from YouTube.+export function YouTubeEmbed({+ url,+ title = "YouTube video",+ className,+}: Props) {+ const {+ videoId,+ embedUrl,+ watchUrl,+ showPlayer,+ canLoadOnce,+ canAllowHere,+ settingsReady,+ openSettings,+ loadVideo,+ } = useYouTubeEmbed(url);++ if (showPlayer && embedUrl) {+ return (+ <iframe+ className={cn("h-full w-full", className)}+ src={embedUrl}+ title={title}+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"+ allowFullScreen+ sandbox="allow-scripts allow-same-origin allow-presentation allow-popups allow-popups-to-escape-sandbox"+ />+ );+ }++ return (+ <div+ role="group"+ aria-label={title}+ className={cn(+ "flex h-full w-full flex-col items-center justify-center gap-3 overflow-auto bg-zinc-100 p-4 text-center",+ className,+ )}+ >+ <Icon icon={YoutubeIcon} size={28} className="text-zinc-400" />+ <Text variant="body" tone="secondary" className="max-w-sm">+ {getNoticeText({ hasVideoId: videoId !== null, canAllowHere })}+ </Text>+ <div className="flex flex-wrap items-center justify-center gap-2">+ {watchUrl && (+ <Button+ as="NextLink"+ href={watchUrl}+ target="_blank"+ rel="noopener noreferrer"+ variant="secondary"+ size="small"+ leadingIcon={YoutubeIcon}+ >+ Watch on YouTube+ </Button>+ )}+ {canLoadOnce && (+ <Button variant="primary" size="small" onClick={loadVideo}>+ Load video+ </Button>+ )}+ {canAllowHere && (+ <Button+ variant="primary"+ size="small"+ disabled={!settingsReady}+ onClick={openSettings}+ >+ Cookie settings+ </Button>+ )}+ </div>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/components/molecules/YouTubeEmbed/__tests__/YouTubeEmbed.test.tsx b/autogpt_platform/frontend/src/components/molecules/YouTubeEmbed/__tests__/YouTubeEmbed.test.tsxnew file mode 100644index 0000000000..b504207984--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/YouTubeEmbed/__tests__/YouTubeEmbed.test.tsx@@ -0,0 +1,191 @@+import { afterEach, describe, expect, test, vi } from "vitest";+import {+ answerCookiebot,+ configureCookiebot,+ installCookiebot,+ removeCookiebot,+} from "@/tests/integrations/cookiebot";+import {+ act,+ fireEvent,+ render,+ screen,+} from "@/tests/integrations/test-utils";+import { YouTubeEmbed } from "../YouTubeEmbed";++const VIDEO_ID = "dQw4w9WgXcQ";+const VIDEO_URL = `https://www.youtube.com/watch?v=${VIDEO_ID}`;+const NOTICE = "YouTube sets advertising cookies when this video loads.";++function renderEmbed() {+ return render(<YouTubeEmbed url={VIDEO_URL} title="Demo video" />);+}++function getPlayer(container: HTMLElement) {+ return container.querySelector("iframe");+}++afterEach(() => {+ removeCookiebot();+ vi.unstubAllEnvs();+ vi.restoreAllMocks();+});++describe("YouTubeEmbed", () => {+ test("loads the privacy-enhanced player once marketing cookies are allowed", () => {+ configureCookiebot();+ installCookiebot({ marketing: true });++ const { container } = renderEmbed();++ const player = getPlayer(container);+ expect(player?.getAttribute("src")).toBe(+ `https://www.youtube-nocookie.com/embed/${VIDEO_ID}`,+ );+ expect(player?.getAttribute("title")).toBe("Demo video");+ expect(player?.hasAttribute("allowfullscreen")).toBe(true);+ expect(player?.getAttribute("sandbox")).toBe(+ "allow-scripts allow-same-origin allow-presentation allow-popups allow-popups-to-escape-sandbox",+ );+ expect(screen.queryByText(NOTICE, { exact: false })).toBeNull();+ });++ test("shows a notice instead of the player without marketing consent", () => {+ configureCookiebot();+ installCookiebot({ statistics: true, marketing: false });++ const { container } = renderEmbed();++ expect(getPlayer(container)).toBeNull();+ expect(+ screen.getByText(+ "YouTube sets advertising cookies when this video loads. To watch it here, allow marketing cookies.",+ ),+ ).toBeDefined();+ const watchLink = screen.getByRole("link", { name: "Watch on YouTube" });+ expect(watchLink.getAttribute("href")).toBe(+ `https://www.youtube.com/watch?v=${VIDEO_ID}`,+ );+ expect(watchLink.getAttribute("target")).toBe("_blank");+ expect(watchLink.getAttribute("rel")).toContain("noopener");+ });++ test("opens the cookie settings from the notice", () => {+ configureCookiebot();+ const { renew } = installCookiebot({ marketing: false });++ renderEmbed();+ fireEvent.click(screen.getByRole("button", { name: "Cookie settings" }));++ expect(renew).toHaveBeenCalledOnce();+ });++ test("plays without a reload when the visitor allows marketing cookies", () => {+ configureCookiebot();+ installCookiebot({ marketing: false });+ const { container } = renderEmbed();+ expect(getPlayer(container)).toBeNull();++ act(() => answerCookiebot({ statistics: true, marketing: true }));++ expect(getPlayer(container)?.getAttribute("src")).toBe(+ `https://www.youtube-nocookie.com/embed/${VIDEO_ID}`,+ );+ });++ test("removes the player when the visitor takes marketing consent back", () => {+ configureCookiebot();+ installCookiebot({ marketing: true });+ const { container } = renderEmbed();+ expect(getPlayer(container)).not.toBeNull();++ act(() => answerCookiebot({ statistics: true, marketing: false }));++ expect(getPlayer(container)).toBeNull();+ expect(+ screen.getByRole("link", { name: "Watch on YouTube" }),+ ).toBeDefined();+ });++ test("keeps the settings button disabled until the consent banner loads", () => {+ configureCookiebot();+ vi.spyOn(document, "readyState", "get").mockReturnValue("loading");++ const { container } = renderEmbed();++ expect(getPlayer(container)).toBeNull();+ const settings = screen.getByRole("button", { name: "Cookie settings" });+ expect(settings.hasAttribute("disabled")).toBe(true);+ });++ test("lets the viewer load one video when there is no consent banner", () => {+ vi.stubEnv("NEXT_PUBLIC_COOKIEBOT_CBID", "");++ const { container } = renderEmbed();++ expect(getPlayer(container)).toBeNull();+ expect(screen.getByText(NOTICE)).toBeDefined();+ expect(+ screen.queryByRole("button", { name: "Cookie settings" }),+ ).toBeNull();++ fireEvent.click(screen.getByRole("button", { name: "Load video" }));++ expect(getPlayer(container)?.getAttribute("src")).toBe(+ `https://www.youtube-nocookie.com/embed/${VIDEO_ID}`,+ );+ });++ test("asks again before loading a different video without a banner", () => {+ vi.stubEnv("NEXT_PUBLIC_COOKIEBOT_CBID", "");+ const { container, rerender } = renderEmbed();+ fireEvent.click(screen.getByRole("button", { name: "Load video" }));+ expect(getPlayer(container)).not.toBeNull();++ rerender(+ <YouTubeEmbed url="https://youtu.be/aaaaaaaaaaa" title="Other video" />,+ );++ expect(getPlayer(container)).toBeNull();+ expect(screen.getByRole("button", { name: "Load video" })).toBeDefined();+ });++ test("only links to YouTube when the consent banner could not load", () => {+ configureCookiebot();+ vi.spyOn(document, "readyState", "get").mockReturnValue("complete");++ const { container } = renderEmbed();++ expect(getPlayer(container)).toBeNull();+ expect(screen.getByText(NOTICE)).toBeDefined();+ expect(+ screen.getByRole("link", { name: "Watch on YouTube" }),+ ).toBeDefined();+ expect(+ screen.queryByRole("button", { name: "Cookie settings" }),+ ).toBeNull();+ expect(screen.queryByRole("button", { name: "Load video" })).toBeNull();+ });++ test("only links out for a YouTube link that names no single video", () => {+ configureCookiebot();+ installCookiebot({ marketing: true });++ const { container } = render(+ <YouTubeEmbed url="https://www.youtube.com/@somechannel" />,+ );++ expect(getPlayer(container)).toBeNull();+ expect(+ screen.getByText("This video can only be watched on YouTube."),+ ).toBeDefined();+ expect(+ screen+ .getByRole("link", { name: "Watch on YouTube" })+ .getAttribute("href"),+ ).toBe("https://www.youtube.com/@somechannel");+ expect(+ screen.queryByRole("button", { name: "Cookie settings" }),+ ).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/components/molecules/YouTubeEmbed/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/components/molecules/YouTubeEmbed/__tests__/helpers.test.tsnew file mode 100644index 0000000000..f000d62120--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/YouTubeEmbed/__tests__/helpers.test.ts@@ -0,0 +1,148 @@+import { describe, expect, it } from "vitest";+import {+ getYouTubeEmbedUrl,+ getYouTubeVideoId,+ getYouTubeWatchUrl,+ isYouTubeImageUrl,+ isYouTubeUrl,+} from "../helpers";++const ID = "dQw4w9WgXcQ";++describe("getYouTubeVideoId", () => {+ it.each([+ `https://www.youtube.com/watch?v=${ID}`,+ `https://youtube.com/watch?v=${ID}&t=30s`,+ `https://www.youtube.com/watch?feature=shared&v=${ID}`,+ `https://m.youtube.com/watch?v=${ID}`,+ `https://music.youtube.com/watch?v=${ID}&list=abc`,+ `https://youtu.be/${ID}`,+ `https://youtu.be/${ID}?si=abc123`,+ `https://www.youtube.com/shorts/${ID}`,+ `https://youtube.com/shorts/${ID}?feature=share`,+ `https://www.youtube.com/live/${ID}`,+ `https://www.youtube.com/embed/${ID}`,+ `https://www.youtube.com/v/${ID}`,+ `https://www.youtube-nocookie.com/embed/${ID}`,+ `www.youtube.com/watch?v=${ID}`,+ `youtu.be/${ID}`,+ ])("finds the video in %s", (url) => {+ expect(getYouTubeVideoId(url)).toBe(ID);+ });++ it.each([+ "https://www.youtube.com/@somechannel",+ "https://www.youtube.com/playlist?list=PL123",+ "https://www.youtube.com/watch?v=short",+ "https://www.youtube.com/shorts/",+ "https://www.youtube.com/embed/videoseries?list=PL123",+ "https://www.youtube.com/embed/live_stream?channel=UC123",+ `https://youtube.com.example.com/watch?v=${ID}`,+ `https://example.com/watch?v=${ID}`,+ `javascript:alert(1)//youtu.be/${ID}`,+ ])("finds no video in %s", (url) => {+ expect(getYouTubeVideoId(url)).toBeNull();+ });+});++describe("isYouTubeUrl", () => {+ it("accepts any YouTube page", () => {+ expect(isYouTubeUrl("https://www.youtube.com/@somechannel")).toBe(true);+ expect(isYouTubeUrl("https://m.youtube.com/playlist?list=PL1")).toBe(true);+ });++ it("rejects other hosts that only look like YouTube", () => {+ expect(isYouTubeUrl("https://youtube.com.example.com/x")).toBe(false);+ expect(isYouTubeUrl("https://notyoutube.com/watch?v=x")).toBe(false);+ expect(isYouTubeUrl("https://example.com/video.mp4")).toBe(false);+ });++ it("leaves YouTube image hosts to render as images", () => {+ expect(isYouTubeUrl(`https://img.youtube.com/vi/${ID}/0.jpg`)).toBe(false);+ expect(isYouTubeUrl(`https://i.ytimg.com/vi/${ID}/hqdefault.jpg`)).toBe(+ false,+ );+ });+});++describe("getYouTubeWatchUrl", () => {+ it("links a video to its watch page", () => {+ expect(getYouTubeWatchUrl(`https://youtube.com/shorts/${ID}`)).toBe(+ `https://www.youtube.com/watch?v=${ID}`,+ );+ });++ it("keeps any other YouTube link as given", () => {+ expect(getYouTubeWatchUrl("youtube.com/@somechannel")).toBe(+ "https://youtube.com/@somechannel",+ );+ });++ it("gives nothing for a link outside YouTube", () => {+ expect(getYouTubeWatchUrl("https://example.com/x")).toBeNull();+ });+});++describe("start time", () => {+ it.each([+ [`https://youtu.be/${ID}?t=90`, 90],+ [`https://www.youtube.com/watch?v=${ID}&t=1m30s`, 90],+ [`https://www.youtube.com/watch?v=${ID}&t=1h2m3s`, 3723],+ [`https://www.youtube.com/embed/${ID}?start=45`, 45],+ ])("keeps the start of %s", (url, seconds) => {+ expect(getYouTubeEmbedUrl(url)).toBe(+ `https://www.youtube-nocookie.com/embed/${ID}?start=${seconds}`,+ );+ expect(getYouTubeWatchUrl(url)).toBe(+ `https://www.youtube.com/watch?v=${ID}&t=${seconds}s`,+ );+ });++ it("drops a start it can't read and every other parameter", () => {+ const url = `https://youtu.be/${ID}?t=soon&si=tracking`;+ expect(getYouTubeEmbedUrl(url)).toBe(+ `https://www.youtube-nocookie.com/embed/${ID}`,+ );+ expect(getYouTubeWatchUrl(url)).toBe(+ `https://www.youtube.com/watch?v=${ID}`,+ );+ });+});++describe("isYouTubeImageUrl", () => {+ it("recognises YouTube image hosts", () => {+ expect(isYouTubeImageUrl(`https://img.youtube.com/vi/${ID}/0.jpg`)).toBe(+ true,+ );+ expect(isYouTubeImageUrl(`https://i.ytimg.com/vi/${ID}/0.jpg`)).toBe(true);+ expect(isYouTubeImageUrl(`https://i3.ytimg.com/vi/${ID}/0.jpg`)).toBe(true);+ });++ it("ignores YouTube pages and other hosts", () => {+ expect(isYouTubeImageUrl(`https://www.youtube.com/watch?v=${ID}`)).toBe(+ false,+ );+ expect(isYouTubeImageUrl("https://ytimg.com.example.com/a.jpg")).toBe(+ false,+ );+ expect(isYouTubeImageUrl("https://cdn.test/one.png")).toBe(false);+ });+});++describe("hosts written with a trailing dot", () => {+ it.each([+ [`https://www.youtube.com./watch?v=${ID}`, ID],+ [`https://YOUTUBE.COM./shorts/${ID}`, ID],+ [`https://youtu.be./${ID}`, ID],+ ])("still finds the video in %s", (url, id) => {+ expect(isYouTubeUrl(url)).toBe(true);+ expect(getYouTubeVideoId(url)).toBe(id);+ });++ it.each([+ `https://img.youtube.com./vi/${ID}/0.jpg`,+ `https://i.ytimg.com./vi/${ID}/mqdefault.jpg`,+ ])("still sees %s as a YouTube image", (url) => {+ expect(isYouTubeImageUrl(url)).toBe(true);+ });+});diff --git a/autogpt_platform/frontend/src/components/molecules/YouTubeEmbed/helpers.ts b/autogpt_platform/frontend/src/components/molecules/YouTubeEmbed/helpers.tsnew file mode 100644index 0000000000..959457f762--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/YouTubeEmbed/helpers.ts@@ -0,0 +1,137 @@+const VIDEO_ID = /^[A-Za-z0-9_-]{11}$/;+// Paths that carry the ID as the next segment: /embed/ID, /shorts/ID, ...+const ID_PATH_PREFIXES = new Set(["embed", "v", "e", "shorts", "live"]);+// Embed paths for a playlist or a channel's stream, not one video, though+// they are 11 characters long like an ID.+const NOT_VIDEO_IDS = new Set(["videoseries", "live_stream"]);++function parseHttpUrl(url: string): URL | null {+ const trimmed = url.trim();+ const withScheme = /^[a-z][a-z\d+.-]*:\/\//i.test(trimmed)+ ? trimmed+ : `https://${trimmed}`;+ try {+ const parsed = new URL(withScheme);+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {+ return null;+ }+ // "i.ytimg.com." is the same host as "i.ytimg.com" and URL keeps the dot,+ // so host checks would otherwise miss it.+ parsed.hostname = parsed.hostname.toLowerCase().replace(/\.$/, "");+ return parsed;+ } catch {+ return null;+ }+}++// Pages that play a video. Image hosts (img.youtube.com, i.ytimg.com) are+// left alone, so a thumbnail stays an image.+const YOUTUBE_PAGE_HOSTS = new Set([+ "youtube.com",+ "www.youtube.com",+ "m.youtube.com",+ "music.youtube.com",+ "youtube-nocookie.com",+ "www.youtube-nocookie.com",+ "youtu.be",+ "www.youtu.be",+]);++function isYouTubeHost(hostname: string): boolean {+ return YOUTUBE_PAGE_HOSTS.has(hostname.toLowerCase());+}++function parseYouTubeUrl(url: string): URL | null {+ const parsed = parseHttpUrl(url);+ return parsed && isYouTubeHost(parsed.hostname) ? parsed : null;+}++/** An image served by YouTube, such as a video thumbnail. */+export function isYouTubeImageUrl(url: string): boolean {+ const host = parseHttpUrl(url)?.hostname.toLowerCase();+ if (!host) return false;+ return (+ host === "img.youtube.com" ||+ host === "ytimg.com" ||+ host.endsWith(".ytimg.com")+ );+}++/** Any link to YouTube, whether or not it names a single video. */+export function isYouTubeUrl(url: string): boolean {+ return parseYouTubeUrl(url) !== null;+}++export function getYouTubeVideoId(url: string): string | null {+ const parsed = parseYouTubeUrl(url);+ if (!parsed) return null;+ const segments = parsed.pathname.split("/").filter(Boolean);+ const host = parsed.hostname.toLowerCase();+ let candidate: string | null | undefined;+ if (host === "youtu.be" || host === "www.youtu.be") {+ candidate = segments[0];+ } else if (segments[0] === "watch") {+ candidate = parsed.searchParams.get("v");+ } else if (segments[0] && ID_PATH_PREFIXES.has(segments[0])) {+ candidate = segments[1];+ }+ return candidate && VIDEO_ID.test(candidate) && !NOT_VIDEO_IDS.has(candidate)+ ? candidate+ : null;+}++/** Where the link asks playback to start (`t=90`, `t=1m30s`, `start=90`). */+export function getYouTubeStartSeconds(url: string): number | null {+ const parsed = parseYouTubeUrl(url);+ const value =+ parsed?.searchParams.get("t") ?? parsed?.searchParams.get("start");+ if (!value) return null;+ const match = value.match(/^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s?)?$/);+ if (!match) return null;+ const [, hours = "0", minutes = "0", seconds = "0"] = match;+ const total = Number(hours) * 3600 + Number(minutes) * 60 + Number(seconds);+ return total > 0 ? total : null;+}++// Privacy-enhanced mode: YouTube sets no cookies until the viewer presses play.+export function getYouTubeLinks(url: string) {+ const videoId = getYouTubeVideoId(url);+ if (!videoId) {+ return {+ videoId,+ embedUrl: null,+ watchUrl: parseYouTubeUrl(url)?.toString() ?? null,+ };+ }+ const start = getYouTubeStartSeconds(url);+ const id = encodeURIComponent(videoId);+ const embedUrl = `https://www.youtube-nocookie.com/embed/${id}`;+ const watchUrl = `https://www.youtube.com/watch?v=${id}`;+ return {+ videoId,+ embedUrl: start ? `${embedUrl}?start=${start}` : embedUrl,+ watchUrl: start ? `${watchUrl}&t=${start}s` : watchUrl,+ };+}++export function getYouTubeEmbedUrl(url: string): string | null {+ return getYouTubeLinks(url).embedUrl;+}++export function getYouTubeWatchUrl(url: string): string | null {+ return getYouTubeLinks(url).watchUrl;+}++export function getNoticeText({+ hasVideoId,+ canAllowHere,+}: {+ hasVideoId: boolean;+ canAllowHere: boolean;+}): string {+ if (!hasVideoId) return "This video can only be watched on YouTube.";+ if (canAllowHere) {+ return "YouTube sets advertising cookies when this video loads. To watch it here, allow marketing cookies.";+ }+ return "YouTube sets advertising cookies when this video loads.";+}diff --git a/autogpt_platform/frontend/src/components/molecules/YouTubeEmbed/useYouTubeEmbed.ts b/autogpt_platform/frontend/src/components/molecules/YouTubeEmbed/useYouTubeEmbed.tsnew file mode 100644index 0000000000..a793aa7471--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/YouTubeEmbed/useYouTubeEmbed.ts@@ -0,0 +1,46 @@+"use client";++import { useState } from "react";+import {+ isConsentManagerConfigured,+ openConsentSettings,+} from "@/services/consent/consent";+import {+ useConsent,+ useConsentManagerStatus,+} from "@/services/consent/useConsent";+import { getYouTubeLinks } from "./helpers";++export function useYouTubeEmbed(url: string) {+ const consent = useConsent();+ const managerStatus = useConsentManagerStatus();+ // Without a consent banner (self-hosted installs) the viewer can load a+ // video on purpose after reading the notice. The choice covers that one+ // video only, so switching to another asks again.+ const [loadedVideoId, setLoadedVideoId] = useState<string | null>(null);++ const { videoId, embedUrl, watchUrl } = getYouTubeLinks(url);+ // With a banner configured, consent only ever comes from it, even while+ // its script loads or after a blocker stopped it.+ const hasConsentBanner = isConsentManagerConfigured();+ const loadedOnRequest =+ !hasConsentBanner && videoId !== null && loadedVideoId === videoId;++ function loadVideo() {+ setLoadedVideoId(videoId);+ }++ return {+ videoId,+ embedUrl,+ watchUrl,+ showPlayer: consent.advertising || loadedOnRequest,+ canLoadOnce: !hasConsentBanner && videoId !== null,+ // The banner can be opened from the notice (a blocker may have stopped it).+ canAllowHere:+ videoId !== null && hasConsentBanner && managerStatus !== "unavailable",+ settingsReady: managerStatus === "ready",+ openSettings: openConsentSettings,+ loadVideo,+ };+}